api.go 18 KB

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