api.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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. "io"
  18. "slices"
  19. "strings"
  20. "time"
  21. "github.com/compose-spec/compose-go/v2/cli"
  22. "github.com/compose-spec/compose-go/v2/types"
  23. "github.com/containerd/platforms"
  24. "github.com/docker/cli/opts"
  25. "github.com/docker/docker/api/types/volume"
  26. )
  27. // LoadListener receives events during project loading.
  28. // Events include:
  29. // - "extends": when a service extends another (metadata: service info)
  30. // - "include": when including external compose files (metadata: {"path": StringList})
  31. //
  32. // Multiple listeners can be registered, and all will be notified of events.
  33. type LoadListener func(event string, metadata map[string]any)
  34. // ProjectLoadOptions configures how a Compose project should be loaded
  35. type ProjectLoadOptions struct {
  36. // ProjectName to use, or empty to infer from directory
  37. ProjectName string
  38. // ConfigPaths are paths to compose files
  39. ConfigPaths []string
  40. // WorkingDir is the project directory
  41. WorkingDir string
  42. // EnvFiles are paths to .env files
  43. EnvFiles []string
  44. // Profiles to activate
  45. Profiles []string
  46. // Services to select (empty = all)
  47. Services []string
  48. // Offline mode disables remote resource loading
  49. Offline bool
  50. // All includes all resources (not just those used by services)
  51. All bool
  52. // Compatibility enables v1 compatibility mode
  53. Compatibility bool
  54. // ProjectOptionsFns are compose-go project options to apply.
  55. // Use cli.WithInterpolation(false), cli.WithNormalization(false), etc.
  56. // This is optional - pass nil or empty slice to use defaults.
  57. ProjectOptionsFns []cli.ProjectOptionsFn
  58. // LoadListeners receive events during project loading.
  59. // All registered listeners will be notified of events.
  60. // This is optional - pass nil or empty slice if not needed.
  61. LoadListeners []LoadListener
  62. }
  63. // Compose is the API interface one can use to programmatically use docker/compose in a third-party software
  64. // Use [compose.NewComposeService] to get an actual instance
  65. type Compose interface {
  66. // Build executes the equivalent to a `compose build`
  67. Build(ctx context.Context, project *types.Project, options BuildOptions) error
  68. // Push executes the equivalent to a `compose push`
  69. Push(ctx context.Context, project *types.Project, options PushOptions) error
  70. // Pull executes the equivalent of a `compose pull`
  71. Pull(ctx context.Context, project *types.Project, options PullOptions) error
  72. // Create executes the equivalent to a `compose create`
  73. Create(ctx context.Context, project *types.Project, options CreateOptions) error
  74. // Start executes the equivalent to a `compose start`
  75. Start(ctx context.Context, projectName string, options StartOptions) error
  76. // Restart restarts containers
  77. Restart(ctx context.Context, projectName string, options RestartOptions) error
  78. // Stop executes the equivalent to a `compose stop`
  79. Stop(ctx context.Context, projectName string, options StopOptions) error
  80. // Up executes the equivalent to a `compose up`
  81. Up(ctx context.Context, project *types.Project, options UpOptions) error
  82. // Down executes the equivalent to a `compose down`
  83. Down(ctx context.Context, projectName string, options DownOptions) error
  84. // Logs executes the equivalent to a `compose logs`
  85. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  86. // Ps executes the equivalent to a `compose ps`
  87. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  88. // List executes the equivalent to a `docker stack ls`
  89. List(ctx context.Context, options ListOptions) ([]Stack, error)
  90. // Kill executes the equivalent to a `compose kill`
  91. Kill(ctx context.Context, projectName string, options KillOptions) error
  92. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  93. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  94. // Remove executes the equivalent to a `compose rm`
  95. Remove(ctx context.Context, projectName string, options RemoveOptions) error
  96. // Exec executes a command in a running service container
  97. Exec(ctx context.Context, projectName string, options RunOptions) (int, error)
  98. // Attach STDIN,STDOUT,STDERR to a running service container
  99. Attach(ctx context.Context, projectName string, options AttachOptions) error
  100. // Copy copies a file/folder between a service container and the local filesystem
  101. Copy(ctx context.Context, projectName string, options CopyOptions) error
  102. // Pause executes the equivalent to a `compose pause`
  103. Pause(ctx context.Context, projectName string, options PauseOptions) error
  104. // UnPause executes the equivalent to a `compose unpause`
  105. UnPause(ctx context.Context, projectName string, options PauseOptions) error
  106. // Top executes the equivalent to a `compose top`
  107. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  108. // Events executes the equivalent to a `compose events`
  109. Events(ctx context.Context, projectName string, options EventsOptions) error
  110. // Port executes the equivalent to a `compose port`
  111. Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error)
  112. // Publish executes the equivalent to a `compose publish`
  113. Publish(ctx context.Context, project *types.Project, repository string, options PublishOptions) error
  114. // Images executes the equivalent of a `compose images`
  115. Images(ctx context.Context, projectName string, options ImagesOptions) (map[string]ImageSummary, error)
  116. // Watch services' development context and sync/notify/rebuild/restart on changes
  117. Watch(ctx context.Context, project *types.Project, options WatchOptions) error
  118. // Viz generates a graphviz graph of the project services
  119. Viz(ctx context.Context, project *types.Project, options VizOptions) (string, error)
  120. // Wait blocks until at least one of the services' container exits
  121. Wait(ctx context.Context, projectName string, options WaitOptions) (int64, error)
  122. // Scale manages numbers of container instances running per service
  123. Scale(ctx context.Context, project *types.Project, options ScaleOptions) error
  124. // Export a service container's filesystem as a tar archive
  125. Export(ctx context.Context, projectName string, options ExportOptions) error
  126. // Create a new image from a service container's changes
  127. Commit(ctx context.Context, projectName string, options CommitOptions) error
  128. // Generate generates a Compose Project from existing containers
  129. Generate(ctx context.Context, options GenerateOptions) (*types.Project, error)
  130. // Volumes executes the equivalent to a `docker volume ls`
  131. Volumes(ctx context.Context, project string, options VolumesOptions) ([]VolumesSummary, error)
  132. // GetConfiguredStreams returns the configured I/O streams (stdout, stderr, stdin).
  133. // If no custom streams were configured, it returns the dockerCli streams.
  134. GetConfiguredStreams() (stdout io.Writer, stderr io.Writer, stdin io.Reader)
  135. // LoadProject loads and validates a Compose project from configuration files.
  136. LoadProject(ctx context.Context, options ProjectLoadOptions) (*types.Project, error)
  137. }
  138. type VolumesOptions struct {
  139. Services []string
  140. }
  141. type VolumesSummary = *volume.Volume
  142. type ScaleOptions struct {
  143. Services []string
  144. }
  145. type WaitOptions struct {
  146. // Services passed in the command line to be waited
  147. Services []string
  148. // Executes a down when a container exits
  149. DownProjectOnContainerExit bool
  150. }
  151. type VizOptions struct {
  152. // IncludeNetworks if true, network names a container is attached to should appear in the graph node
  153. IncludeNetworks bool
  154. // IncludePorts if true, ports a container exposes should appear in the graph node
  155. IncludePorts bool
  156. // IncludeImageName if true, name of the image used to create a container should appear in the graph node
  157. IncludeImageName bool
  158. // Indentation string to be used to indent graphviz code, e.g. "\t", " "
  159. Indentation string
  160. }
  161. // WatchLogger is a reserved name to log watch events
  162. const WatchLogger = "#watch"
  163. // WatchOptions group options of the Watch API
  164. type WatchOptions struct {
  165. Build *BuildOptions
  166. LogTo LogConsumer
  167. Prune bool
  168. Services []string
  169. }
  170. // BuildOptions group options of the Build API
  171. type BuildOptions struct {
  172. // Pull always attempt to pull a newer version of the image
  173. Pull bool
  174. // Push pushes service images
  175. Push bool
  176. // Progress set type of progress output ("auto", "plain", "tty")
  177. Progress string
  178. // Args set build-time args
  179. Args types.MappingWithEquals
  180. // NoCache disables cache use
  181. NoCache bool
  182. // Quiet make the build process not output to the console
  183. Quiet bool
  184. // Services passed in the command line to be built
  185. Services []string
  186. // Deps also build selected services dependencies
  187. Deps bool
  188. // Ssh authentications passed in the command line
  189. SSHs []types.SSHKey
  190. // Memory limit for the build container
  191. Memory int64
  192. // Builder name passed in the command line
  193. Builder string
  194. // Print don't actually run builder but print equivalent build config
  195. Print bool
  196. // Check let builder validate build configuration
  197. Check bool
  198. // Attestations allows to enable attestations generation
  199. Attestations bool
  200. // Provenance generate a provenance attestation
  201. Provenance string
  202. // SBOM generate a SBOM attestation
  203. SBOM string
  204. // Out is the stream to write build progress
  205. Out io.Writer
  206. }
  207. // Apply mutates project according to build options
  208. func (o BuildOptions) Apply(project *types.Project) error {
  209. platform := project.Environment["DOCKER_DEFAULT_PLATFORM"]
  210. for name, service := range project.Services {
  211. if service.Provider == nil && service.Image == "" && service.Build == nil {
  212. return fmt.Errorf("invalid service %q. Must specify either image or build", name)
  213. }
  214. if service.Build == nil {
  215. continue
  216. }
  217. if platform != "" {
  218. if len(service.Build.Platforms) > 0 && !slices.Contains(service.Build.Platforms, platform) {
  219. return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", name, platform)
  220. }
  221. service.Platform = platform
  222. }
  223. if service.Platform != "" {
  224. if len(service.Build.Platforms) > 0 && !slices.Contains(service.Build.Platforms, service.Platform) {
  225. return fmt.Errorf("service %q build configuration does not support platform: %s", name, service.Platform)
  226. }
  227. }
  228. service.Build.Pull = service.Build.Pull || o.Pull
  229. service.Build.NoCache = service.Build.NoCache || o.NoCache
  230. project.Services[name] = service
  231. }
  232. return nil
  233. }
  234. // CreateOptions group options of the Create API
  235. type CreateOptions struct {
  236. Build *BuildOptions
  237. // Services defines the services user interacts with
  238. Services []string
  239. // Remove legacy containers for services that are not defined in the project
  240. RemoveOrphans bool
  241. // Ignore legacy containers for services that are not defined in the project
  242. IgnoreOrphans bool
  243. // Recreate define the strategy to apply on existing containers
  244. Recreate string
  245. // RecreateDependencies define the strategy to apply on dependencies services
  246. RecreateDependencies string
  247. // Inherit reuse anonymous volumes from previous container
  248. Inherit bool
  249. // Timeout set delay to wait for container to gracefully stop before sending SIGKILL
  250. Timeout *time.Duration
  251. // QuietPull makes the pulling process quiet
  252. QuietPull bool
  253. }
  254. // StartOptions group options of the Start API
  255. type StartOptions struct {
  256. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  257. Project *types.Project
  258. // Attach to container and forward logs if not nil
  259. Attach LogConsumer
  260. // AttachTo set the services to attach to
  261. AttachTo []string
  262. // OnExit defines behavior when a container stops
  263. OnExit Cascade
  264. // ExitCodeFrom return exit code from specified service
  265. ExitCodeFrom string
  266. // Wait won't return until containers reached the running|healthy state
  267. Wait bool
  268. WaitTimeout time.Duration
  269. // Services passed in the command line to be started
  270. Services []string
  271. Watch bool
  272. NavigationMenu bool
  273. }
  274. type Cascade int
  275. const (
  276. CascadeIgnore Cascade = iota
  277. CascadeStop Cascade = iota
  278. CascadeFail Cascade = iota
  279. )
  280. // RestartOptions group options of the Restart API
  281. type RestartOptions struct {
  282. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  283. Project *types.Project
  284. // Timeout override container restart timeout
  285. Timeout *time.Duration
  286. // Services passed in the command line to be restarted
  287. Services []string
  288. // NoDeps ignores services dependencies
  289. NoDeps bool
  290. }
  291. // StopOptions group options of the Stop API
  292. type StopOptions struct {
  293. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  294. Project *types.Project
  295. // Timeout override container stop timeout
  296. Timeout *time.Duration
  297. // Services passed in the command line to be stopped
  298. Services []string
  299. }
  300. // UpOptions group options of the Up API
  301. type UpOptions struct {
  302. Create CreateOptions
  303. Start StartOptions
  304. }
  305. // DownOptions group options of the Down API
  306. type DownOptions struct {
  307. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  308. RemoveOrphans bool
  309. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  310. Project *types.Project
  311. // Timeout override container stop timeout
  312. Timeout *time.Duration
  313. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  314. Images string
  315. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  316. Volumes bool
  317. // Services passed in the command line to be stopped
  318. Services []string
  319. }
  320. // ConfigOptions group options of the Config API
  321. type ConfigOptions struct {
  322. // Format define the output format used to dump converted application model (json|yaml)
  323. Format string
  324. // Output defines the path to save the application model
  325. Output string
  326. // Resolve image reference to digests
  327. ResolveImageDigests bool
  328. }
  329. // PushOptions group options of the Push API
  330. type PushOptions struct {
  331. Quiet bool
  332. IgnoreFailures bool
  333. ImageMandatory bool
  334. }
  335. // PullOptions group options of the Pull API
  336. type PullOptions struct {
  337. Quiet bool
  338. IgnoreFailures bool
  339. IgnoreBuildable bool
  340. }
  341. // ImagesOptions group options of the Images API
  342. type ImagesOptions struct {
  343. Services []string
  344. }
  345. // KillOptions group options of the Kill API
  346. type KillOptions struct {
  347. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  348. RemoveOrphans bool
  349. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  350. Project *types.Project
  351. // Services passed in the command line to be killed
  352. Services []string
  353. // Signal to send to containers
  354. Signal string
  355. // All can be set to true to try to kill all found containers, independently of their state
  356. All bool
  357. }
  358. // RemoveOptions group options of the Remove API
  359. type RemoveOptions struct {
  360. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  361. Project *types.Project
  362. // Stop option passed in the command line
  363. Stop bool
  364. // Volumes remove anonymous volumes
  365. Volumes bool
  366. // Force don't ask to confirm removal
  367. Force bool
  368. // Services passed in the command line to be removed
  369. Services []string
  370. }
  371. // RunOptions group options of the Run API
  372. type RunOptions struct {
  373. CreateOptions
  374. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  375. Project *types.Project
  376. Name string
  377. Service string
  378. Command []string
  379. Entrypoint []string
  380. Detach bool
  381. AutoRemove bool
  382. Tty bool
  383. Interactive bool
  384. WorkingDir string
  385. User string
  386. Environment []string
  387. CapAdd []string
  388. CapDrop []string
  389. Labels types.Labels
  390. Privileged bool
  391. UseNetworkAliases bool
  392. NoDeps bool
  393. // used by exec
  394. Index int
  395. }
  396. // AttachOptions group options of the Attach API
  397. type AttachOptions struct {
  398. Project *types.Project
  399. Service string
  400. Index int
  401. DetachKeys string
  402. NoStdin bool
  403. Proxy bool
  404. }
  405. // EventsOptions group options of the Events API
  406. type EventsOptions struct {
  407. Services []string
  408. Consumer func(event Event) error
  409. Since string
  410. Until string
  411. }
  412. // Event is a container runtime event served by Events API
  413. type Event struct {
  414. Timestamp time.Time
  415. Service string
  416. Container string
  417. Status string
  418. Attributes map[string]string
  419. }
  420. // PortOptions group options of the Port API
  421. type PortOptions struct {
  422. Protocol string
  423. Index int
  424. }
  425. // OCIVersion controls manifest generation to ensure compatibility
  426. // with different registries.
  427. //
  428. // Currently, this is not exposed as an option to the user – Compose uses
  429. // OCI 1.0 mode automatically for ECR registries based on domain and OCI 1.1
  430. // for all other registries.
  431. //
  432. // There are likely other popular registries that do not support the OCI 1.1
  433. // format, so it might make sense to expose this as a CLI flag or see if
  434. // there's a way to generically probe the registry for support level.
  435. type OCIVersion string
  436. const (
  437. OCIVersion1_0 OCIVersion = "1.0"
  438. OCIVersion1_1 OCIVersion = "1.1"
  439. )
  440. // PublishOptions group options of the Publish API
  441. type PublishOptions struct {
  442. ResolveImageDigests bool
  443. Application bool
  444. WithEnvironment bool
  445. OCIVersion OCIVersion
  446. }
  447. func (e Event) String() string {
  448. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  449. var attr []string
  450. for k, v := range e.Attributes {
  451. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  452. }
  453. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  454. }
  455. // ListOptions group options of the ls API
  456. type ListOptions struct {
  457. All bool
  458. }
  459. // PsOptions group options of the Ps API
  460. type PsOptions struct {
  461. Project *types.Project
  462. All bool
  463. Services []string
  464. }
  465. // CopyOptions group options of the cp API
  466. type CopyOptions struct {
  467. Source string
  468. Destination string
  469. All bool
  470. Index int
  471. FollowLink bool
  472. CopyUIDGID bool
  473. }
  474. // PortPublisher hold status about published port
  475. type PortPublisher struct {
  476. URL string
  477. TargetPort int
  478. PublishedPort int
  479. Protocol string
  480. }
  481. // ContainerSummary hold high-level description of a container
  482. type ContainerSummary struct {
  483. ID string
  484. Name string
  485. Names []string
  486. Image string
  487. Command string
  488. Project string
  489. Service string
  490. Created int64
  491. State string
  492. Status string
  493. Health string
  494. ExitCode int
  495. Publishers PortPublishers
  496. Labels map[string]string
  497. SizeRw int64 `json:",omitempty"`
  498. SizeRootFs int64 `json:",omitempty"`
  499. Mounts []string
  500. Networks []string
  501. LocalVolumes int
  502. }
  503. // PortPublishers is a slice of PortPublisher
  504. type PortPublishers []PortPublisher
  505. // Len implements sort.Interface
  506. func (p PortPublishers) Len() int {
  507. return len(p)
  508. }
  509. // Less implements sort.Interface
  510. func (p PortPublishers) Less(i, j int) bool {
  511. left := p[i]
  512. right := p[j]
  513. if left.URL != right.URL {
  514. return left.URL < right.URL
  515. }
  516. if left.TargetPort != right.TargetPort {
  517. return left.TargetPort < right.TargetPort
  518. }
  519. if left.PublishedPort != right.PublishedPort {
  520. return left.PublishedPort < right.PublishedPort
  521. }
  522. return left.Protocol < right.Protocol
  523. }
  524. // Swap implements sort.Interface
  525. func (p PortPublishers) Swap(i, j int) {
  526. p[i], p[j] = p[j], p[i]
  527. }
  528. // ContainerProcSummary holds container processes top data
  529. type ContainerProcSummary struct {
  530. ID string
  531. Name string
  532. Processes [][]string
  533. Titles []string
  534. Service string
  535. Replica string
  536. }
  537. // ImageSummary holds container image description
  538. type ImageSummary struct {
  539. ID string
  540. Repository string
  541. Tag string
  542. Platform platforms.Platform
  543. Size int64
  544. Created time.Time
  545. LastTagTime time.Time
  546. }
  547. // ServiceStatus hold status about a service
  548. type ServiceStatus struct {
  549. ID string
  550. Name string
  551. Replicas int
  552. Desired int
  553. Ports []string
  554. Publishers []PortPublisher
  555. }
  556. // LogOptions defines optional parameters for the `Log` API
  557. type LogOptions struct {
  558. Project *types.Project
  559. Index int
  560. Services []string
  561. Tail string
  562. Since string
  563. Until string
  564. Follow bool
  565. Timestamps bool
  566. }
  567. // PauseOptions group options of the Pause API
  568. type PauseOptions struct {
  569. // Services passed in the command line to be started
  570. Services []string
  571. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  572. Project *types.Project
  573. }
  574. // ExportOptions group options of the Export API
  575. type ExportOptions struct {
  576. Service string
  577. Index int
  578. Output string
  579. }
  580. // CommitOptions group options of the Commit API
  581. type CommitOptions struct {
  582. Service string
  583. Reference string
  584. Pause bool
  585. Comment string
  586. Author string
  587. Changes opts.ListOpts
  588. Index int
  589. }
  590. type GenerateOptions struct {
  591. // ProjectName to set in the Compose file
  592. ProjectName string
  593. // Containers passed in the command line to be used as reference for service definition
  594. Containers []string
  595. }
  596. const (
  597. // STARTING indicates that stack is being deployed
  598. STARTING string = "Starting"
  599. // RUNNING indicates that stack is deployed and services are running
  600. RUNNING string = "Running"
  601. // UPDATING indicates that some stack resources are being recreated
  602. UPDATING string = "Updating"
  603. // REMOVING indicates that stack is being deleted
  604. REMOVING string = "Removing"
  605. // UNKNOWN indicates unknown stack state
  606. UNKNOWN string = "Unknown"
  607. // FAILED indicates that stack deployment failed
  608. FAILED string = "Failed"
  609. )
  610. const (
  611. // RecreateDiverged to recreate services which configuration diverges from compose model
  612. RecreateDiverged = "diverged"
  613. // RecreateForce to force service container being recreated
  614. RecreateForce = "force"
  615. // RecreateNever to never recreate existing service containers
  616. RecreateNever = "never"
  617. )
  618. // Stack holds the name and state of a compose application/stack
  619. type Stack struct {
  620. ID string
  621. Name string
  622. Status string
  623. ConfigFiles string
  624. Reason string
  625. }
  626. // LogConsumer is a callback to process log messages from services
  627. type LogConsumer interface {
  628. Log(containerName, message string)
  629. Err(containerName, message string)
  630. Status(container, msg string)
  631. }
  632. // ContainerEventListener is a callback to process ContainerEvent from services
  633. type ContainerEventListener func(event ContainerEvent)
  634. // ContainerEvent notify an event has been collected on source container implementing Service
  635. type ContainerEvent struct {
  636. Type int
  637. Time int64
  638. Container *ContainerSummary
  639. // Source is the name of the container _without the project prefix_.
  640. //
  641. // This is only suitable for display purposes within Compose, as it's
  642. // not guaranteed to be unique across services.
  643. Source string
  644. ID string
  645. Service string
  646. Line string
  647. // ExitCode is only set on ContainerEventExited events
  648. ExitCode int
  649. Restarting bool
  650. }
  651. const (
  652. // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set
  653. ContainerEventLog = iota
  654. // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set
  655. ContainerEventErr
  656. // ContainerEventStarted let consumer know a container has been started
  657. ContainerEventStarted
  658. // ContainerEventRestarted let consumer know a container has been restarted
  659. ContainerEventRestarted
  660. // ContainerEventStopped is a ContainerEvent of type stopped.
  661. ContainerEventStopped
  662. // ContainerEventCreated let consumer know a new container has been created
  663. ContainerEventCreated
  664. // ContainerEventRecreated let consumer know container stopped but his being replaced
  665. ContainerEventRecreated
  666. // ContainerEventExited is a ContainerEvent of type exit. ExitCode is set
  667. ContainerEventExited
  668. // UserCancel user cancelled compose up, we are stopping containers
  669. HookEventLog
  670. )
  671. // Separator is used for naming components
  672. var Separator = "-"
  673. // GetImageNameOrDefault computes the default image name for a service, used to tag built images
  674. func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string {
  675. imageName := service.Image
  676. if imageName == "" {
  677. imageName = projectName + Separator + service.Name
  678. }
  679. return imageName
  680. }