state.go 1.1 KB

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