api.go 16 KB

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