state.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package container
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "time"
  7. "golang.org/x/net/context"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/go-units"
  10. )
  11. // State holds the current container state, and has methods to get and
  12. // set the state. Container has an embed, which allows all of the
  13. // functions defined against State to run against Container.
  14. type State struct {
  15. sync.Mutex
  16. // Note that `Running` and `Paused` are not mutually exclusive:
  17. // When pausing a container (on Linux), the cgroups freezer is used to suspend
  18. // all processes in the container. Freezing the process requires the process to
  19. // be running. As a result, paused containers are both `Running` _and_ `Paused`.
  20. Running bool
  21. Paused bool
  22. Restarting bool
  23. OOMKilled bool
  24. RemovalInProgress bool // Not need for this to be persistent on disk.
  25. Dead bool
  26. Pid int
  27. ExitCodeValue int `json:"ExitCode"`
  28. ErrorMsg string `json:"Error"` // contains last known error when starting the container
  29. StartedAt time.Time
  30. FinishedAt time.Time
  31. Health *Health
  32. waitStop chan struct{}
  33. waitRemove chan struct{}
  34. }
  35. // StateStatus is used to return container wait results.
  36. // Implements exec.ExitCode interface.
  37. // This type is needed as State include a sync.Mutex field which make
  38. // copying it unsafe.
  39. type StateStatus struct {
  40. exitCode int
  41. err error
  42. }
  43. // ExitCode returns current exitcode for the state.
  44. func (s StateStatus) ExitCode() int {
  45. return s.exitCode
  46. }
  47. // Err returns current error for the state. Returns nil if the container had
  48. // exited on its own.
  49. func (s StateStatus) Err() error {
  50. return s.err
  51. }
  52. // NewState creates a default state object with a fresh channel for state changes.
  53. func NewState() *State {
  54. return &State{
  55. waitStop: make(chan struct{}),
  56. waitRemove: 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. // WaitCondition is an enum type for different states to wait for.
  137. type WaitCondition int
  138. // Possible WaitCondition Values.
  139. //
  140. // WaitConditionNotRunning (default) is used to wait for any of the non-running
  141. // states: "created", "exited", "dead", "removing", or "removed".
  142. //
  143. // WaitConditionNextExit is used to wait for the next time the state changes
  144. // to a non-running state. If the state is currently "created" or "exited",
  145. // this would cause Wait() to block until either the container runs and exits
  146. // or is removed.
  147. //
  148. // WaitConditionRemoved is used to wait for the container to be removed.
  149. const (
  150. WaitConditionNotRunning WaitCondition = iota
  151. WaitConditionNextExit
  152. WaitConditionRemoved
  153. )
  154. // Wait waits until the container is in a certain state indicated by the given
  155. // condition. A context must be used for cancelling the request, controlling
  156. // timeouts, and avoiding goroutine leaks. Wait must be called without holding
  157. // the state lock. Returns a channel from which the caller will receive the
  158. // result. If the container exited on its own, the result's Err() method will
  159. // be nil and its ExitCode() method will return the container's exit code,
  160. // otherwise, the results Err() method will return an error indicating why the
  161. // wait operation failed.
  162. func (s *State) Wait(ctx context.Context, condition WaitCondition) <-chan StateStatus {
  163. s.Lock()
  164. defer s.Unlock()
  165. if condition == WaitConditionNotRunning && !s.Running {
  166. // Buffer so we can put it in the channel now.
  167. resultC := make(chan StateStatus, 1)
  168. // Send the current status.
  169. resultC <- StateStatus{
  170. exitCode: s.ExitCode(),
  171. err: s.Err(),
  172. }
  173. return resultC
  174. }
  175. // If we are waiting only for removal, the waitStop channel should
  176. // remain nil and block forever.
  177. var waitStop chan struct{}
  178. if condition < WaitConditionRemoved {
  179. waitStop = s.waitStop
  180. }
  181. // Always wait for removal, just in case the container gets removed
  182. // while it is still in a "created" state, in which case it is never
  183. // actually stopped.
  184. waitRemove := s.waitRemove
  185. resultC := make(chan StateStatus)
  186. go func() {
  187. select {
  188. case <-ctx.Done():
  189. // Context timeout or cancellation.
  190. resultC <- StateStatus{
  191. exitCode: -1,
  192. err: ctx.Err(),
  193. }
  194. return
  195. case <-waitStop:
  196. case <-waitRemove:
  197. }
  198. s.Lock()
  199. result := StateStatus{
  200. exitCode: s.ExitCode(),
  201. err: s.Err(),
  202. }
  203. s.Unlock()
  204. resultC <- result
  205. }()
  206. return resultC
  207. }
  208. // IsRunning returns whether the running flag is set. Used by Container to check whether a container is running.
  209. func (s *State) IsRunning() bool {
  210. s.Lock()
  211. res := s.Running
  212. s.Unlock()
  213. return res
  214. }
  215. // GetPID holds the process id of a container.
  216. func (s *State) GetPID() int {
  217. s.Lock()
  218. res := s.Pid
  219. s.Unlock()
  220. return res
  221. }
  222. // ExitCode returns current exitcode for the state. Take lock before if state
  223. // may be shared.
  224. func (s *State) ExitCode() int {
  225. return s.ExitCodeValue
  226. }
  227. // SetExitCode sets current exitcode for the state. Take lock before if state
  228. // may be shared.
  229. func (s *State) SetExitCode(ec int) {
  230. s.ExitCodeValue = ec
  231. }
  232. // SetRunning sets the state of the container to "running".
  233. func (s *State) SetRunning(pid int, initial bool) {
  234. s.ErrorMsg = ""
  235. s.Running = true
  236. s.Restarting = false
  237. if initial {
  238. s.Paused = false
  239. }
  240. s.ExitCodeValue = 0
  241. s.Pid = pid
  242. if initial {
  243. s.StartedAt = time.Now().UTC()
  244. }
  245. }
  246. // SetStopped sets the container state to "stopped" without locking.
  247. func (s *State) SetStopped(exitStatus *ExitStatus) {
  248. s.Running = false
  249. s.Paused = false
  250. s.Restarting = false
  251. s.Pid = 0
  252. s.FinishedAt = time.Now().UTC()
  253. s.setFromExitStatus(exitStatus)
  254. close(s.waitStop) // Fire waiters for stop
  255. s.waitStop = make(chan struct{})
  256. }
  257. // SetRestarting sets the container state to "restarting" without locking.
  258. // It also sets the container PID to 0.
  259. func (s *State) SetRestarting(exitStatus *ExitStatus) {
  260. // we should consider the container running when it is restarting because of
  261. // all the checks in docker around rm/stop/etc
  262. s.Running = true
  263. s.Restarting = true
  264. s.Paused = false
  265. s.Pid = 0
  266. s.FinishedAt = time.Now().UTC()
  267. s.setFromExitStatus(exitStatus)
  268. close(s.waitStop) // Fire waiters for stop
  269. s.waitStop = make(chan struct{})
  270. }
  271. // SetError sets the container's error state. This is useful when we want to
  272. // know the error that occurred when container transits to another state
  273. // when inspecting it
  274. func (s *State) SetError(err error) {
  275. s.ErrorMsg = err.Error()
  276. }
  277. // IsPaused returns whether the container is paused or not.
  278. func (s *State) IsPaused() bool {
  279. s.Lock()
  280. res := s.Paused
  281. s.Unlock()
  282. return res
  283. }
  284. // IsRestarting returns whether the container is restarting or not.
  285. func (s *State) IsRestarting() bool {
  286. s.Lock()
  287. res := s.Restarting
  288. s.Unlock()
  289. return res
  290. }
  291. // SetRemovalInProgress sets the container state as being removed.
  292. // It returns true if the container was already in that state.
  293. func (s *State) SetRemovalInProgress() bool {
  294. s.Lock()
  295. defer s.Unlock()
  296. if s.RemovalInProgress {
  297. return true
  298. }
  299. s.RemovalInProgress = true
  300. return false
  301. }
  302. // ResetRemovalInProgress makes the RemovalInProgress state to false.
  303. func (s *State) ResetRemovalInProgress() {
  304. s.Lock()
  305. s.RemovalInProgress = false
  306. s.Unlock()
  307. }
  308. // IsRemovalInProgress returns whether the RemovalInProgress flag is set.
  309. // Used by Container to check whether a container is being removed.
  310. func (s *State) IsRemovalInProgress() bool {
  311. s.Lock()
  312. res := s.RemovalInProgress
  313. s.Unlock()
  314. return res
  315. }
  316. // SetDead sets the container state to "dead"
  317. func (s *State) SetDead() {
  318. s.Lock()
  319. s.Dead = true
  320. s.Unlock()
  321. }
  322. // IsDead returns whether the Dead flag is set. Used by Container to check whether a container is dead.
  323. func (s *State) IsDead() bool {
  324. s.Lock()
  325. res := s.Dead
  326. s.Unlock()
  327. return res
  328. }
  329. // SetRemoved assumes this container is already in the "dead" state and
  330. // closes the internal waitRemove channel to unblock callers waiting for a
  331. // container to be removed.
  332. func (s *State) SetRemoved() {
  333. s.Lock()
  334. close(s.waitRemove) // Unblock those waiting on remove.
  335. s.Unlock()
  336. }
  337. // Err returns an error if there is one.
  338. func (s *State) Err() error {
  339. if s.ErrorMsg != "" {
  340. return errors.New(s.ErrorMsg)
  341. }
  342. return nil
  343. }