thread.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2022 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. fsi "github.com/prometheus/procfs/internal/fs"
  19. )
  20. // Provide access to /proc/PID/task/TID files, for thread specific values. Since
  21. // such files have the same structure as /proc/PID/ ones, the data structures
  22. // and the parsers for the latter may be reused.
  23. // AllThreads returns a list of all currently available threads under /proc/PID.
  24. func AllThreads(pid int) (Procs, error) {
  25. fs, err := NewFS(DefaultMountPoint)
  26. if err != nil {
  27. return Procs{}, err
  28. }
  29. return fs.AllThreads(pid)
  30. }
  31. // AllThreads returns a list of all currently available threads for PID.
  32. func (fs FS) AllThreads(pid int) (Procs, error) {
  33. taskPath := fs.proc.Path(strconv.Itoa(pid), "task")
  34. d, err := os.Open(taskPath)
  35. if err != nil {
  36. return Procs{}, err
  37. }
  38. defer d.Close()
  39. names, err := d.Readdirnames(-1)
  40. if err != nil {
  41. return Procs{}, fmt.Errorf("%s: could not read %q: %w", ErrFileRead, d.Name(), err)
  42. }
  43. t := Procs{}
  44. for _, n := range names {
  45. tid, err := strconv.ParseInt(n, 10, 64)
  46. if err != nil {
  47. continue
  48. }
  49. t = append(t, Proc{PID: int(tid), fs: FS{fsi.FS(taskPath), fs.isReal}})
  50. }
  51. return t, nil
  52. }
  53. // Thread returns a process for a given PID, TID.
  54. func (fs FS) Thread(pid, tid int) (Proc, error) {
  55. taskPath := fs.proc.Path(strconv.Itoa(pid), "task")
  56. if _, err := os.Stat(taskPath); err != nil {
  57. return Proc{}, err
  58. }
  59. return Proc{PID: tid, fs: FS{fsi.FS(taskPath), fs.isReal}}, nil
  60. }
  61. // Thread returns a process for a given TID of Proc.
  62. func (proc Proc) Thread(tid int) (Proc, error) {
  63. tfs := FS{fsi.FS(proc.path("task")), proc.fs.isReal}
  64. if _, err := os.Stat(tfs.proc.Path(strconv.Itoa(tid))); err != nil {
  65. return Proc{}, err
  66. }
  67. return Proc{PID: tid, fs: tfs}, nil
  68. }