proc_ns.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2018 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package procfs
  14. import (
  15. "fmt"
  16. "os"
  17. "strconv"
  18. "strings"
  19. )
  20. // Namespace represents a single namespace of a process.
  21. type Namespace struct {
  22. Type string // Namespace type.
  23. Inode uint32 // Inode number of the namespace. If two processes are in the same namespace their inodes will match.
  24. }
  25. // Namespaces contains all of the namespaces that the process is contained in.
  26. type Namespaces map[string]Namespace
  27. // Namespaces reads from /proc/<pid>/ns/* to get the namespaces of which the
  28. // process is a member.
  29. func (p Proc) Namespaces() (Namespaces, error) {
  30. d, err := os.Open(p.path("ns"))
  31. if err != nil {
  32. return nil, err
  33. }
  34. defer d.Close()
  35. names, err := d.Readdirnames(-1)
  36. if err != nil {
  37. return nil, fmt.Errorf("failed to read contents of ns dir: %w", err)
  38. }
  39. ns := make(Namespaces, len(names))
  40. for _, name := range names {
  41. target, err := os.Readlink(p.path("ns", name))
  42. if err != nil {
  43. return nil, err
  44. }
  45. fields := strings.SplitN(target, ":", 2)
  46. if len(fields) != 2 {
  47. return nil, fmt.Errorf("failed to parse namespace type and inode from %q", target)
  48. }
  49. typ := fields[0]
  50. inode, err := strconv.ParseUint(strings.Trim(fields[1], "[]"), 10, 32)
  51. if err != nil {
  52. return nil, fmt.Errorf("failed to parse inode from %q: %w", fields[1], err)
  53. }
  54. ns[name] = Namespace{typ, uint32(inode)}
  55. }
  56. return ns, nil
  57. }