api.go 15 KB

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