1
0

api.go 16 KB

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