api.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. // Quiet make the build process not output to the console
  82. Quiet bool
  83. }
  84. // CreateOptions group options of the Create API
  85. type CreateOptions struct {
  86. // Services defines the services user interacts with
  87. Services []string
  88. // Remove legacy containers for services that are not defined in the project
  89. RemoveOrphans bool
  90. // Recreate define the strategy to apply on existing containers
  91. Recreate string
  92. // RecreateDependencies define the strategy to apply on dependencies services
  93. RecreateDependencies string
  94. // Inherit reuse anonymous volumes from previous container
  95. Inherit bool
  96. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  97. Timeout *time.Duration
  98. // QuietPull makes the pulling process quiet
  99. QuietPull bool
  100. }
  101. // StartOptions group options of the Start API
  102. type StartOptions struct {
  103. // Attach will attach to service containers and send container logs and events
  104. Attach ContainerEventListener
  105. // Services passed in the command line to be started
  106. Services []string
  107. }
  108. // RestartOptions group options of the Restart API
  109. type RestartOptions struct {
  110. // Timeout override container restart timeout
  111. Timeout *time.Duration
  112. }
  113. // StopOptions group options of the Stop API
  114. type StopOptions struct {
  115. // Timeout override container stop timeout
  116. Timeout *time.Duration
  117. }
  118. // UpOptions group options of the Up API
  119. type UpOptions struct {
  120. // Detach will create services and return immediately
  121. Detach bool
  122. // QuietPull makes the pulling process quiet
  123. QuietPull bool
  124. }
  125. // DownOptions group options of the Down API
  126. type DownOptions struct {
  127. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  128. RemoveOrphans bool
  129. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  130. Project *types.Project
  131. // Timeout override container stop timeout
  132. Timeout *time.Duration
  133. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  134. Images string
  135. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  136. Volumes bool
  137. }
  138. // ConvertOptions group options of the Convert API
  139. type ConvertOptions struct {
  140. // Format define the output format used to dump converted application model (json|yaml)
  141. Format string
  142. // Output defines the path to save the application model
  143. Output string
  144. }
  145. // PushOptions group options of the Push API
  146. type PushOptions struct {
  147. IgnoreFailures bool
  148. }
  149. // PullOptions group options of the Push API
  150. type PullOptions struct {
  151. IgnoreFailures bool
  152. }
  153. // ImagesOptions group options of the Images API
  154. type ImagesOptions struct {
  155. Services []string
  156. }
  157. // KillOptions group options of the Kill API
  158. type KillOptions struct {
  159. // Signal to send to containers
  160. Signal string
  161. }
  162. // RemoveOptions group options of the Remove API
  163. type RemoveOptions struct {
  164. // DryRun just list removable resources
  165. DryRun bool
  166. // Volumes remove anonymous volumes
  167. Volumes bool
  168. // Force don't ask to confirm removal
  169. Force bool
  170. }
  171. // RunOptions group options of the Run API
  172. type RunOptions struct {
  173. Name string
  174. Service string
  175. Command []string
  176. Entrypoint []string
  177. Detach bool
  178. AutoRemove bool
  179. Writer io.WriteCloser
  180. Reader io.ReadCloser
  181. Tty bool
  182. WorkingDir string
  183. User string
  184. Environment []string
  185. Labels types.Labels
  186. Privileged bool
  187. UseNetworkAliases bool
  188. // used by exec
  189. Index int
  190. }
  191. // EventsOptions group options of the Events API
  192. type EventsOptions struct {
  193. Services []string
  194. Consumer func(event Event) error
  195. }
  196. // Event is a container runtime event served by Events API
  197. type Event struct {
  198. Timestamp time.Time
  199. Service string
  200. Container string
  201. Status string
  202. Attributes map[string]string
  203. }
  204. // PortOptions group options of the Port API
  205. type PortOptions struct {
  206. Protocol string
  207. Index int
  208. }
  209. func (e Event) String() string {
  210. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  211. var attr []string
  212. for k, v := range e.Attributes {
  213. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  214. }
  215. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  216. }
  217. // EnvironmentMap return RunOptions.Environment as a MappingWithEquals
  218. func (opts *RunOptions) EnvironmentMap() types.MappingWithEquals {
  219. environment := types.MappingWithEquals{}
  220. for _, s := range opts.Environment {
  221. parts := strings.SplitN(s, "=", 2)
  222. key := parts[0]
  223. switch {
  224. case len(parts) == 1:
  225. environment[key] = nil
  226. default:
  227. environment[key] = &parts[1]
  228. }
  229. }
  230. return environment
  231. }
  232. // ListOptions group options of the ls API
  233. type ListOptions struct {
  234. All bool
  235. }
  236. // PsOptions group options of the Ps API
  237. type PsOptions struct {
  238. All bool
  239. }
  240. // PortPublisher hold status about published port
  241. type PortPublisher struct {
  242. URL string
  243. TargetPort int
  244. PublishedPort int
  245. Protocol string
  246. }
  247. // ContainerSummary hold high-level description of a container
  248. type ContainerSummary struct {
  249. ID string
  250. Name string
  251. Project string
  252. Service string
  253. State string
  254. Health string
  255. Publishers []PortPublisher
  256. }
  257. // ContainerProcSummary holds container processes top data
  258. type ContainerProcSummary struct {
  259. ID string
  260. Name string
  261. Processes [][]string
  262. Titles []string
  263. }
  264. // ImageSummary holds container image description
  265. type ImageSummary struct {
  266. ID string
  267. ContainerName string
  268. Repository string
  269. Tag string
  270. Size int64
  271. }
  272. // ServiceStatus hold status about a service
  273. type ServiceStatus struct {
  274. ID string
  275. Name string
  276. Replicas int
  277. Desired int
  278. Ports []string
  279. Publishers []PortPublisher
  280. }
  281. // LogOptions defines optional parameters for the `Log` API
  282. type LogOptions struct {
  283. Services []string
  284. Tail string
  285. Follow bool
  286. Timestamps bool
  287. }
  288. // PauseOptions group options of the Pause API
  289. type PauseOptions struct {
  290. // Services passed in the command line to be started
  291. Services []string
  292. }
  293. const (
  294. // STARTING indicates that stack is being deployed
  295. STARTING string = "Starting"
  296. // RUNNING indicates that stack is deployed and services are running
  297. RUNNING string = "Running"
  298. // UPDATING indicates that some stack resources are being recreated
  299. UPDATING string = "Updating"
  300. // REMOVING indicates that stack is being deleted
  301. REMOVING string = "Removing"
  302. // UNKNOWN indicates unknown stack state
  303. UNKNOWN string = "Unknown"
  304. // FAILED indicates that stack deployment failed
  305. FAILED string = "Failed"
  306. )
  307. const (
  308. // RecreateDiverged to recreate services which configuration diverges from compose model
  309. RecreateDiverged = "diverged"
  310. // RecreateForce to force service container being recreated
  311. RecreateForce = "force"
  312. // RecreateNever to never recreate existing service containers
  313. RecreateNever = "never"
  314. )
  315. // Stack holds the name and state of a compose application/stack
  316. type Stack struct {
  317. ID string
  318. Name string
  319. Status string
  320. Reason string
  321. }
  322. // LogConsumer is a callback to process log messages from services
  323. type LogConsumer interface {
  324. Log(service, container, message string)
  325. Status(container, msg string)
  326. Register(container string)
  327. }
  328. // ContainerEventListener is a callback to process ContainerEvent from services
  329. type ContainerEventListener func(event ContainerEvent)
  330. // ContainerEvent notify an event has been collected on source container implementing Service
  331. type ContainerEvent struct {
  332. Type int
  333. Container string
  334. Service string
  335. Line string
  336. ExitCode int
  337. }
  338. const (
  339. // ContainerEventLog is a ContainerEvent of type log. Line is set
  340. ContainerEventLog = iota
  341. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  342. ContainerEventAttach
  343. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  344. ContainerEventExit
  345. // UserCancel user cancelled compose up, we are stopping containers
  346. UserCancel
  347. )