api.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "strings"
  19. "time"
  20. "github.com/compose-spec/compose-go/types"
  21. )
  22. // Service manages a compose project
  23. type Service interface {
  24. // Build executes the equivalent to a `compose build`
  25. Build(ctx context.Context, project *types.Project, options BuildOptions) error
  26. // Push executes the equivalent ot a `compose push`
  27. Push(ctx context.Context, project *types.Project, options PushOptions) error
  28. // Pull executes the equivalent of a `compose pull`
  29. Pull(ctx context.Context, project *types.Project, opts PullOptions) error
  30. // Create executes the equivalent to a `compose create`
  31. Create(ctx context.Context, project *types.Project, opts CreateOptions) error
  32. // Start executes the equivalent to a `compose start`
  33. Start(ctx context.Context, project *types.Project, options StartOptions) error
  34. // Restart restarts containers
  35. Restart(ctx context.Context, project *types.Project, options RestartOptions) error
  36. // Stop executes the equivalent to a `compose stop`
  37. Stop(ctx context.Context, project *types.Project, options StopOptions) error
  38. // Up executes the equivalent to a `compose up`
  39. Up(ctx context.Context, project *types.Project, options UpOptions) error
  40. // Down executes the equivalent to a `compose down`
  41. Down(ctx context.Context, projectName string, options DownOptions) error
  42. // Logs executes the equivalent to a `compose logs`
  43. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  44. // Ps executes the equivalent to a `compose ps`
  45. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  46. // List executes the equivalent to a `docker stack ls`
  47. List(ctx context.Context, options ListOptions) ([]Stack, error)
  48. // Convert translate compose model into backend's native format
  49. Convert(ctx context.Context, project *types.Project, options ConvertOptions) ([]byte, error)
  50. // Kill executes the equivalent to a `compose kill`
  51. Kill(ctx context.Context, project *types.Project, options KillOptions) error
  52. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  53. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  54. // Remove executes the equivalent to a `compose rm`
  55. Remove(ctx context.Context, project *types.Project, options RemoveOptions) ([]string, error)
  56. // Exec executes a command in a running service container
  57. Exec(ctx context.Context, project *types.Project, opts RunOptions) error
  58. // Pause executes the equivalent to a `compose pause`
  59. Pause(ctx context.Context, project string, options PauseOptions) error
  60. // UnPause executes the equivalent to a `compose unpause`
  61. UnPause(ctx context.Context, project string, options PauseOptions) error
  62. // Top executes the equivalent to a `compose top`
  63. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  64. // Events executes the equivalent to a `compose events`
  65. Events(ctx context.Context, project string, options EventsOptions) error
  66. // Port executes the equivalent to a `compose port`
  67. Port(ctx context.Context, project string, service string, port int, options PortOptions) (string, int, error)
  68. // Images executes the equivalent of a `compose images`
  69. Images(ctx context.Context, projectName string, options ImagesOptions) ([]ImageSummary, error)
  70. }
  71. // BuildOptions group options of the Build API
  72. type BuildOptions struct {
  73. // Pull always attempt to pull a newer version of the image
  74. Pull bool
  75. // Progress set type of progress output ("auto", "plain", "tty")
  76. Progress string
  77. // Args set build-time args
  78. Args types.Mapping
  79. // NoCache disables cache use
  80. NoCache bool
  81. }
  82. // CreateOptions group options of the Create API
  83. type CreateOptions struct {
  84. // Services defines the services user interacts with
  85. Services []string
  86. // Remove legacy containers for services that are not defined in the project
  87. RemoveOrphans bool
  88. // Recreate define the strategy to apply on existing containers
  89. Recreate string
  90. // RecreateDependencies define the strategy to apply on dependencies services
  91. RecreateDependencies string
  92. // Inherit reuse anonymous volumes from previous container
  93. Inherit bool
  94. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  95. Timeout *time.Duration
  96. // QuietPull makes the pulling process quiet
  97. QuietPull bool
  98. }
  99. // StartOptions group options of the Start API
  100. type StartOptions struct {
  101. // Attach will attach to service containers and send container logs and events
  102. Attach ContainerEventListener
  103. // Services passed in the command line to be started
  104. Services []string
  105. }
  106. // RestartOptions group options of the Restart API
  107. type RestartOptions struct {
  108. // Timeout override container restart timeout
  109. Timeout *time.Duration
  110. }
  111. // StopOptions group options of the Stop API
  112. type StopOptions struct {
  113. // Timeout override container stop timeout
  114. Timeout *time.Duration
  115. }
  116. // UpOptions group options of the Up API
  117. type UpOptions struct {
  118. // Detach will create services and return immediately
  119. Detach bool
  120. // QuietPull makes the pulling process quiet
  121. QuietPull bool
  122. }
  123. // DownOptions group options of the Down API
  124. type DownOptions struct {
  125. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  126. RemoveOrphans bool
  127. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  128. Project *types.Project
  129. // Timeout override container stop timeout
  130. Timeout *time.Duration
  131. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  132. Images string
  133. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  134. Volumes bool
  135. }
  136. // ConvertOptions group options of the Convert API
  137. type ConvertOptions struct {
  138. // Format define the output format used to dump converted application model (json|yaml)
  139. Format string
  140. // Output defines the path to save the application model
  141. Output string
  142. }
  143. // PushOptions group options of the Push API
  144. type PushOptions struct {
  145. IgnoreFailures bool
  146. }
  147. // PullOptions group options of the Push API
  148. type PullOptions struct {
  149. IgnoreFailures bool
  150. }
  151. // ImagesOptions group options of the Images API
  152. type ImagesOptions struct {
  153. Services []string
  154. }
  155. // KillOptions group options of the Kill API
  156. type KillOptions struct {
  157. // Signal to send to containers
  158. Signal string
  159. }
  160. // RemoveOptions group options of the Remove API
  161. type RemoveOptions struct {
  162. // DryRun just list removable resources
  163. DryRun bool
  164. // Volumes remove anonymous volumes
  165. Volumes bool
  166. // Force don't ask to confirm removal
  167. Force bool
  168. }
  169. // RunOptions group options of the Run API
  170. type RunOptions struct {
  171. Name string
  172. Service string
  173. Command []string
  174. Entrypoint []string
  175. Detach bool
  176. AutoRemove bool
  177. Writer io.WriteCloser
  178. Reader io.ReadCloser
  179. Tty bool
  180. WorkingDir string
  181. User string
  182. Environment []string
  183. Labels types.Labels
  184. Privileged bool
  185. UseNetworkAliases bool
  186. // used by exec
  187. Index int
  188. }
  189. // EventsOptions group options of the Events API
  190. type EventsOptions struct {
  191. Services []string
  192. Consumer func(event Event) error
  193. }
  194. // Event is a container runtime event served by Events API
  195. type Event struct {
  196. Timestamp time.Time
  197. Service string
  198. Container string
  199. Status string
  200. Attributes map[string]string
  201. }
  202. // PortOptions group options of the Port API
  203. type PortOptions struct {
  204. Protocol string
  205. Index int
  206. }
  207. func (e Event) String() string {
  208. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  209. var attr []string
  210. for k, v := range e.Attributes {
  211. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  212. }
  213. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  214. }
  215. // EnvironmentMap return RunOptions.Environment as a MappingWithEquals
  216. func (opts *RunOptions) EnvironmentMap() types.MappingWithEquals {
  217. environment := types.MappingWithEquals{}
  218. for _, s := range opts.Environment {
  219. parts := strings.SplitN(s, "=", 2)
  220. key := parts[0]
  221. switch {
  222. case len(parts) == 1:
  223. environment[key] = nil
  224. default:
  225. environment[key] = &parts[1]
  226. }
  227. }
  228. return environment
  229. }
  230. // ListOptions group options of the ls API
  231. type ListOptions struct {
  232. All bool
  233. }
  234. // PsOptions group options of the Ps API
  235. type PsOptions struct {
  236. All bool
  237. }
  238. // PortPublisher hold status about published port
  239. type PortPublisher struct {
  240. URL string
  241. TargetPort int
  242. PublishedPort int
  243. Protocol string
  244. }
  245. // ContainerSummary hold high-level description of a container
  246. type ContainerSummary struct {
  247. ID string
  248. Name string
  249. Project string
  250. Service string
  251. State string
  252. Health string
  253. Publishers []PortPublisher
  254. }
  255. // ContainerProcSummary holds container processes top data
  256. type ContainerProcSummary struct {
  257. ID string
  258. Name string
  259. Processes [][]string
  260. Titles []string
  261. }
  262. // ImageSummary holds container image description
  263. type ImageSummary struct {
  264. ID string
  265. ContainerName string
  266. Repository string
  267. Tag string
  268. Size int64
  269. }
  270. // ServiceStatus hold status about a service
  271. type ServiceStatus struct {
  272. ID string
  273. Name string
  274. Replicas int
  275. Desired int
  276. Ports []string
  277. Publishers []PortPublisher
  278. }
  279. // LogOptions defines optional parameters for the `Log` API
  280. type LogOptions struct {
  281. Services []string
  282. Tail string
  283. Follow bool
  284. Timestamps bool
  285. }
  286. // PauseOptions group options of the Pause API
  287. type PauseOptions struct {
  288. // Services passed in the command line to be started
  289. Services []string
  290. }
  291. const (
  292. // STARTING indicates that stack is being deployed
  293. STARTING string = "Starting"
  294. // RUNNING indicates that stack is deployed and services are running
  295. RUNNING string = "Running"
  296. // UPDATING indicates that some stack resources are being recreated
  297. UPDATING string = "Updating"
  298. // REMOVING indicates that stack is being deleted
  299. REMOVING string = "Removing"
  300. // UNKNOWN indicates unknown stack state
  301. UNKNOWN string = "Unknown"
  302. // FAILED indicates that stack deployment failed
  303. FAILED string = "Failed"
  304. )
  305. const (
  306. // RecreateDiverged to recreate services which configuration diverges from compose model
  307. RecreateDiverged = "diverged"
  308. // RecreateForce to force service container being recreated
  309. RecreateForce = "force"
  310. // RecreateNever to never recreate existing service containers
  311. RecreateNever = "never"
  312. )
  313. // Stack holds the name and state of a compose application/stack
  314. type Stack struct {
  315. ID string
  316. Name string
  317. Status string
  318. Reason string
  319. }
  320. // LogConsumer is a callback to process log messages from services
  321. type LogConsumer interface {
  322. Log(service, container, message string)
  323. Status(container, msg string)
  324. Register(container string)
  325. }
  326. // ContainerEventListener is a callback to process ContainerEvent from services
  327. type ContainerEventListener func(event ContainerEvent)
  328. // ContainerEvent notify an event has been collected on source container implementing Service
  329. type ContainerEvent struct {
  330. Type int
  331. Container string
  332. Service string
  333. Line string
  334. ExitCode int
  335. }
  336. const (
  337. // ContainerEventLog is a ContainerEvent of type log. Line is set
  338. ContainerEventLog = iota
  339. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  340. ContainerEventAttach
  341. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  342. ContainerEventExit
  343. // UserCancel user cancelled compose up, we are stopping containers
  344. UserCancel
  345. )