api.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 api
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "time"
  19. "github.com/compose-spec/compose-go/types"
  20. "github.com/docker/compose/v2/pkg/utils"
  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 to 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, options PullOptions) error
  30. // Create executes the equivalent to a `compose create`
  31. Create(ctx context.Context, project *types.Project, options CreateOptions) error
  32. // Start executes the equivalent to a `compose start`
  33. Start(ctx context.Context, projectName string, options StartOptions) error
  34. // Restart restarts containers
  35. Restart(ctx context.Context, projectName string, options RestartOptions) error
  36. // Stop executes the equivalent to a `compose stop`
  37. Stop(ctx context.Context, projectName string, 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. // Config executes the equivalent to a `compose config`
  49. Config(ctx context.Context, project *types.Project, options ConfigOptions) ([]byte, error)
  50. // Kill executes the equivalent to a `compose kill`
  51. Kill(ctx context.Context, projectName string, 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, projectName string, options RemoveOptions) error
  56. // Exec executes a command in a running service container
  57. Exec(ctx context.Context, projectName string, options RunOptions) (int, error)
  58. // Copy copies a file/folder between a service container and the local filesystem
  59. Copy(ctx context.Context, projectName string, options CopyOptions) error
  60. // Pause executes the equivalent to a `compose pause`
  61. Pause(ctx context.Context, projectName string, options PauseOptions) error
  62. // UnPause executes the equivalent to a `compose unpause`
  63. UnPause(ctx context.Context, projectName string, options PauseOptions) error
  64. // Top executes the equivalent to a `compose top`
  65. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  66. // Events executes the equivalent to a `compose events`
  67. Events(ctx context.Context, projectName string, options EventsOptions) error
  68. // Port executes the equivalent to a `compose port`
  69. Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error)
  70. // Images executes the equivalent of a `compose images`
  71. Images(ctx context.Context, projectName string, options ImagesOptions) ([]ImageSummary, error)
  72. // MaxConcurrency defines upper limit for concurrent operations against engine API
  73. MaxConcurrency(parallel int)
  74. // DryRunMode defines if dry run applies to the command
  75. DryRunMode(ctx context.Context, dryRun bool) (context.Context, error)
  76. // Watch services' development context and sync/notify/rebuild/restart on changes
  77. Watch(ctx context.Context, project *types.Project, services []string, options WatchOptions) error
  78. // Viz generates a graphviz graph of the project services
  79. Viz(ctx context.Context, project *types.Project, options VizOptions) (string, error)
  80. // Wait blocks until at least one of the services' container exits
  81. Wait(ctx context.Context, projectName string, options WaitOptions) (int64, error)
  82. }
  83. type WaitOptions struct {
  84. // Services passed in the command line to be waited
  85. Services []string
  86. // Executes a down when a container exits
  87. DownProjectOnContainerExit bool
  88. }
  89. type VizOptions struct {
  90. // IncludeNetworks if true, network names a container is attached to should appear in the graph node
  91. IncludeNetworks bool
  92. // IncludePorts if true, ports a container exposes should appear in the graph node
  93. IncludePorts bool
  94. // IncludeImageName if true, name of the image used to create a container should appear in the graph node
  95. IncludeImageName bool
  96. // Indentation string to be used to indent graphviz code, e.g. "\t", " "
  97. Indentation string
  98. }
  99. // WatchOptions group options of the Watch API
  100. type WatchOptions struct {
  101. }
  102. // BuildOptions group options of the Build API
  103. type BuildOptions struct {
  104. // Pull always attempt to pull a newer version of the image
  105. Pull bool
  106. // Push pushes service images
  107. Push bool
  108. // Progress set type of progress output ("auto", "plain", "tty")
  109. Progress string
  110. // Args set build-time args
  111. Args types.MappingWithEquals
  112. // NoCache disables cache use
  113. NoCache bool
  114. // Quiet make the build process not output to the console
  115. Quiet bool
  116. // Services passed in the command line to be built
  117. Services []string
  118. // Ssh authentications passed in the command line
  119. SSHs []types.SSHKey
  120. // Memory limit for the build container
  121. Memory int64
  122. // Builder name passed in the command line
  123. Builder string
  124. }
  125. // Apply mutates project according to build options
  126. func (o BuildOptions) Apply(project *types.Project) error {
  127. platform := project.Environment["DOCKER_DEFAULT_PLATFORM"]
  128. for i, service := range project.Services {
  129. if service.Image == "" && service.Build == nil {
  130. return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  131. }
  132. if service.Build == nil {
  133. continue
  134. }
  135. if platform != "" {
  136. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, platform) {
  137. return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", service.Name, platform)
  138. }
  139. service.Platform = platform
  140. }
  141. if service.Platform != "" {
  142. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, service.Platform) {
  143. return fmt.Errorf("service %q build configuration does not support platform: %s", service.Name, service.Platform)
  144. }
  145. }
  146. service.Build.Pull = service.Build.Pull || o.Pull
  147. service.Build.NoCache = service.Build.NoCache || o.NoCache
  148. project.Services[i] = service
  149. }
  150. return nil
  151. }
  152. // CreateOptions group options of the Create API
  153. type CreateOptions struct {
  154. // Services defines the services user interacts with
  155. Services []string
  156. // Remove legacy containers for services that are not defined in the project
  157. RemoveOrphans bool
  158. // Ignore legacy containers for services that are not defined in the project
  159. IgnoreOrphans bool
  160. // Recreate define the strategy to apply on existing containers
  161. Recreate string
  162. // RecreateDependencies define the strategy to apply on dependencies services
  163. RecreateDependencies string
  164. // Inherit reuse anonymous volumes from previous container
  165. Inherit bool
  166. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  167. Timeout *time.Duration
  168. // QuietPull makes the pulling process quiet
  169. QuietPull bool
  170. }
  171. // StartOptions group options of the Start API
  172. type StartOptions struct {
  173. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  174. Project *types.Project
  175. // Attach to container and forward logs if not nil
  176. Attach LogConsumer
  177. // AttachTo set the services to attach to
  178. AttachTo []string
  179. // CascadeStop stops the application when a container stops
  180. CascadeStop bool
  181. // ExitCodeFrom return exit code from specified service
  182. ExitCodeFrom string
  183. // Wait won't return until containers reached the running|healthy state
  184. Wait bool
  185. WaitTimeout time.Duration
  186. // Services passed in the command line to be started
  187. Services []string
  188. }
  189. // RestartOptions group options of the Restart API
  190. type RestartOptions struct {
  191. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  192. Project *types.Project
  193. // Timeout override container restart timeout
  194. Timeout *time.Duration
  195. // Services passed in the command line to be restarted
  196. Services []string
  197. }
  198. // StopOptions group options of the Stop API
  199. type StopOptions struct {
  200. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  201. Project *types.Project
  202. // Timeout override container stop timeout
  203. Timeout *time.Duration
  204. // Services passed in the command line to be stopped
  205. Services []string
  206. }
  207. // UpOptions group options of the Up API
  208. type UpOptions struct {
  209. Create CreateOptions
  210. Start StartOptions
  211. }
  212. // DownOptions group options of the Down API
  213. type DownOptions struct {
  214. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  215. RemoveOrphans bool
  216. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  217. Project *types.Project
  218. // Timeout override container stop timeout
  219. Timeout *time.Duration
  220. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  221. Images string
  222. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  223. Volumes bool
  224. // Services passed in the command line to be stopped
  225. Services []string
  226. }
  227. // ConfigOptions group options of the Config API
  228. type ConfigOptions struct {
  229. // Format define the output format used to dump converted application model (json|yaml)
  230. Format string
  231. // Output defines the path to save the application model
  232. Output string
  233. // Resolve image reference to digests
  234. ResolveImageDigests bool
  235. }
  236. // PushOptions group options of the Push API
  237. type PushOptions struct {
  238. Quiet bool
  239. IgnoreFailures bool
  240. }
  241. // PullOptions group options of the Pull API
  242. type PullOptions struct {
  243. Quiet bool
  244. IgnoreFailures bool
  245. IgnoreBuildable bool
  246. }
  247. // ImagesOptions group options of the Images API
  248. type ImagesOptions struct {
  249. Services []string
  250. }
  251. // KillOptions group options of the Kill API
  252. type KillOptions struct {
  253. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  254. RemoveOrphans bool
  255. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  256. Project *types.Project
  257. // Services passed in the command line to be killed
  258. Services []string
  259. // Signal to send to containers
  260. Signal string
  261. }
  262. // RemoveOptions group options of the Remove API
  263. type RemoveOptions struct {
  264. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  265. Project *types.Project
  266. // Stop option passed in the command line
  267. Stop bool
  268. // Volumes remove anonymous volumes
  269. Volumes bool
  270. // Force don't ask to confirm removal
  271. Force bool
  272. // Services passed in the command line to be removed
  273. Services []string
  274. }
  275. // RunOptions group options of the Run API
  276. type RunOptions struct {
  277. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  278. Project *types.Project
  279. Name string
  280. Service string
  281. Command []string
  282. Entrypoint []string
  283. Detach bool
  284. AutoRemove bool
  285. Tty bool
  286. Interactive bool
  287. WorkingDir string
  288. User string
  289. Environment []string
  290. CapAdd []string
  291. CapDrop []string
  292. Labels types.Labels
  293. Privileged bool
  294. UseNetworkAliases bool
  295. NoDeps bool
  296. // QuietPull makes the pulling process quiet
  297. QuietPull bool
  298. // used by exec
  299. Index int
  300. }
  301. // EventsOptions group options of the Events API
  302. type EventsOptions struct {
  303. Services []string
  304. Consumer func(event Event) error
  305. }
  306. // Event is a container runtime event served by Events API
  307. type Event struct {
  308. Timestamp time.Time
  309. Service string
  310. Container string
  311. Status string
  312. Attributes map[string]string
  313. }
  314. // PortOptions group options of the Port API
  315. type PortOptions struct {
  316. Protocol string
  317. Index int
  318. }
  319. func (e Event) String() string {
  320. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  321. var attr []string
  322. for k, v := range e.Attributes {
  323. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  324. }
  325. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  326. }
  327. // ListOptions group options of the ls API
  328. type ListOptions struct {
  329. All bool
  330. }
  331. // PsOptions group options of the Ps API
  332. type PsOptions struct {
  333. Project *types.Project
  334. All bool
  335. Services []string
  336. }
  337. // CopyOptions group options of the cp API
  338. type CopyOptions struct {
  339. Source string
  340. Destination string
  341. All bool
  342. Index int
  343. FollowLink bool
  344. CopyUIDGID bool
  345. }
  346. // PortPublisher hold status about published port
  347. type PortPublisher struct {
  348. URL string
  349. TargetPort int
  350. PublishedPort int
  351. Protocol string
  352. }
  353. // ContainerSummary hold high-level description of a container
  354. type ContainerSummary struct {
  355. ID string
  356. Name string
  357. Image string
  358. Command string
  359. Project string
  360. Service string
  361. Created int64
  362. State string
  363. Status string
  364. Health string
  365. ExitCode int
  366. Publishers PortPublishers
  367. }
  368. // PortPublishers is a slice of PortPublisher
  369. type PortPublishers []PortPublisher
  370. // Len implements sort.Interface
  371. func (p PortPublishers) Len() int {
  372. return len(p)
  373. }
  374. // Less implements sort.Interface
  375. func (p PortPublishers) Less(i, j int) bool {
  376. left := p[i]
  377. right := p[j]
  378. if left.URL != right.URL {
  379. return left.URL < right.URL
  380. }
  381. if left.TargetPort != right.TargetPort {
  382. return left.TargetPort < right.TargetPort
  383. }
  384. if left.PublishedPort != right.PublishedPort {
  385. return left.PublishedPort < right.PublishedPort
  386. }
  387. return left.Protocol < right.Protocol
  388. }
  389. // Swap implements sort.Interface
  390. func (p PortPublishers) Swap(i, j int) {
  391. p[i], p[j] = p[j], p[i]
  392. }
  393. // ContainerProcSummary holds container processes top data
  394. type ContainerProcSummary struct {
  395. ID string
  396. Name string
  397. Processes [][]string
  398. Titles []string
  399. }
  400. // ImageSummary holds container image description
  401. type ImageSummary struct {
  402. ID string
  403. ContainerName string
  404. Repository string
  405. Tag string
  406. Size int64
  407. }
  408. // ServiceStatus hold status about a service
  409. type ServiceStatus struct {
  410. ID string
  411. Name string
  412. Replicas int
  413. Desired int
  414. Ports []string
  415. Publishers []PortPublisher
  416. }
  417. // LogOptions defines optional parameters for the `Log` API
  418. type LogOptions struct {
  419. Project *types.Project
  420. Services []string
  421. Tail string
  422. Since string
  423. Until string
  424. Follow bool
  425. Timestamps bool
  426. }
  427. // PauseOptions group options of the Pause API
  428. type PauseOptions struct {
  429. // Services passed in the command line to be started
  430. Services []string
  431. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  432. Project *types.Project
  433. }
  434. const (
  435. // STARTING indicates that stack is being deployed
  436. STARTING string = "Starting"
  437. // RUNNING indicates that stack is deployed and services are running
  438. RUNNING string = "Running"
  439. // UPDATING indicates that some stack resources are being recreated
  440. UPDATING string = "Updating"
  441. // REMOVING indicates that stack is being deleted
  442. REMOVING string = "Removing"
  443. // UNKNOWN indicates unknown stack state
  444. UNKNOWN string = "Unknown"
  445. // FAILED indicates that stack deployment failed
  446. FAILED string = "Failed"
  447. )
  448. const (
  449. // RecreateDiverged to recreate services which configuration diverges from compose model
  450. RecreateDiverged = "diverged"
  451. // RecreateForce to force service container being recreated
  452. RecreateForce = "force"
  453. // RecreateNever to never recreate existing service containers
  454. RecreateNever = "never"
  455. )
  456. // Stack holds the name and state of a compose application/stack
  457. type Stack struct {
  458. ID string
  459. Name string
  460. Status string
  461. ConfigFiles string
  462. Reason string
  463. }
  464. // LogConsumer is a callback to process log messages from services
  465. type LogConsumer interface {
  466. Log(containerName, message string)
  467. Err(containerName, message string)
  468. Status(container, msg string)
  469. Register(container string)
  470. }
  471. // ContainerEventListener is a callback to process ContainerEvent from services
  472. type ContainerEventListener func(event ContainerEvent)
  473. // ContainerEvent notify an event has been collected on source container implementing Service
  474. type ContainerEvent struct {
  475. Type int
  476. // Container is the name of the container _without the project prefix_.
  477. //
  478. // This is only suitable for display purposes within Compose, as it's
  479. // not guaranteed to be unique across services.
  480. Container string
  481. ID string
  482. Service string
  483. Line string
  484. // ContainerEventExit only
  485. ExitCode int
  486. Restarting bool
  487. }
  488. const (
  489. // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set
  490. ContainerEventLog = iota
  491. // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set
  492. ContainerEventErr
  493. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  494. ContainerEventAttach
  495. // ContainerEventStopped is a ContainerEvent of type stopped.
  496. ContainerEventStopped
  497. // ContainerEventRecreated let consumer know container stopped but his being replaced
  498. ContainerEventRecreated
  499. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  500. ContainerEventExit
  501. // UserCancel user cancelled compose up, we are stopping containers
  502. UserCancel
  503. )
  504. // Separator is used for naming components
  505. var Separator = "-"
  506. // GetImageNameOrDefault computes the default image name for a service, used to tag built images
  507. func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string {
  508. imageName := service.Image
  509. if imageName == "" {
  510. imageName = projectName + Separator + service.Name
  511. }
  512. return imageName
  513. }