state.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package docker
  2. import (
  3. "fmt"
  4. "github.com/dotcloud/docker/utils"
  5. "sync"
  6. "time"
  7. )
  8. type State struct {
  9. sync.RWMutex
  10. Running bool
  11. Pid int
  12. ExitCode int
  13. StartedAt time.Time
  14. FinishedAt time.Time
  15. Ghost bool
  16. }
  17. // String returns a human-readable description of the state
  18. func (s *State) String() string {
  19. s.RLock()
  20. defer s.RUnlock()
  21. if s.Running {
  22. if s.Ghost {
  23. return fmt.Sprintf("Ghost")
  24. }
  25. return fmt.Sprintf("Up %s", utils.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
  26. }
  27. return fmt.Sprintf("Exit %d", s.ExitCode)
  28. }
  29. func (s *State) IsRunning() bool {
  30. s.RLock()
  31. defer s.RUnlock()
  32. return s.Running
  33. }
  34. func (s *State) IsGhost() bool {
  35. s.RLock()
  36. defer s.RUnlock()
  37. return s.Ghost
  38. }
  39. func (s *State) GetExitCode() int {
  40. s.RLock()
  41. defer s.RUnlock()
  42. return s.ExitCode
  43. }
  44. func (s *State) SetGhost(val bool) {
  45. s.Lock()
  46. defer s.Unlock()
  47. s.Ghost = val
  48. }
  49. func (s *State) SetRunning(pid int) {
  50. s.Lock()
  51. defer s.Unlock()
  52. s.Running = true
  53. s.Ghost = false
  54. s.ExitCode = 0
  55. s.Pid = pid
  56. s.StartedAt = time.Now().UTC()
  57. }
  58. func (s *State) SetStopped(exitCode int) {
  59. s.Lock()
  60. defer s.Unlock()
  61. s.Running = false
  62. s.Pid = 0
  63. s.FinishedAt = time.Now().UTC()
  64. s.ExitCode = exitCode
  65. }