state.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 conatiners 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. s.ExitCodeValue = 0
  238. s.Pid = pid
  239. if initial {
  240. s.StartedAt = time.Now().UTC()
  241. }
  242. }
  243. // SetStopped sets the container state to "stopped" without locking.
  244. func (s *State) SetStopped(exitStatus *ExitStatus) {
  245. s.Running = false
  246. s.Paused = false
  247. s.Restarting = false
  248. s.Pid = 0
  249. s.FinishedAt = time.Now().UTC()
  250. s.setFromExitStatus(exitStatus)
  251. close(s.waitStop) // Fire waiters for stop
  252. s.waitStop = make(chan struct{})
  253. }
  254. // SetRestarting sets the container state to "restarting" without locking.
  255. // It also sets the container PID to 0.
  256. func (s *State) SetRestarting(exitStatus *ExitStatus) {
  257. // we should consider the container running when it is restarting because of
  258. // all the checks in docker around rm/stop/etc
  259. s.Running = true
  260. s.Restarting = true
  261. s.Pid = 0
  262. s.FinishedAt = time.Now().UTC()
  263. s.setFromExitStatus(exitStatus)
  264. close(s.waitStop) // Fire waiters for stop
  265. s.waitStop = make(chan struct{})
  266. }
  267. // SetError sets the container's error state. This is useful when we want to
  268. // know the error that occurred when container transits to another state
  269. // when inspecting it
  270. func (s *State) SetError(err error) {
  271. s.ErrorMsg = err.Error()
  272. }
  273. // IsPaused returns whether the container is paused or not.
  274. func (s *State) IsPaused() bool {
  275. s.Lock()
  276. res := s.Paused
  277. s.Unlock()
  278. return res
  279. }
  280. // IsRestarting returns whether the container is restarting or not.
  281. func (s *State) IsRestarting() bool {
  282. s.Lock()
  283. res := s.Restarting
  284. s.Unlock()
  285. return res
  286. }
  287. // SetRemovalInProgress sets the container state as being removed.
  288. // It returns true if the container was already in that state.
  289. func (s *State) SetRemovalInProgress() bool {
  290. s.Lock()
  291. defer s.Unlock()
  292. if s.RemovalInProgress {
  293. return true
  294. }
  295. s.RemovalInProgress = true
  296. return false
  297. }
  298. // ResetRemovalInProgress makes the RemovalInProgress state to false.
  299. func (s *State) ResetRemovalInProgress() {
  300. s.Lock()
  301. s.RemovalInProgress = false
  302. s.Unlock()
  303. }
  304. // SetDead sets the container state to "dead"
  305. func (s *State) SetDead() {
  306. s.Lock()
  307. s.Dead = true
  308. s.Unlock()
  309. }
  310. // SetRemoved assumes this container is already in the "dead" state and
  311. // closes the internal waitRemove channel to unblock callers waiting for a
  312. // container to be removed.
  313. func (s *State) SetRemoved() {
  314. s.Lock()
  315. close(s.waitRemove) // Unblock those waiting on remove.
  316. s.Unlock()
  317. }
  318. // Err returns an error if there is one.
  319. func (s *State) Err() error {
  320. if s.ErrorMsg != "" {
  321. return errors.New(s.ErrorMsg)
  322. }
  323. return nil
  324. }