api.go 24 KB

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