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.

context.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package process
  4. import (
  5. "context"
  6. )
  7. // Context is a wrapper around context.Context and contains the current pid for this context
  8. type Context struct {
  9. context.Context
  10. pid IDType
  11. }
  12. // GetPID returns the PID for this context
  13. func (c *Context) GetPID() IDType {
  14. return c.pid
  15. }
  16. // GetParent returns the parent process context (if any)
  17. func (c *Context) GetParent() *Context {
  18. return GetContext(c.Context)
  19. }
  20. // Value is part of the interface for context.Context. We mostly defer to the internal context - but we return this in response to the ProcessContextKey
  21. func (c *Context) Value(key any) any {
  22. if key == ProcessContextKey {
  23. return c
  24. }
  25. return c.Context.Value(key)
  26. }
  27. // ProcessContextKey is the key under which process contexts are stored
  28. var ProcessContextKey any = "process-context"
  29. // GetContext will return a process context if one exists
  30. func GetContext(ctx context.Context) *Context {
  31. if pCtx, ok := ctx.(*Context); ok {
  32. return pCtx
  33. }
  34. pCtxInterface := ctx.Value(ProcessContextKey)
  35. if pCtxInterface == nil {
  36. return nil
  37. }
  38. if pCtx, ok := pCtxInterface.(*Context); ok {
  39. return pCtx
  40. }
  41. return nil
  42. }
  43. // GetPID returns the PID for this context
  44. func GetPID(ctx context.Context) IDType {
  45. pCtx := GetContext(ctx)
  46. if pCtx == nil {
  47. return ""
  48. }
  49. return pCtx.GetPID()
  50. }
  51. // GetParentPID returns the ParentPID for this context
  52. func GetParentPID(ctx context.Context) IDType {
  53. var parentPID IDType
  54. if parentProcess := GetContext(ctx); parentProcess != nil {
  55. parentPID = parentProcess.GetPID()
  56. }
  57. return parentPID
  58. }