api.go 25 KB

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