api.go 18 KB

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