api.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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 compose
  14. import (
  15. "context"
  16. "fmt"
  17. "io"
  18. "strings"
  19. "time"
  20. "github.com/compose-spec/compose-go/types"
  21. )
  22. // Service manages a compose project
  23. type Service interface {
  24. // Build executes the equivalent to a `compose build`
  25. Build(ctx context.Context, project *types.Project, options BuildOptions) error
  26. // Push executes the equivalent ot a `compose push`
  27. Push(ctx context.Context, project *types.Project, options PushOptions) error
  28. // Pull executes the equivalent of a `compose pull`
  29. Pull(ctx context.Context, project *types.Project, opts PullOptions) error
  30. // Create executes the equivalent to a `compose create`
  31. Create(ctx context.Context, project *types.Project, opts CreateOptions) error
  32. // Start executes the equivalent to a `compose start`
  33. Start(ctx context.Context, project *types.Project, options StartOptions) error
  34. // Restart restarts containers
  35. Restart(ctx context.Context, project *types.Project, options RestartOptions) error
  36. // Stop executes the equivalent to a `compose stop`
  37. Stop(ctx context.Context, project *types.Project, options StopOptions) error
  38. // Up executes the equivalent to a `compose up`
  39. Up(ctx context.Context, project *types.Project, options UpOptions) error
  40. // Down executes the equivalent to a `compose down`
  41. Down(ctx context.Context, projectName string, options DownOptions) error
  42. // Logs executes the equivalent to a `compose logs`
  43. Logs(ctx context.Context, projectName string, consumer LogConsumer, options LogOptions) error
  44. // Ps executes the equivalent to a `compose ps`
  45. Ps(ctx context.Context, projectName string, options PsOptions) ([]ContainerSummary, error)
  46. // List executes the equivalent to a `docker stack ls`
  47. List(ctx context.Context, options ListOptions) ([]Stack, error)
  48. // Convert translate compose model into backend's native format
  49. Convert(ctx context.Context, project *types.Project, options ConvertOptions) ([]byte, error)
  50. // Kill executes the equivalent to a `compose kill`
  51. Kill(ctx context.Context, project *types.Project, options KillOptions) error
  52. // RunOneOffContainer creates a service oneoff container and starts its dependencies
  53. RunOneOffContainer(ctx context.Context, project *types.Project, opts RunOptions) (int, error)
  54. // Remove executes the equivalent to a `compose rm`
  55. Remove(ctx context.Context, project *types.Project, options RemoveOptions) ([]string, error)
  56. // Exec executes a command in a running service container
  57. Exec(ctx context.Context, project *types.Project, opts RunOptions) error
  58. // Pause executes the equivalent to a `compose pause`
  59. Pause(ctx context.Context, project *types.Project) error
  60. // UnPause executes the equivalent to a `compose unpause`
  61. UnPause(ctx context.Context, project *types.Project) error
  62. // Top executes the equivalent to a `compose top`
  63. Top(ctx context.Context, projectName string, services []string) ([]ContainerProcSummary, error)
  64. // Events executes the equivalent to a `compose events`
  65. Events(ctx context.Context, project string, options EventsOptions) error
  66. // Port executes the equivalent to a `compose port`
  67. Port(ctx context.Context, project string, service string, port int, options PortOptions) (string, int, error)
  68. }
  69. // BuildOptions group options of the Build API
  70. type BuildOptions struct {
  71. // Pull always attempt to pull a newer version of the image
  72. Pull bool
  73. // Progress set type of progress output ("auto", "plain", "tty")
  74. Progress string
  75. // Args set build-time args
  76. Args types.Mapping
  77. }
  78. // CreateOptions group options of the Create API
  79. type CreateOptions struct {
  80. // Services defines the services user interacts with
  81. Services []string
  82. // Remove legacy containers for services that are not defined in the project
  83. RemoveOrphans bool
  84. // Recreate define the strategy to apply on existing containers
  85. Recreate string
  86. // RecreateDependencies define the strategy to apply on dependencies services
  87. RecreateDependencies string
  88. // Inherit reuse anonymous volumes from previous container
  89. Inherit bool
  90. // Timeout set delay to wait for container to gracelfuly stop before sending SIGKILL
  91. Timeout *time.Duration
  92. // QuietPull makes the pulling process quiet
  93. QuietPull bool
  94. }
  95. // StartOptions group options of the Start API
  96. type StartOptions struct {
  97. // Attach will attach to service containers and send container logs and events
  98. Attach ContainerEventListener
  99. // Services passed in the command line to be started
  100. Services []string
  101. }
  102. // RestartOptions group options of the Restart API
  103. type RestartOptions struct {
  104. // Timeout override container restart timeout
  105. Timeout *time.Duration
  106. }
  107. // StopOptions group options of the Stop API
  108. type StopOptions struct {
  109. // Timeout override container stop timeout
  110. Timeout *time.Duration
  111. }
  112. // UpOptions group options of the Up API
  113. type UpOptions struct {
  114. // Detach will create services and return immediately
  115. Detach bool
  116. // QuietPull makes the pulling process quiet
  117. QuietPull bool
  118. }
  119. // DownOptions group options of the Down API
  120. type DownOptions struct {
  121. // RemoveOrphans will cleanup containers that are not declared on the compose model but own the same labels
  122. RemoveOrphans bool
  123. // Project is the compose project used to define this app. Might be nil if user ran `down` just with project name
  124. Project *types.Project
  125. // Timeout override container stop timeout
  126. Timeout *time.Duration
  127. // Images remove image used by services. 'all': Remove all images. 'local': Remove only images that don't have a tag
  128. Images string
  129. // Volumes remove volumes, both declared in the `volumes` section and anonymous ones
  130. Volumes bool
  131. }
  132. // ConvertOptions group options of the Convert API
  133. type ConvertOptions struct {
  134. // Format define the output format used to dump converted application model (json|yaml)
  135. Format string
  136. // Output defines the path to save the application model
  137. Output string
  138. }
  139. // PushOptions group options of the Push API
  140. type PushOptions struct {
  141. IgnoreFailures bool
  142. }
  143. // PullOptions group options of the Push API
  144. type PullOptions struct {
  145. IgnoreFailures bool
  146. }
  147. // KillOptions group options of the Kill API
  148. type KillOptions struct {
  149. // Signal to send to containers
  150. Signal string
  151. }
  152. // RemoveOptions group options of the Remove API
  153. type RemoveOptions struct {
  154. // DryRun just list removable resources
  155. DryRun bool
  156. // Volumes remove anonymous volumes
  157. Volumes bool
  158. // Force don't ask to confirm removal
  159. Force bool
  160. }
  161. // RunOptions group options of the Run API
  162. type RunOptions struct {
  163. Name string
  164. Service string
  165. Command []string
  166. Entrypoint []string
  167. Detach bool
  168. AutoRemove bool
  169. Writer io.WriteCloser
  170. Reader io.ReadCloser
  171. Tty bool
  172. WorkingDir string
  173. User string
  174. Environment []string
  175. Labels types.Labels
  176. Privileged bool
  177. UseNetworkAliases bool
  178. // used by exec
  179. Index int
  180. }
  181. // EventsOptions group options of the Events API
  182. type EventsOptions struct {
  183. Services []string
  184. Consumer func(event Event) error
  185. }
  186. // Event is a container runtime event served by Events API
  187. type Event struct {
  188. Timestamp time.Time
  189. Service string
  190. Container string
  191. Status string
  192. Attributes map[string]string
  193. }
  194. // PortOptions group options of the Port API
  195. type PortOptions struct {
  196. Protocol string
  197. Index int
  198. }
  199. func (e Event) String() string {
  200. t := e.Timestamp.Format("2006-01-02 15:04:05.000000")
  201. var attr []string
  202. for k, v := range e.Attributes {
  203. attr = append(attr, fmt.Sprintf("%s=%s", k, v))
  204. }
  205. return fmt.Sprintf("%s container %s %s (%s)\n", t, e.Status, e.Container, strings.Join(attr, ", "))
  206. }
  207. // EnvironmentMap return RunOptions.Environment as a MappingWithEquals
  208. func (opts *RunOptions) EnvironmentMap() types.MappingWithEquals {
  209. environment := types.MappingWithEquals{}
  210. for _, s := range opts.Environment {
  211. parts := strings.SplitN(s, "=", 2)
  212. key := parts[0]
  213. switch {
  214. case len(parts) == 1:
  215. environment[key] = nil
  216. default:
  217. environment[key] = &parts[1]
  218. }
  219. }
  220. return environment
  221. }
  222. // ListOptions group options of the ls API
  223. type ListOptions struct {
  224. All bool
  225. }
  226. // PsOptions group options of the Ps API
  227. type PsOptions struct {
  228. All bool
  229. }
  230. // PortPublisher hold status about published port
  231. type PortPublisher struct {
  232. URL string
  233. TargetPort int
  234. PublishedPort int
  235. Protocol string
  236. }
  237. // ContainerSummary hold high-level description of a container
  238. type ContainerSummary struct {
  239. ID string
  240. Name string
  241. Project string
  242. Service string
  243. State string
  244. Health string
  245. Publishers []PortPublisher
  246. }
  247. // ContainerProcSummary holds container processes top data
  248. type ContainerProcSummary struct {
  249. ID string
  250. Name string
  251. Processes [][]string
  252. Titles []string
  253. }
  254. // ServiceStatus hold status about a service
  255. type ServiceStatus struct {
  256. ID string
  257. Name string
  258. Replicas int
  259. Desired int
  260. Ports []string
  261. Publishers []PortPublisher
  262. }
  263. // LogOptions defines optional parameters for the `Log` API
  264. type LogOptions struct {
  265. Services []string
  266. Tail string
  267. Follow bool
  268. Timestamps bool
  269. }
  270. const (
  271. // STARTING indicates that stack is being deployed
  272. STARTING string = "Starting"
  273. // RUNNING indicates that stack is deployed and services are running
  274. RUNNING string = "Running"
  275. // UPDATING indicates that some stack resources are being recreated
  276. UPDATING string = "Updating"
  277. // REMOVING indicates that stack is being deleted
  278. REMOVING string = "Removing"
  279. // UNKNOWN indicates unknown stack state
  280. UNKNOWN string = "Unknown"
  281. // FAILED indicates that stack deployment failed
  282. FAILED string = "Failed"
  283. )
  284. const (
  285. // RecreateDiverged to recreate services which configuration diverges from compose model
  286. RecreateDiverged = "diverged"
  287. // RecreateForce to force service container being recreated
  288. RecreateForce = "force"
  289. // RecreateNever to never recreate existing service containers
  290. RecreateNever = "never"
  291. )
  292. // Stack holds the name and state of a compose application/stack
  293. type Stack struct {
  294. ID string
  295. Name string
  296. Status string
  297. Reason string
  298. }
  299. // LogConsumer is a callback to process log messages from services
  300. type LogConsumer interface {
  301. Log(service, container, message string)
  302. Status(container, msg string)
  303. Register(container string)
  304. }
  305. // ContainerEventListener is a callback to process ContainerEvent from services
  306. type ContainerEventListener func(event ContainerEvent)
  307. // ContainerEvent notify an event has been collected on source container implementing Service
  308. type ContainerEvent struct {
  309. Type int
  310. Container string
  311. Service string
  312. Line string
  313. ExitCode int
  314. }
  315. const (
  316. // ContainerEventLog is a ContainerEvent of type log. Line is set
  317. ContainerEventLog = iota
  318. // ContainerEventAttach is a ContainerEvent of type attach. First event sent about a container
  319. ContainerEventAttach
  320. // ContainerEventExit is a ContainerEvent of type exit. ExitCode is set
  321. ContainerEventExit
  322. // UserCancel user cancelled compose up, we are stopping containers
  323. UserCancel
  324. )