api.go 24 KB

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