api.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. "io"
  17. "strings"
  18. "time"
  19. "github.com/compose-spec/compose-go/types"
  20. )
  21. // Service manages a compose project
  22. type Service interface {
  23. // Build executes the equivalent to a `compose build`
  24. Build(ctx context.Context, project *types.Project, options BuildOptions) error
  25. // Push executes the equivalent ot a `compose push`
  26. Push(ctx context.Context, project *types.Project) error
  27. // Pull executes the equivalent of a `compose pull`
  28. Pull(ctx context.Context, project *types.Project) error
  29. // Create executes the equivalent to a `compose create`
  30. Create(ctx context.Context, project *types.Project, opts CreateOptions) error
  31. // Start executes the equivalent to a `compose start`
  32. Start(ctx context.Context, project *types.Project, options StartOptions) error
  33. // Stop executes the equivalent to a `compose stop`
  34. Stop(ctx context.Context, project *types.Project, options StopOptions) error
  35. // Up executes the equivalent to a `compose up`
  36. Up(ctx context.Context, project *types.Project, options UpOptions) error
  37. // Down executes the equivalent to a `compose down`
  38. Down(ctx context.Context, projectName string, options DownOptions) error
  39. // Logs executes the equivalent to a `compose logs`
  40. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  41. // Ps executes the equivalent to a `compose ps`
  42. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  43. // List executes the equivalent to a `docker stack ls`
  44. List(ctx context.Context, options ListOptions) ([]Stack, error)
  45. // Convert translate compose model into backend's native format
  46. Convert(ctx context.Context, project *types.Project, options ConvertOptions) ([]byte, error)
  47. // Kill executes the equivalent to a `compose kill`
  48. Kill(ctx context.Context, project *types.Project, options KillOptions) error
  49. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  50. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  51. // Remove executes the equivalent to a `compose rm`
  52. Remove(ctx context.Context, project *types.Project, options RemoveOptions) ([]string, error)
  53. // Exec executes a command in a running service container
  54. Exec(ctx context.Context, project *types.Project, opts RunOptions) error
  55. // Pause executes the equivalent to a `compose pause`
  56. Pause(ctx context.Context, project *types.Project) error
  57. // UnPause executes the equivalent to a `compose unpause`
  58. UnPause(ctx context.Context, project *types.Project) error
  59. // Top executes the equivalent to a `compose top`
  60. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  61. }
  62. // BuildOptions group options of the Build API
  63. type BuildOptions struct {
  64. // Pull always attempt to pull a newer version of the image
  65. Pull bool
  66. // Progress set type of progress output ("auto", "plain", "tty")
  67. Progress string
  68. // Args set build-time args
  69. Args types.Mapping
  70. }
  71. // CreateOptions group options of the Create API
  72. type CreateOptions struct {
  73. // Services defines the services user interacts with
  74. Services []string
  75. // Remove legacy containers for services that are not defined in the project
  76. RemoveOrphans bool
  77. // Recreate define the strategy to apply on existing containers
  78. Recreate string
  79. // RecreateDependencies define the strategy to apply on dependencies services
  80. RecreateDependencies string
  81. // Inherit reuse anonymous volumes from previous container
  82. Inherit bool
  83. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  84. Timeout *time.Duration
  85. }
  86. // StartOptions group options of the Start API
  87. type StartOptions struct {
  88. // Attach will attach to service containers and send container logs and events
  89. Attach ContainerEventListener
  90. // Services passed in the command line to be started
  91. Services []string
  92. }
  93. // StopOptions group options of the Stop API
  94. type StopOptions struct {
  95. // Timeout override container stop timeout
  96. Timeout *time.Duration
  97. }
  98. // UpOptions group options of the Up API
  99. type UpOptions struct {
  100. // Detach will create services and return immediately
  101. Detach bool
  102. }
  103. // DownOptions group options of the Down API
  104. type DownOptions struct {
  105. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  106. RemoveOrphans bool
  107. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  108. Project *types.Project
  109. // Timeout override container stop timeout
  110. Timeout *time.Duration
  111. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  112. Images string
  113. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  114. Volumes bool
  115. }
  116. // ConvertOptions group options of the Convert API
  117. type ConvertOptions struct {
  118. // Format define the output format used to dump converted application model (json|yaml)
  119. Format string
  120. // Output defines the path to save the application model
  121. Output string
  122. }
  123. // KillOptions group options of the Kill API
  124. type KillOptions struct {
  125. // Signal to send to containers
  126. Signal string
  127. }
  128. // RemoveOptions group options of the Remove API
  129. type RemoveOptions struct {
  130. // DryRun just list removable resources
  131. DryRun bool
  132. // Volumes remove anonymous volumes
  133. Volumes bool
  134. // Force don't ask to confirm removal
  135. Force bool
  136. }
  137. // RunOptions options to execute compose run
  138. type RunOptions struct {
  139. Name string
  140. Service string
  141. Command []string
  142. Entrypoint []string
  143. Detach bool
  144. AutoRemove bool
  145. Writer io.Writer
  146. Reader io.Reader
  147. Tty bool
  148. WorkingDir string
  149. User string
  150. Environment []string
  151. Labels types.Labels
  152. Privileged bool
  153. // used by exec
  154. Index int
  155. }
  156. // EnvironmentMap return RunOptions.Environment as a MappingWithEquals
  157. func (opts *RunOptions) EnvironmentMap() types.MappingWithEquals {
  158. environment := types.MappingWithEquals{}
  159. for _, s := range opts.Environment {
  160. parts := strings.SplitN(s, "=", 2)
  161. key := parts[0]
  162. switch {
  163. case len(parts) == 1:
  164. environment[key] = nil
  165. default:
  166. environment[key] = &parts[1]
  167. }
  168. }
  169. return environment
  170. }
  171. // ListOptions group options of the ls API
  172. type ListOptions struct {
  173. All bool
  174. }
  175. // PsOptions group options of the Ps API
  176. type PsOptions struct {
  177. All bool
  178. }
  179. // PortPublisher hold status about published port
  180. type PortPublisher struct {
  181. URL string
  182. TargetPort int
  183. PublishedPort int
  184. Protocol string
  185. }
  186. // ContainerSummary hold high-level description of a container
  187. type ContainerSummary struct {
  188. ID string
  189. Name string
  190. Project string
  191. Service string
  192. State string
  193. Health string
  194. Publishers []PortPublisher
  195. }
  196. // ContainerProcSummary holds container processes top data
  197. type ContainerProcSummary struct {
  198. ID string
  199. Name string
  200. Processes [][]string
  201. Titles []string
  202. }
  203. // ServiceStatus hold status about a service
  204. type ServiceStatus struct {
  205. ID string
  206. Name string
  207. Replicas int
  208. Desired int
  209. Ports []string
  210. Publishers []PortPublisher
  211. }
  212. // LogOptions defines optional parameters for the `Log` API
  213. type LogOptions struct {
  214. Services []string
  215. Tail string
  216. Follow bool
  217. Timestamps bool
  218. }
  219. const (
  220. // STARTING indicates that stack is being deployed
  221. STARTING string = "Starting"
  222. // RUNNING indicates that stack is deployed and services are running
  223. RUNNING string = "Running"
  224. // UPDATING indicates that some stack resources are being recreated
  225. UPDATING string = "Updating"
  226. // REMOVING indicates that stack is being deleted
  227. REMOVING string = "Removing"
  228. // UNKNOWN indicates unknown stack state
  229. UNKNOWN string = "Unknown"
  230. // FAILED indicates that stack deployment failed
  231. FAILED string = "Failed"
  232. )
  233. const (
  234. // RecreateDiverged to recreate services which configuration diverges from compose model
  235. RecreateDiverged = "diverged"
  236. // RecreateForce to force service container being recreated
  237. RecreateForce = "force"
  238. // RecreateNever to never recreate existing service containers
  239. RecreateNever = "never"
  240. )
  241. // Stack holds the name and state of a compose application/stack
  242. type Stack struct {
  243. ID string
  244. Name string
  245. Status string
  246. Reason string
  247. }
  248. // LogConsumer is a callback to process log messages from services
  249. type LogConsumer interface {
  250. Log(name, service, container, message string)
  251. Status(name, container, msg string)
  252. Register(name string, source string)
  253. }
  254. // ContainerEventListener is a callback to process ContainerEvent from services
  255. type ContainerEventListener func(event ContainerEvent)
  256. // ContainerEvent notify an event has been collected on Source container implementing Service
  257. type ContainerEvent struct {
  258. Type int
  259. Source string
  260. Service string
  261. Name string
  262. Line string
  263. ExitCode int
  264. }
  265. const (
  266. // ContainerEventLog is a ContainerEvent of type log. Line is set
  267. ContainerEventLog = iota
  268. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  269. ContainerEventAttach
  270. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  271. ContainerEventExit
  272. // UserCancel user cancelled compose up, we are stopping containers
  273. UserCancel
  274. )