podman
1// Copyright 2016 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package profile16
17import (18"fmt"19"strconv"20"strings"21)
22
23// SampleIndexByName returns the appropriate index for a value of sample index.
24// If numeric, it returns the number, otherwise it looks up the text in the
25// profile sample types.
26func (p *Profile) SampleIndexByName(sampleIndex string) (int, error) {27if sampleIndex == "" {28if dst := p.DefaultSampleType; dst != "" {29for i, t := range sampleTypes(p) {30if t == dst {31return i, nil32}33}34}35// By default select the last sample value36return len(p.SampleType) - 1, nil37}38if i, err := strconv.Atoi(sampleIndex); err == nil {39if i < 0 || i >= len(p.SampleType) {40return 0, fmt.Errorf("sample_index %s is outside the range [0..%d]", sampleIndex, len(p.SampleType)-1)41}42return i, nil43}44
45// Remove the inuse_ prefix to support legacy pprof options46// "inuse_space" and "inuse_objects" for profiles containing types47// "space" and "objects".48noInuse := strings.TrimPrefix(sampleIndex, "inuse_")49for i, t := range p.SampleType {50if t.Type == sampleIndex || t.Type == noInuse {51return i, nil52}53}54
55return 0, fmt.Errorf("sample_index %q must be one of: %v", sampleIndex, sampleTypes(p))56}
57
58func sampleTypes(p *Profile) []string {59types := make([]string, len(p.SampleType))60for i, t := range p.SampleType {61types[i] = t.Type62}63return types64}
65