state.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package container
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/go-units"
  9. )
  10. // State holds the current container state, and has methods to get and
  11. // set the state. Container has an embed, which allows all of the
  12. // functions defined against State to run against Container.
  13. type State struct {
  14. sync.Mutex
  15. // FIXME: Why do we have both paused and running if a
  16. // container cannot be paused and running at the same time?
  17. Running bool
  18. Paused bool
  19. Restarting bool
  20. OOMKilled bool
  21. RemovalInProgress bool // Not need for this to be persistent on disk.
  22. Dead bool
  23. Pid int
  24. ExitCodeValue int `json:"ExitCode"`
  25. ErrorMsg string `json:"Error"` // contains last known error when starting the container
  26. StartedAt time.Time
  27. FinishedAt time.Time
  28. waitChan chan struct{}
  29. Health *Health
  30. }
  31. // StateStatus is used to return an error type implementing both
  32. // exec.ExitCode and error.
  33. // This type is needed as State include a sync.Mutex field which make
  34. // copying it unsafe.
  35. type StateStatus struct {
  36. exitCode int
  37. error string
  38. }
  39. func newStateStatus(ec int, err string) *StateStatus {
  40. return &StateStatus{
  41. exitCode: ec,
  42. error: err,
  43. }
  44. }
  45. // ExitCode returns current exitcode for the state.
  46. func (ss *StateStatus) ExitCode() int {
  47. return ss.exitCode
  48. }
  49. // Error returns current error for the state.
  50. func (ss *StateStatus) Error() string {
  51. return ss.error
  52. }
  53. // NewState creates a default state object with a fresh channel for state changes.
  54. func NewState() *State {
  55. return &State{
  56. waitChan: make(chan struct{}),
  57. }
  58. }
  59. // String returns a human-readable description of the state
  60. func (s *State) String() string {
  61. if s.Running {
  62. if s.Paused {
  63. return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
  64. }
  65. if s.Restarting {
  66. return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCodeValue, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
  67. }
  68. if h := s.Health; h != nil {
  69. return fmt.Sprintf("Up %s (%s)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)), h.String())
  70. }
  71. return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt)))
  72. }
  73. if s.RemovalInProgress {
  74. return "Removal In Progress"
  75. }
  76. if s.Dead {
  77. return "Dead"
  78. }
  79. if s.StartedAt.IsZero() {
  80. return "Created"
  81. }
  82. if s.FinishedAt.IsZero() {
  83. return ""
  84. }
  85. return fmt.Sprintf("Exited (%d) %s ago", s.ExitCodeValue, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt)))
  86. }
  87. // HealthString returns a single string to describe health status.
  88. func (s *State) HealthString() string {
  89. if s.Health == nil {
  90. return types.NoHealthcheck
  91. }
  92. return s.Health.String()
  93. }
  94. // IsValidHealthString checks if the provided string is a valid container health status or not.
  95. func IsValidHealthString(s string) bool {
  96. return s == types.Starting ||
  97. s == types.Healthy ||
  98. s == types.Unhealthy ||
  99. s == types.NoHealthcheck
  100. }
  101. // StateString returns a single string to describe state
  102. func (s *State) StateString() string {
  103. if s.Running {
  104. if s.Paused {
  105. return "paused"
  106. }
  107. if s.Restarting {
  108. return "restarting"
  109. }
  110. return "running"
  111. }
  112. if s.RemovalInProgress {
  113. return "removing"
  114. }
  115. if s.Dead {
  116. return "dead"
  117. }
  118. if s.StartedAt.IsZero() {
  119. return "created"
  120. }
  121. return "exited"
  122. }
  123. // IsValidStateString checks if the provided string is a valid container state or not.
  124. func IsValidStateString(s string) bool {
  125. if s != "paused" &&
  126. s != "restarting" &&
  127. s != "removing" &&
  128. s != "running" &&
  129. s != "dead" &&
  130. s != "created" &&
  131. s != "exited" {
  132. return false
  133. }
  134. return true
  135. }
  136. func wait(waitChan <-chan struct{}, timeout time.Duration) error {
  137. if timeout < 0 {
  138. <-waitChan
  139. return nil
  140. }
  141. select {
  142. case <-time.After(timeout):
  143. return fmt.Errorf("Timed out: %v", timeout)
  144. case <-waitChan:
  145. return nil
  146. }
  147. }
  148. // WaitStop waits until state is stopped. If state already stopped it returns
  149. // immediately. If you want wait forever you must supply negative timeout.
  150. // Returns exit code, that was passed to SetStopped
  151. func (s *State) WaitStop(timeout time.Duration) (int, error) {
  152. ctx := context.Background()
  153. if timeout >= 0 {
  154. var cancel func()
  155. ctx, cancel = context.WithTimeout(ctx, timeout)
  156. defer cancel()
  157. }
  158. if err := s.WaitWithContext(ctx); err != nil {
  159. if status, ok := err.(*StateStatus); ok {
  160. return status.ExitCode(), nil
  161. }
  162. return -1, err
  163. }
  164. return 0, nil
  165. }
  166. // WaitWithContext waits for the container to stop. Optional context can be
  167. // passed for canceling the request.
  168. func (s *State) WaitWithContext(ctx context.Context) error {
  169. s.Lock()
  170. if !s.Running {
  171. state := newStateStatus(s.ExitCode(), s.Error())
  172. defer s.Unlock()
  173. if state.ExitCode() == 0 {
  174. return nil
  175. }
  176. return state
  177. }
  178. waitChan := s.waitChan
  179. s.Unlock()
  180. select {
  181. case <-waitChan:
  182. s.Lock()
  183. state := newStateStatus(s.ExitCode(), s.Error())
  184. s.Unlock()
  185. if state.ExitCode() == 0 {
  186. return nil
  187. }
  188. return state
  189. case <-ctx.Done():
  190. return ctx.Err()
  191. }
  192. }
  193. // IsRunning returns whether the running flag is set. Used by Container to check whether a container is running.
  194. func (s *State) IsRunning() bool {
  195. s.Lock()
  196. res := s.Running
  197. s.Unlock()
  198. return res
  199. }
  200. // GetPID holds the process id of a container.
  201. func (s *State) GetPID() int {
  202. s.Lock()
  203. res := s.Pid
  204. s.Unlock()
  205. return res
  206. }
  207. // ExitCode returns current exitcode for the state. Take lock before if state
  208. // may be shared.
  209. func (s *State) ExitCode() int {
  210. return s.ExitCodeValue
  211. }
  212. // SetExitCode sets current exitcode for the state. Take lock before if state
  213. // may be shared.
  214. func (s *State) SetExitCode(ec int) {
  215. s.ExitCodeValue = ec
  216. }
  217. // SetRunning sets the state of the container to "running".
  218. func (s *State) SetRunning(pid int, initial bool) {
  219. s.ErrorMsg = ""
  220. s.Running = true
  221. s.Restarting = false
  222. s.ExitCodeValue = 0
  223. s.Pid = pid
  224. if initial {
  225. s.StartedAt = time.Now().UTC()
  226. }
  227. }
  228. // SetStopped sets the container state to "stopped" without locking.
  229. func (s *State) SetStopped(exitStatus *ExitStatus) {
  230. s.Running = false
  231. s.Paused = false
  232. s.Restarting = false
  233. s.Pid = 0
  234. s.FinishedAt = time.Now().UTC()
  235. s.setFromExitStatus(exitStatus)
  236. close(s.waitChan) // fire waiters for stop
  237. s.waitChan = make(chan struct{})
  238. }
  239. // SetRestarting sets the container state to "restarting" without locking.
  240. // It also sets the container PID to 0.
  241. func (s *State) SetRestarting(exitStatus *ExitStatus) {
  242. // we should consider the container running when it is restarting because of
  243. // all the checks in docker around rm/stop/etc
  244. s.Running = true
  245. s.Restarting = true
  246. s.Pid = 0
  247. s.FinishedAt = time.Now().UTC()
  248. s.setFromExitStatus(exitStatus)
  249. close(s.waitChan) // fire waiters for stop
  250. s.waitChan = make(chan struct{})
  251. }
  252. // SetError sets the container's error state. This is useful when we want to
  253. // know the error that occurred when container transits to another state
  254. // when inspecting it
  255. func (s *State) SetError(err error) {
  256. s.ErrorMsg = err.Error()
  257. }
  258. // IsPaused returns whether the container is paused or not.
  259. func (s *State) IsPaused() bool {
  260. s.Lock()
  261. res := s.Paused
  262. s.Unlock()
  263. return res
  264. }
  265. // IsRestarting returns whether the container is restarting or not.
  266. func (s *State) IsRestarting() bool {
  267. s.Lock()
  268. res := s.Restarting
  269. s.Unlock()
  270. return res
  271. }
  272. // SetRemovalInProgress sets the container state as being removed.
  273. // It returns true if the container was already in that state.
  274. func (s *State) SetRemovalInProgress() bool {
  275. s.Lock()
  276. defer s.Unlock()
  277. if s.RemovalInProgress {
  278. return true
  279. }
  280. s.RemovalInProgress = true
  281. return false
  282. }
  283. // ResetRemovalInProgress makes the RemovalInProgress state to false.
  284. func (s *State) ResetRemovalInProgress() {
  285. s.Lock()
  286. s.RemovalInProgress = false
  287. s.Unlock()
  288. }
  289. // SetDead sets the container state to "dead"
  290. func (s *State) SetDead() {
  291. s.Lock()
  292. s.Dead = true
  293. s.Unlock()
  294. }
  295. // Error returns current error for the state.
  296. func (s *State) Error() string {
  297. return s.ErrorMsg
  298. }