api.go 18 KB

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