state.go 900 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package docker
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. type State struct {
  8. Running bool
  9. Pid int
  10. ExitCode int
  11. StartedAt time.Time
  12. stateChangeLock *sync.Mutex
  13. stateChangeCond *sync.Cond
  14. }
  15. // String returns a human-readable description of the state
  16. func (s *State) String() string {
  17. if s.Running {
  18. return fmt.Sprintf("Up %s", HumanDuration(time.Now().Sub(s.StartedAt)))
  19. }
  20. return fmt.Sprintf("Exit %d", s.ExitCode)
  21. }
  22. func (s *State) setRunning(pid int) {
  23. s.Running = true
  24. s.ExitCode = 0
  25. s.Pid = pid
  26. s.StartedAt = time.Now()
  27. s.broadcast()
  28. }
  29. func (s *State) setStopped(exitCode int) {
  30. s.Running = false
  31. s.Pid = 0
  32. s.ExitCode = exitCode
  33. s.broadcast()
  34. }
  35. func (s *State) broadcast() {
  36. s.stateChangeLock.Lock()
  37. s.stateChangeCond.Broadcast()
  38. s.stateChangeLock.Unlock()
  39. }
  40. func (s *State) wait() {
  41. s.stateChangeLock.Lock()
  42. s.stateChangeCond.Wait()
  43. s.stateChangeLock.Unlock()
  44. }