api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package api
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "time"
  19. "github.com/compose-spec/compose-go/types"
  20. )
  21. // Service manages a compose project
  22. type Service interface {
  23. // Build executes the equivalent to a `compose build`
  24. Build(ctx context.Context, project *types.Project, options BuildOptions) error
  25. // Push executes the equivalent to a `compose push`
  26. Push(ctx context.Context, project *types.Project, options PushOptions) error
  27. // Pull executes the equivalent of a `compose pull`
  28. Pull(ctx context.Context, project *types.Project, options PullOptions) error
  29. // Create executes the equivalent to a `compose create`
  30. Create(ctx context.Context, project *types.Project, options CreateOptions) error
  31. // Start executes the equivalent to a `compose start`
  32. Start(ctx context.Context, projectName string, options StartOptions) error
  33. // Restart restarts containers
  34. Restart(ctx context.Context, projectName string, options RestartOptions) error
  35. // Stop executes the equivalent to a `compose stop`
  36. Stop(ctx context.Context, projectName string, options StopOptions) error
  37. // Up executes the equivalent to a `compose up`
  38. Up(ctx context.Context, project *types.Project, options UpOptions) error
  39. // Down executes the equivalent to a `compose down`
  40. Down(ctx context.Context, projectName string, options DownOptions) error
  41. // Logs executes the equivalent to a `compose logs`
  42. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  43. // Ps executes the equivalent to a `compose ps`
  44. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  45. // List executes the equivalent to a `docker stack ls`
  46. List(ctx context.Context, options ListOptions) ([]Stack, error)
  47. // Convert translate compose model into backend's native format
  48. Convert(ctx context.Context, project *types.Project, options ConvertOptions) ([]byte, error)
  49. // Kill executes the equivalent to a `compose kill`
  50. Kill(ctx context.Context, projectName string, options KillOptions) error
  51. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  52. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  53. // Remove executes the equivalent to a `compose rm`
  54. Remove(ctx context.Context, projectName string, options RemoveOptions) error
  55. // Exec executes a command in a running service container
  56. Exec(ctx context.Context, projectName string, options RunOptions) (int, error)
  57. // Copy copies a file/folder between a service container and the local filesystem
  58. Copy(ctx context.Context, projectName string, options CopyOptions) error
  59. // Pause executes the equivalent to a `compose pause`
  60. Pause(ctx context.Context, projectName string, options PauseOptions) error
  61. // UnPause executes the equivalent to a `compose unpause`
  62. UnPause(ctx context.Context, projectName string, options PauseOptions) error
  63. // Top executes the equivalent to a `compose top`
  64. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  65. // Events executes the equivalent to a `compose events`
  66. Events(ctx context.Context, projectName string, options EventsOptions) error
  67. // Port executes the equivalent to a `compose port`
  68. Port(ctx context.Context, projectName string, service string, port uint16, options PortOptions) (string, int, error)
  69. // Images executes the equivalent of a `compose images`
  70. Images(ctx context.Context, projectName string, options ImagesOptions) ([]ImageSummary, error)
  71. // MaxConcurrency defines upper limit for concurrent operations against engine API
  72. MaxConcurrency(parallel int)
  73. // DryRunMode defines if dry run applies to the command
  74. DryRunMode(dryRun bool)
  75. // Watch services' development context and sync/notify/rebuild/restart on changes
  76. Watch(ctx context.Context, project *types.Project, services []string, options WatchOptions) error
  77. }
  78. // WatchOptions group options of the Watch API
  79. type WatchOptions struct {
  80. }
  81. // BuildOptions group options of the Build API
  82. type BuildOptions struct {
  83. // Pull always attempt to pull a newer version of the image
  84. Pull bool
  85. // Progress set type of progress output ("auto", "plain", "tty")
  86. Progress string
  87. // Args set build-time args
  88. Args types.MappingWithEquals
  89. // NoCache disables cache use
  90. NoCache bool
  91. // Quiet make the build process not output to the console
  92. Quiet bool
  93. // Services passed in the command line to be built
  94. Services []string
  95. // Ssh authentications passed in the command line
  96. SSHs []types.SSHKey
  97. }
  98. // CreateOptions group options of the Create API
  99. type CreateOptions struct {
  100. // Services defines the services user interacts with
  101. Services []string
  102. // Remove legacy containers for services that are not defined in the project
  103. RemoveOrphans bool
  104. // Ignore legacy containers for services that are not defined in the project
  105. IgnoreOrphans bool
  106. // Recreate define the strategy to apply on existing containers
  107. Recreate string
  108. // RecreateDependencies define the strategy to apply on dependencies services
  109. RecreateDependencies string
  110. // Inherit reuse anonymous volumes from previous container
  111. Inherit bool
  112. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  113. Timeout *time.Duration
  114. // QuietPull makes the pulling process quiet
  115. QuietPull bool
  116. }
  117. // StartOptions group options of the Start API
  118. type StartOptions struct {
  119. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  120. Project *types.Project
  121. // Attach to container and forward logs if not nil
  122. Attach LogConsumer
  123. // AttachTo set the services to attach to
  124. AttachTo []string
  125. // CascadeStop stops the application when a container stops
  126. CascadeStop bool
  127. // ExitCodeFrom return exit code from specified service
  128. ExitCodeFrom string
  129. // Wait won't return until containers reached the running|healthy state
  130. Wait bool
  131. // Services passed in the command line to be started
  132. Services []string
  133. }
  134. // RestartOptions group options of the Restart API
  135. type RestartOptions struct {
  136. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  137. Project *types.Project
  138. // Timeout override container restart timeout
  139. Timeout *time.Duration
  140. // Services passed in the command line to be restarted
  141. Services []string
  142. }
  143. // StopOptions group options of the Stop API
  144. type StopOptions struct {
  145. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  146. Project *types.Project
  147. // Timeout override container stop timeout
  148. Timeout *time.Duration
  149. // Services passed in the command line to be stopped
  150. Services []string
  151. }
  152. // UpOptions group options of the Up API
  153. type UpOptions struct {
  154. Create CreateOptions
  155. Start StartOptions
  156. }
  157. // DownOptions group options of the Down API
  158. type DownOptions struct {
  159. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  160. RemoveOrphans bool
  161. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  162. Project *types.Project
  163. // Timeout override container stop timeout
  164. Timeout *time.Duration
  165. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  166. Images string
  167. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  168. Volumes bool
  169. }
  170. // ConvertOptions group options of the Convert API
  171. type ConvertOptions struct {
  172. // Format define the output format used to dump converted application model (json|yaml)
  173. Format string
  174. // Output defines the path to save the application model
  175. Output string
  176. // Resolve image reference to digests
  177. ResolveImageDigests bool
  178. }
  179. // PushOptions group options of the Push API
  180. type PushOptions struct {
  181. Quiet bool
  182. IgnoreFailures bool
  183. }
  184. // PullOptions group options of the Pull API
  185. type PullOptions struct {
  186. Quiet bool
  187. IgnoreFailures bool
  188. IgnoreBuildable bool
  189. }
  190. // ImagesOptions group options of the Images API
  191. type ImagesOptions struct {
  192. Services []string
  193. }
  194. // KillOptions group options of the Kill API
  195. type KillOptions struct {
  196. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  197. RemoveOrphans bool
  198. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  199. Project *types.Project
  200. // Services passed in the command line to be killed
  201. Services []string
  202. // Signal to send to containers
  203. Signal string
  204. }
  205. // RemoveOptions group options of the Remove API
  206. type RemoveOptions struct {
  207. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  208. Project *types.Project
  209. // DryRun just list removable resources
  210. DryRun bool
  211. // Volumes remove anonymous volumes
  212. Volumes bool
  213. // Force don't ask to confirm removal
  214. Force bool
  215. // Services passed in the command line to be removed
  216. Services []string
  217. }
  218. // RunOptions group options of the Run API
  219. type RunOptions struct {
  220. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  221. Project *types.Project
  222. Name string
  223. Service string
  224. Command []string
  225. Entrypoint []string
  226. Detach bool
  227. AutoRemove bool
  228. Tty bool
  229. Interactive bool
  230. WorkingDir string
  231. User string
  232. Environment []string
  233. Labels types.Labels
  234. Privileged bool
  235. UseNetworkAliases bool
  236. NoDeps bool
  237. // QuietPull makes the pulling process quiet
  238. QuietPull bool
  239. // used by exec
  240. Index int
  241. }
  242. // EventsOptions group options of the Events API
  243. type EventsOptions struct {
  244. Services []string
  245. Consumer func(event Event) error
  246. }
  247. // Event is a container runtime event served by Events API
  248. type Event struct {
  249. Timestamp time.Time
  250. Service string
  251. Container string
  252. Status string
  253. Attributes map[string]string
  254. }
  255. // PortOptions group options of the Port API
  256. type PortOptions struct {
  257. Protocol string
  258. Index int
  259. }
  260. func (e Event) String() string {
  261. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  262. var attr []string
  263. for k, v := range e.Attributes {
  264. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  265. }
  266. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  267. }
  268. // ListOptions group options of the ls API
  269. type ListOptions struct {
  270. All bool
  271. }
  272. // PsOptions group options of the Ps API
  273. type PsOptions struct {
  274. Project *types.Project
  275. All bool
  276. Services []string
  277. }
  278. // CopyOptions group options of the cp API
  279. type CopyOptions struct {
  280. Source string
  281. Destination string
  282. All bool
  283. Index int
  284. FollowLink bool
  285. CopyUIDGID bool
  286. }
  287. // PortPublisher hold status about published port
  288. type PortPublisher struct {
  289. URL string
  290. TargetPort int
  291. PublishedPort int
  292. Protocol string
  293. }
  294. // ContainerSummary hold high-level description of a container
  295. type ContainerSummary struct {
  296. ID string
  297. Name string
  298. Image any
  299. Command string
  300. Project string
  301. Service string
  302. Created int64
  303. State string
  304. Status string
  305. Health string
  306. ExitCode int
  307. Publishers PortPublishers
  308. }
  309. // PortPublishers is a slice of PortPublisher
  310. type PortPublishers []PortPublisher
  311. // Len implements sort.Interface
  312. func (p PortPublishers) Len() int {
  313. return len(p)
  314. }
  315. // Less implements sort.Interface
  316. func (p PortPublishers) Less(i, j int) bool {
  317. left := p[i]
  318. right := p[j]
  319. if left.URL != right.URL {
  320. return left.URL < right.URL
  321. }
  322. if left.TargetPort != right.TargetPort {
  323. return left.TargetPort < right.TargetPort
  324. }
  325. if left.PublishedPort != right.PublishedPort {
  326. return left.PublishedPort < right.PublishedPort
  327. }
  328. return left.Protocol < right.Protocol
  329. }
  330. // Swap implements sort.Interface
  331. func (p PortPublishers) Swap(i, j int) {
  332. p[i], p[j] = p[j], p[i]
  333. }
  334. // ContainerProcSummary holds container processes top data
  335. type ContainerProcSummary struct {
  336. ID string
  337. Name string
  338. Processes [][]string
  339. Titles []string
  340. }
  341. // ImageSummary holds container image description
  342. type ImageSummary struct {
  343. ID string
  344. ContainerName string
  345. Repository string
  346. Tag string
  347. Size int64
  348. }
  349. // ServiceStatus hold status about a service
  350. type ServiceStatus struct {
  351. ID string
  352. Name string
  353. Replicas int
  354. Desired int
  355. Ports []string
  356. Publishers []PortPublisher
  357. }
  358. // LogOptions defines optional parameters for the `Log` API
  359. type LogOptions struct {
  360. Project *types.Project
  361. Services []string
  362. Tail string
  363. Since string
  364. Until string
  365. Follow bool
  366. Timestamps bool
  367. }
  368. // PauseOptions group options of the Pause API
  369. type PauseOptions struct {
  370. // Services passed in the command line to be started
  371. Services []string
  372. // Project is the compose project used to define this app. Might be nil if user ran command just with project name
  373. Project *types.Project
  374. }
  375. const (
  376. // STARTING indicates that stack is being deployed
  377. STARTING string = "Starting"
  378. // RUNNING indicates that stack is deployed and services are running
  379. RUNNING string = "Running"
  380. // UPDATING indicates that some stack resources are being recreated
  381. UPDATING string = "Updating"
  382. // REMOVING indicates that stack is being deleted
  383. REMOVING string = "Removing"
  384. // UNKNOWN indicates unknown stack state
  385. UNKNOWN string = "Unknown"
  386. // FAILED indicates that stack deployment failed
  387. FAILED string = "Failed"
  388. )
  389. const (
  390. // RecreateDiverged to recreate services which configuration diverges from compose model
  391. RecreateDiverged = "diverged"
  392. // RecreateForce to force service container being recreated
  393. RecreateForce = "force"
  394. // RecreateNever to never recreate existing service containers
  395. RecreateNever = "never"
  396. )
  397. // Stack holds the name and state of a compose application/stack
  398. type Stack struct {
  399. ID string
  400. Name string
  401. Status string
  402. ConfigFiles string
  403. Reason string
  404. }
  405. // LogConsumer is a callback to process log messages from services
  406. type LogConsumer interface {
  407. Log(containerName, message string)
  408. Err(containerName, message string)
  409. Status(container, msg string)
  410. Register(container string)
  411. }
  412. // ContainerEventListener is a callback to process ContainerEvent from services
  413. type ContainerEventListener func(event ContainerEvent)
  414. // ContainerEvent notify an event has been collected on source container implementing Service
  415. type ContainerEvent struct {
  416. Type int
  417. // Container is the name of the container _without the project prefix_.
  418. //
  419. // This is only suitable for display purposes within Compose, as it's
  420. // not guaranteed to be unique across services.
  421. Container string
  422. Service string
  423. Line string
  424. // ContainerEventExit only
  425. ExitCode int
  426. Restarting bool
  427. }
  428. const (
  429. // ContainerEventLog is a ContainerEvent of type log on stdout. Line is set
  430. ContainerEventLog = iota
  431. // ContainerEventErr is a ContainerEvent of type log on stderr. Line is set
  432. ContainerEventErr
  433. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  434. ContainerEventAttach
  435. // ContainerEventStopped is a ContainerEvent of type stopped.
  436. ContainerEventStopped
  437. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  438. ContainerEventExit
  439. // UserCancel user cancelled compose up, we are stopping containers
  440. UserCancel
  441. )
  442. // Separator is used for naming components
  443. var Separator = "-"
  444. // GetImageNameOrDefault computes the default image name for a service, used to tag built images
  445. func GetImageNameOrDefault(service types.ServiceConfig, projectName string) string {
  446. imageName := service.Image
  447. if imageName == "" {
  448. imageName = projectName + Separator + service.Name
  449. }
  450. return imageName
  451. }