api.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. }
  216. // ConfigOptions group options of the Config API
  217. type ConfigOptions struct {
  218. // Format define the output format used to dump converted application model (json|yaml)
  219. Format string
  220. // Output defines the path to save the application model
  221. Output string
  222. // Resolve image reference to digests
  223. ResolveImageDigests bool
  224. }
  225. // PushOptions group options of the Push API
  226. type PushOptions struct {
  227. Quiet bool
  228. IgnoreFailures bool
  229. }
  230. // PullOptions group options of the Pull API
  231. type PullOptions struct {
  232. Quiet bool
  233. IgnoreFailures bool
  234. IgnoreBuildable bool
  235. }
  236. // ImagesOptions group options of the Images API
  237. type ImagesOptions struct {
  238. Services []string
  239. }
  240. // KillOptions group options of the Kill API
  241. type KillOptions struct {
  242. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  243. RemoveOrphans bool
  244. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  245. Project *types.Project
  246. // Services passed in the command line to be killed
  247. Services []string
  248. // Signal to send to containers
  249. Signal string
  250. }
  251. // RemoveOptions group options of the Remove API
  252. type RemoveOptions struct {
  253. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  254. Project *types.Project
  255. // Stop option passed in the command line
  256. Stop bool
  257. // Volumes remove anonymous volumes
  258. Volumes bool
  259. // Force don't ask to confirm removal
  260. Force bool
  261. // Services passed in the command line to be removed
  262. Services []string
  263. }
  264. // RunOptions group options of the Run API
  265. type RunOptions struct {
  266. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  267. Project *types.Project
  268. Name string
  269. Service string
  270. Command []string
  271. Entrypoint []string
  272. Detach bool
  273. AutoRemove bool
  274. Tty bool
  275. Interactive bool
  276. WorkingDir string
  277. User string
  278. Environment []string
  279. Labels types.Labels
  280. Privileged bool
  281. UseNetworkAliases bool
  282. NoDeps bool
  283. // QuietPull makes the pulling process quiet
  284. QuietPull bool
  285. // used by exec
  286. Index int
  287. }
  288. // EventsOptions group options of the Events API
  289. type EventsOptions struct {
  290. Services []string
  291. Consumer func(event Event) error
  292. }
  293. // Event is a container runtime event served by Events API
  294. type Event struct {
  295. Timestamp time.Time
  296. Service string
  297. Container string
  298. Status string
  299. Attributes map[string]string
  300. }
  301. // PortOptions group options of the Port API
  302. type PortOptions struct {
  303. Protocol string
  304. Index int
  305. }
  306. func (e Event) String() string {
  307. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  308. var attr []string
  309. for k, v := range e.Attributes {
  310. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  311. }
  312. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  313. }
  314. // ListOptions group options of the ls API
  315. type ListOptions struct {
  316. All bool
  317. }
  318. // PsOptions group options of the Ps API
  319. type PsOptions struct {
  320. Project *types.Project
  321. All bool
  322. Services []string
  323. }
  324. // CopyOptions group options of the cp API
  325. type CopyOptions struct {
  326. Source string
  327. Destination string
  328. All bool
  329. Index int
  330. FollowLink bool
  331. CopyUIDGID bool
  332. }
  333. // PortPublisher hold status about published port
  334. type PortPublisher struct {
  335. URL string
  336. TargetPort int
  337. PublishedPort int
  338. Protocol string
  339. }
  340. // ContainerSummary hold high-level description of a container
  341. type ContainerSummary struct {
  342. ID string
  343. Name string
  344. Image any
  345. Command string
  346. Project string
  347. Service string
  348. Created int64
  349. State string
  350. Status string
  351. Health string
  352. ExitCode int
  353. Publishers PortPublishers
  354. }
  355. // PortPublishers is a slice of PortPublisher
  356. type PortPublishers []PortPublisher
  357. // Len implements sort.Interface
  358. func (p PortPublishers) Len() int {
  359. return len(p)
  360. }
  361. // Less implements sort.Interface
  362. func (p PortPublishers) Less(i, j int) bool {
  363. left := p[i]
  364. right := p[j]
  365. if left.URL != right.URL {
  366. return left.URL < right.URL
  367. }
  368. if left.TargetPort != right.TargetPort {
  369. return left.TargetPort < right.TargetPort
  370. }
  371. if left.PublishedPort != right.PublishedPort {
  372. return left.PublishedPort < right.PublishedPort
  373. }
  374. return left.Protocol < right.Protocol
  375. }
  376. // Swap implements sort.Interface
  377. func (p PortPublishers) Swap(i, j int) {
  378. p[i], p[j] = p[j], p[i]
  379. }
  380. // ContainerProcSummary holds container processes top data
  381. type ContainerProcSummary struct {
  382. ID string
  383. Name string
  384. Processes [][]string
  385. Titles []string
  386. }
  387. // ImageSummary holds container image description
  388. type ImageSummary struct {
  389. ID string
  390. ContainerName string
  391. Repository string
  392. Tag string
  393. Size int64
  394. }
  395. // ServiceStatus hold status about a service
  396. type ServiceStatus struct {
  397. ID string
  398. Name string
  399. Replicas int
  400. Desired int
  401. Ports []string
  402. Publishers []PortPublisher
  403. }
  404. // LogOptions defines optional parameters for the `Log` API
  405. type LogOptions struct {
  406. Project *types.Project
  407. Services []string
  408. Tail string
  409. Since string
  410. Until string
  411. Follow bool
  412. Timestamps bool
  413. }
  414. // PauseOptions group options of the Pause API
  415. type PauseOptions struct {
  416. // Services passed in the command line to be started
  417. Services []string
  418. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  419. Project *types.Project
  420. }
  421. const (
  422. // STARTING indicates that stack is being deployed
  423. STARTING string = "Starting"
  424. // RUNNING indicates that stack is deployed and services are running
  425. RUNNING string = "Running"
  426. // UPDATING indicates that some stack resources are being recreated
  427. UPDATING string = "Updating"
  428. // REMOVING indicates that stack is being deleted
  429. REMOVING string = "Removing"
  430. // UNKNOWN indicates unknown stack state
  431. UNKNOWN string = "Unknown"
  432. // FAILED indicates that stack deployment failed
  433. FAILED string = "Failed"
  434. )
  435. const (
  436. // RecreateDiverged to recreate services which configuration diverges from compose model
  437. RecreateDiverged = "diverged"
  438. // RecreateForce to force service container being recreated
  439. RecreateForce = "force"
  440. // RecreateNever to never recreate existing service containers
  441. RecreateNever = "never"
  442. )
  443. // Stack holds the name and state of a compose application/stack
  444. type Stack struct {
  445. ID string
  446. Name string
  447. Status string
  448. ConfigFiles string
  449. Reason string
  450. }
  451. // LogConsumer is a callback to process log messages from services
  452. type LogConsumer interface {
  453. Log(containerName, message string)
  454. Err(containerName, message string)
  455. Status(container, msg string)
  456. Register(container string)
  457. }
  458. // ContainerEventListener is a callback to process ContainerEvent from services
  459. type ContainerEventListener func(event ContainerEvent)
  460. // ContainerEvent notify an event has been collected on source container implementing Service
  461. type ContainerEvent struct {
  462. Type int
  463. // Container is the name of the container _without the project prefix_.
  464. //
  465. // This is only suitable for display purposes within Compose, as it's
  466. // not guaranteed to be unique across services.
  467. Container string
  468. ID string
  469. Service string
  470. Line string
  471. // ContainerEventExit only
  472. ExitCode int
  473. Restarting bool
  474. }
  475. const (
  476. // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set
  477. ContainerEventLog = iota
  478. // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set
  479. ContainerEventErr
  480. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  481. ContainerEventAttach
  482. // ContainerEventStopped is a ContainerEvent of type stopped.
  483. ContainerEventStopped
  484. // ContainerEventRecreated let consumer know container stopped but his being replaced
  485. ContainerEventRecreated
  486. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  487. ContainerEventExit
  488. // UserCancel user cancelled compose up, we are stopping containers
  489. UserCancel
  490. )
  491. // Separator is used for naming components
  492. var Separator = "-"
  493. // GetImageNameOrDefault computes the default image name for a service, used to tag built images
  494. func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string {
  495. imageName := service.Image
  496. if imageName == "" {
  497. imageName = projectName + Separator + service.Name
  498. }
  499. return imageName
  500. }