You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

65 lines
1.9 KiB

  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. package profile
  15. import (
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. )
  20. // SampleIndexByName returns the appropriate index for a value of sample index.
  21. // If numeric, it returns the number, otherwise it looks up the text in the
  22. // profile sample types.
  23. func (p *Profile) SampleIndexByName(sampleIndex string) (int, error) {
  24. if sampleIndex == "" {
  25. if dst := p.DefaultSampleType; dst != "" {
  26. for i, t := range sampleTypes(p) {
  27. if t == dst {
  28. return i, nil
  29. }
  30. }
  31. }
  32. // By default select the last sample value
  33. return len(p.SampleType) - 1, nil
  34. }
  35. if i, err := strconv.Atoi(sampleIndex); err == nil {
  36. if i < 0 || i >= len(p.SampleType) {
  37. return 0, fmt.Errorf("sample_index %s is outside the range [0..%d]", sampleIndex, len(p.SampleType)-1)
  38. }
  39. return i, nil
  40. }
  41. // Remove the inuse_ prefix to support legacy pprof options
  42. // "inuse_space" and "inuse_objects" for profiles containing types
  43. // "space" and "objects".
  44. noInuse := strings.TrimPrefix(sampleIndex, "inuse_")
  45. for i, t := range p.SampleType {
  46. if t.Type == sampleIndex || t.Type == noInuse {
  47. return i, nil
  48. }
  49. }
  50. return 0, fmt.Errorf("sample_index %q must be one of: %v", sampleIndex, sampleTypes(p))
  51. }
  52. func sampleTypes(p *Profile) []string {
  53. types := make([]string, len(p.SampleType))
  54. for i, t := range p.SampleType {
  55. types[i] = t.Type
  56. }
  57. return types
  58. }