deploy.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. package stack
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "sort"
  7. "strings"
  8. "time"
  9. "github.com/spf13/cobra"
  10. "golang.org/x/net/context"
  11. "github.com/aanand/compose-file/loader"
  12. composetypes "github.com/aanand/compose-file/types"
  13. "github.com/docker/docker/api/types"
  14. "github.com/docker/docker/api/types/container"
  15. "github.com/docker/docker/api/types/mount"
  16. networktypes "github.com/docker/docker/api/types/network"
  17. "github.com/docker/docker/api/types/swarm"
  18. "github.com/docker/docker/cli"
  19. "github.com/docker/docker/cli/command"
  20. servicecmd "github.com/docker/docker/cli/command/service"
  21. "github.com/docker/docker/opts"
  22. runconfigopts "github.com/docker/docker/runconfig/opts"
  23. "github.com/docker/go-connections/nat"
  24. )
  25. const (
  26. defaultNetworkDriver = "overlay"
  27. )
  28. type deployOptions struct {
  29. bundlefile string
  30. composefile string
  31. namespace string
  32. sendRegistryAuth bool
  33. }
  34. func newDeployCommand(dockerCli *command.DockerCli) *cobra.Command {
  35. var opts deployOptions
  36. cmd := &cobra.Command{
  37. Use: "deploy [OPTIONS] STACK",
  38. Aliases: []string{"up"},
  39. Short: "Deploy a new stack or update an existing stack",
  40. Args: cli.ExactArgs(1),
  41. RunE: func(cmd *cobra.Command, args []string) error {
  42. opts.namespace = args[0]
  43. return runDeploy(dockerCli, opts)
  44. },
  45. Tags: map[string]string{"experimental": "", "version": "1.25"},
  46. }
  47. flags := cmd.Flags()
  48. addBundlefileFlag(&opts.bundlefile, flags)
  49. addComposefileFlag(&opts.composefile, flags)
  50. addRegistryAuthFlag(&opts.sendRegistryAuth, flags)
  51. return cmd
  52. }
  53. func runDeploy(dockerCli *command.DockerCli, opts deployOptions) error {
  54. switch {
  55. case opts.bundlefile == "" && opts.composefile == "":
  56. return fmt.Errorf("Please specify either a bundle file (with --bundle-file) or a Compose file (with --compose-file).")
  57. case opts.bundlefile != "" && opts.composefile != "":
  58. return fmt.Errorf("You cannot specify both a bundle file and a Compose file.")
  59. case opts.bundlefile != "":
  60. return deployBundle(dockerCli, opts)
  61. default:
  62. return deployCompose(dockerCli, opts)
  63. }
  64. }
  65. func deployCompose(dockerCli *command.DockerCli, opts deployOptions) error {
  66. configDetails, err := getConfigDetails(opts)
  67. if err != nil {
  68. return err
  69. }
  70. config, err := loader.Load(configDetails)
  71. if err != nil {
  72. if fpe, ok := err.(*loader.ForbiddenPropertiesError); ok {
  73. return fmt.Errorf("Compose file contains unsupported options:\n\n%s\n",
  74. propertyWarnings(fpe.Properties))
  75. }
  76. return err
  77. }
  78. unsupportedProperties := loader.GetUnsupportedProperties(configDetails)
  79. if len(unsupportedProperties) > 0 {
  80. fmt.Fprintf(dockerCli.Err(), "Ignoring unsupported options: %s\n\n",
  81. strings.Join(unsupportedProperties, ", "))
  82. }
  83. deprecatedProperties := loader.GetDeprecatedProperties(configDetails)
  84. if len(deprecatedProperties) > 0 {
  85. fmt.Fprintf(dockerCli.Err(), "Ignoring deprecated options:\n\n%s\n\n",
  86. propertyWarnings(deprecatedProperties))
  87. }
  88. ctx := context.Background()
  89. namespace := namespace{name: opts.namespace}
  90. networks := convertNetworks(namespace, config.Networks)
  91. if err := createNetworks(ctx, dockerCli, namespace, networks); err != nil {
  92. return err
  93. }
  94. services, err := convertServices(namespace, config)
  95. if err != nil {
  96. return err
  97. }
  98. return deployServices(ctx, dockerCli, services, namespace, opts.sendRegistryAuth)
  99. }
  100. func propertyWarnings(properties map[string]string) string {
  101. var msgs []string
  102. for name, description := range properties {
  103. msgs = append(msgs, fmt.Sprintf("%s: %s", name, description))
  104. }
  105. sort.Strings(msgs)
  106. return strings.Join(msgs, "\n\n")
  107. }
  108. func getConfigDetails(opts deployOptions) (composetypes.ConfigDetails, error) {
  109. var details composetypes.ConfigDetails
  110. var err error
  111. details.WorkingDir, err = os.Getwd()
  112. if err != nil {
  113. return details, err
  114. }
  115. configFile, err := getConfigFile(opts.composefile)
  116. if err != nil {
  117. return details, err
  118. }
  119. // TODO: support multiple files
  120. details.ConfigFiles = []composetypes.ConfigFile{*configFile}
  121. return details, nil
  122. }
  123. func getConfigFile(filename string) (*composetypes.ConfigFile, error) {
  124. bytes, err := ioutil.ReadFile(filename)
  125. if err != nil {
  126. return nil, err
  127. }
  128. config, err := loader.ParseYAML(bytes)
  129. if err != nil {
  130. return nil, err
  131. }
  132. return &composetypes.ConfigFile{
  133. Filename: filename,
  134. Config: config,
  135. }, nil
  136. }
  137. func convertNetworks(
  138. namespace namespace,
  139. networks map[string]composetypes.NetworkConfig,
  140. ) map[string]types.NetworkCreate {
  141. if networks == nil {
  142. networks = make(map[string]composetypes.NetworkConfig)
  143. }
  144. // TODO: only add default network if it's used
  145. networks["default"] = composetypes.NetworkConfig{}
  146. result := make(map[string]types.NetworkCreate)
  147. for internalName, network := range networks {
  148. if network.External.Name != "" {
  149. continue
  150. }
  151. createOpts := types.NetworkCreate{
  152. Labels: getStackLabels(namespace.name, network.Labels),
  153. Driver: network.Driver,
  154. Options: network.DriverOpts,
  155. }
  156. if network.Ipam.Driver != "" || len(network.Ipam.Config) > 0 {
  157. createOpts.IPAM = &networktypes.IPAM{}
  158. }
  159. if network.Ipam.Driver != "" {
  160. createOpts.IPAM.Driver = network.Ipam.Driver
  161. }
  162. for _, ipamConfig := range network.Ipam.Config {
  163. config := networktypes.IPAMConfig{
  164. Subnet: ipamConfig.Subnet,
  165. }
  166. createOpts.IPAM.Config = append(createOpts.IPAM.Config, config)
  167. }
  168. result[internalName] = createOpts
  169. }
  170. return result
  171. }
  172. func createNetworks(
  173. ctx context.Context,
  174. dockerCli *command.DockerCli,
  175. namespace namespace,
  176. networks map[string]types.NetworkCreate,
  177. ) error {
  178. client := dockerCli.Client()
  179. existingNetworks, err := getNetworks(ctx, client, namespace.name)
  180. if err != nil {
  181. return err
  182. }
  183. existingNetworkMap := make(map[string]types.NetworkResource)
  184. for _, network := range existingNetworks {
  185. existingNetworkMap[network.Name] = network
  186. }
  187. for internalName, createOpts := range networks {
  188. name := namespace.scope(internalName)
  189. if _, exists := existingNetworkMap[name]; exists {
  190. continue
  191. }
  192. if createOpts.Driver == "" {
  193. createOpts.Driver = defaultNetworkDriver
  194. }
  195. fmt.Fprintf(dockerCli.Out(), "Creating network %s\n", name)
  196. if _, err := client.NetworkCreate(ctx, name, createOpts); err != nil {
  197. return err
  198. }
  199. }
  200. return nil
  201. }
  202. func convertServiceNetworks(
  203. networks map[string]*composetypes.ServiceNetworkConfig,
  204. namespace namespace,
  205. name string,
  206. ) []swarm.NetworkAttachmentConfig {
  207. if len(networks) == 0 {
  208. return []swarm.NetworkAttachmentConfig{
  209. {
  210. Target: namespace.scope("default"),
  211. Aliases: []string{name},
  212. },
  213. }
  214. }
  215. nets := []swarm.NetworkAttachmentConfig{}
  216. for networkName, network := range networks {
  217. nets = append(nets, swarm.NetworkAttachmentConfig{
  218. Target: namespace.scope(networkName),
  219. Aliases: append(network.Aliases, name),
  220. })
  221. }
  222. return nets
  223. }
  224. func convertVolumes(
  225. serviceVolumes []string,
  226. stackVolumes map[string]composetypes.VolumeConfig,
  227. namespace namespace,
  228. ) ([]mount.Mount, error) {
  229. var mounts []mount.Mount
  230. for _, volumeSpec := range serviceVolumes {
  231. mount, err := convertVolumeToMount(volumeSpec, stackVolumes, namespace)
  232. if err != nil {
  233. return nil, err
  234. }
  235. mounts = append(mounts, mount)
  236. }
  237. return mounts, nil
  238. }
  239. func convertVolumeToMount(
  240. volumeSpec string,
  241. stackVolumes map[string]composetypes.VolumeConfig,
  242. namespace namespace,
  243. ) (mount.Mount, error) {
  244. var source, target string
  245. var mode []string
  246. // TODO: split Windows path mappings properly
  247. parts := strings.SplitN(volumeSpec, ":", 3)
  248. switch len(parts) {
  249. case 3:
  250. source = parts[0]
  251. target = parts[1]
  252. mode = strings.Split(parts[2], ",")
  253. case 2:
  254. source = parts[0]
  255. target = parts[1]
  256. case 1:
  257. target = parts[0]
  258. default:
  259. return mount.Mount{}, fmt.Errorf("invald volume: %s", volumeSpec)
  260. }
  261. // TODO: catch Windows paths here
  262. if strings.HasPrefix(source, "/") {
  263. return mount.Mount{
  264. Type: mount.TypeBind,
  265. Source: source,
  266. Target: target,
  267. ReadOnly: isReadOnly(mode),
  268. BindOptions: getBindOptions(mode),
  269. }, nil
  270. }
  271. stackVolume, exists := stackVolumes[source]
  272. if !exists {
  273. return mount.Mount{}, fmt.Errorf("undefined volume: %s", source)
  274. }
  275. var volumeOptions *mount.VolumeOptions
  276. if stackVolume.External.Name != "" {
  277. source = stackVolume.External.Name
  278. } else {
  279. volumeOptions = &mount.VolumeOptions{
  280. Labels: stackVolume.Labels,
  281. NoCopy: isNoCopy(mode),
  282. }
  283. if stackVolume.Driver != "" {
  284. volumeOptions.DriverConfig = &mount.Driver{
  285. Name: stackVolume.Driver,
  286. Options: stackVolume.DriverOpts,
  287. }
  288. }
  289. source = namespace.scope(source)
  290. }
  291. return mount.Mount{
  292. Type: mount.TypeVolume,
  293. Source: source,
  294. Target: target,
  295. ReadOnly: isReadOnly(mode),
  296. VolumeOptions: volumeOptions,
  297. }, nil
  298. }
  299. func modeHas(mode []string, field string) bool {
  300. for _, item := range mode {
  301. if item == field {
  302. return true
  303. }
  304. }
  305. return false
  306. }
  307. func isReadOnly(mode []string) bool {
  308. return modeHas(mode, "ro")
  309. }
  310. func isNoCopy(mode []string) bool {
  311. return modeHas(mode, "nocopy")
  312. }
  313. func getBindOptions(mode []string) *mount.BindOptions {
  314. for _, item := range mode {
  315. if strings.Contains(item, "private") || strings.Contains(item, "shared") || strings.Contains(item, "slave") {
  316. return &mount.BindOptions{Propagation: mount.Propagation(item)}
  317. }
  318. }
  319. return nil
  320. }
  321. func deployServices(
  322. ctx context.Context,
  323. dockerCli *command.DockerCli,
  324. services map[string]swarm.ServiceSpec,
  325. namespace namespace,
  326. sendAuth bool,
  327. ) error {
  328. apiClient := dockerCli.Client()
  329. out := dockerCli.Out()
  330. existingServices, err := getServices(ctx, apiClient, namespace.name)
  331. if err != nil {
  332. return err
  333. }
  334. existingServiceMap := make(map[string]swarm.Service)
  335. for _, service := range existingServices {
  336. existingServiceMap[service.Spec.Name] = service
  337. }
  338. for internalName, serviceSpec := range services {
  339. name := namespace.scope(internalName)
  340. encodedAuth := ""
  341. if sendAuth {
  342. // Retrieve encoded auth token from the image reference
  343. image := serviceSpec.TaskTemplate.ContainerSpec.Image
  344. encodedAuth, err = command.RetrieveAuthTokenFromImage(ctx, dockerCli, image)
  345. if err != nil {
  346. return err
  347. }
  348. }
  349. if service, exists := existingServiceMap[name]; exists {
  350. fmt.Fprintf(out, "Updating service %s (id: %s)\n", name, service.ID)
  351. updateOpts := types.ServiceUpdateOptions{}
  352. if sendAuth {
  353. updateOpts.EncodedRegistryAuth = encodedAuth
  354. }
  355. if err := apiClient.ServiceUpdate(
  356. ctx,
  357. service.ID,
  358. service.Version,
  359. serviceSpec,
  360. updateOpts,
  361. ); err != nil {
  362. return err
  363. }
  364. } else {
  365. fmt.Fprintf(out, "Creating service %s\n", name)
  366. createOpts := types.ServiceCreateOptions{}
  367. if sendAuth {
  368. createOpts.EncodedRegistryAuth = encodedAuth
  369. }
  370. if _, err := apiClient.ServiceCreate(ctx, serviceSpec, createOpts); err != nil {
  371. return err
  372. }
  373. }
  374. }
  375. return nil
  376. }
  377. func convertServices(
  378. namespace namespace,
  379. config *composetypes.Config,
  380. ) (map[string]swarm.ServiceSpec, error) {
  381. result := make(map[string]swarm.ServiceSpec)
  382. services := config.Services
  383. volumes := config.Volumes
  384. for _, service := range services {
  385. serviceSpec, err := convertService(namespace, service, volumes)
  386. if err != nil {
  387. return nil, err
  388. }
  389. result[service.Name] = serviceSpec
  390. }
  391. return result, nil
  392. }
  393. func convertService(
  394. namespace namespace,
  395. service composetypes.ServiceConfig,
  396. volumes map[string]composetypes.VolumeConfig,
  397. ) (swarm.ServiceSpec, error) {
  398. name := namespace.scope(service.Name)
  399. endpoint, err := convertEndpointSpec(service.Ports)
  400. if err != nil {
  401. return swarm.ServiceSpec{}, err
  402. }
  403. mode, err := convertDeployMode(service.Deploy.Mode, service.Deploy.Replicas)
  404. if err != nil {
  405. return swarm.ServiceSpec{}, err
  406. }
  407. mounts, err := convertVolumes(service.Volumes, volumes, namespace)
  408. if err != nil {
  409. // TODO: better error message (include service name)
  410. return swarm.ServiceSpec{}, err
  411. }
  412. resources, err := convertResources(service.Deploy.Resources)
  413. if err != nil {
  414. return swarm.ServiceSpec{}, err
  415. }
  416. restartPolicy, err := convertRestartPolicy(
  417. service.Restart, service.Deploy.RestartPolicy)
  418. if err != nil {
  419. return swarm.ServiceSpec{}, err
  420. }
  421. healthcheck, err := convertHealthcheck(service.HealthCheck)
  422. if err != nil {
  423. return swarm.ServiceSpec{}, err
  424. }
  425. serviceSpec := swarm.ServiceSpec{
  426. Annotations: swarm.Annotations{
  427. Name: name,
  428. Labels: getStackLabels(namespace.name, service.Deploy.Labels),
  429. },
  430. TaskTemplate: swarm.TaskSpec{
  431. ContainerSpec: swarm.ContainerSpec{
  432. Image: service.Image,
  433. Command: service.Entrypoint,
  434. Args: service.Command,
  435. Hostname: service.Hostname,
  436. Hosts: convertExtraHosts(service.ExtraHosts),
  437. Healthcheck: healthcheck,
  438. Env: convertEnvironment(service.Environment),
  439. Labels: getStackLabels(namespace.name, service.Labels),
  440. Dir: service.WorkingDir,
  441. User: service.User,
  442. Mounts: mounts,
  443. StopGracePeriod: service.StopGracePeriod,
  444. TTY: service.Tty,
  445. OpenStdin: service.StdinOpen,
  446. },
  447. Resources: resources,
  448. RestartPolicy: restartPolicy,
  449. Placement: &swarm.Placement{
  450. Constraints: service.Deploy.Placement.Constraints,
  451. },
  452. },
  453. EndpointSpec: endpoint,
  454. Mode: mode,
  455. Networks: convertServiceNetworks(service.Networks, namespace, service.Name),
  456. UpdateConfig: convertUpdateConfig(service.Deploy.UpdateConfig),
  457. }
  458. return serviceSpec, nil
  459. }
  460. func convertExtraHosts(extraHosts map[string]string) []string {
  461. hosts := []string{}
  462. for host, ip := range extraHosts {
  463. hosts = append(hosts, fmt.Sprintf("%s %s", host, ip))
  464. }
  465. return hosts
  466. }
  467. func convertHealthcheck(healthcheck *composetypes.HealthCheckConfig) (*container.HealthConfig, error) {
  468. if healthcheck == nil {
  469. return nil, nil
  470. }
  471. var (
  472. err error
  473. timeout, interval time.Duration
  474. retries int
  475. )
  476. if healthcheck.Disable {
  477. if len(healthcheck.Test) != 0 {
  478. return nil, fmt.Errorf("command and disable key can't be set at the same time")
  479. }
  480. return &container.HealthConfig{
  481. Test: []string{"NONE"},
  482. }, nil
  483. }
  484. if healthcheck.Timeout != "" {
  485. timeout, err = time.ParseDuration(healthcheck.Timeout)
  486. if err != nil {
  487. return nil, err
  488. }
  489. }
  490. if healthcheck.Interval != "" {
  491. interval, err = time.ParseDuration(healthcheck.Interval)
  492. if err != nil {
  493. return nil, err
  494. }
  495. }
  496. if healthcheck.Retries != nil {
  497. retries = int(*healthcheck.Retries)
  498. }
  499. return &container.HealthConfig{
  500. Test: healthcheck.Test,
  501. Timeout: timeout,
  502. Interval: interval,
  503. Retries: retries,
  504. }, nil
  505. }
  506. func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*swarm.RestartPolicy, error) {
  507. // TODO: log if restart is being ignored
  508. if source == nil {
  509. policy, err := runconfigopts.ParseRestartPolicy(restart)
  510. if err != nil {
  511. return nil, err
  512. }
  513. // TODO: is this an accurate convertion?
  514. switch {
  515. case policy.IsNone():
  516. return nil, nil
  517. case policy.IsAlways(), policy.IsUnlessStopped():
  518. return &swarm.RestartPolicy{
  519. Condition: swarm.RestartPolicyConditionAny,
  520. }, nil
  521. case policy.IsOnFailure():
  522. attempts := uint64(policy.MaximumRetryCount)
  523. return &swarm.RestartPolicy{
  524. Condition: swarm.RestartPolicyConditionOnFailure,
  525. MaxAttempts: &attempts,
  526. }, nil
  527. }
  528. }
  529. return &swarm.RestartPolicy{
  530. Condition: swarm.RestartPolicyCondition(source.Condition),
  531. Delay: source.Delay,
  532. MaxAttempts: source.MaxAttempts,
  533. Window: source.Window,
  534. }, nil
  535. }
  536. func convertUpdateConfig(source *composetypes.UpdateConfig) *swarm.UpdateConfig {
  537. if source == nil {
  538. return nil
  539. }
  540. return &swarm.UpdateConfig{
  541. Parallelism: source.Parallelism,
  542. Delay: source.Delay,
  543. FailureAction: source.FailureAction,
  544. Monitor: source.Monitor,
  545. MaxFailureRatio: source.MaxFailureRatio,
  546. }
  547. }
  548. func convertResources(source composetypes.Resources) (*swarm.ResourceRequirements, error) {
  549. resources := &swarm.ResourceRequirements{}
  550. if source.Limits != nil {
  551. cpus, err := opts.ParseCPUs(source.Limits.NanoCPUs)
  552. if err != nil {
  553. return nil, err
  554. }
  555. resources.Limits = &swarm.Resources{
  556. NanoCPUs: cpus,
  557. MemoryBytes: int64(source.Limits.MemoryBytes),
  558. }
  559. }
  560. if source.Reservations != nil {
  561. cpus, err := opts.ParseCPUs(source.Reservations.NanoCPUs)
  562. if err != nil {
  563. return nil, err
  564. }
  565. resources.Reservations = &swarm.Resources{
  566. NanoCPUs: cpus,
  567. MemoryBytes: int64(source.Reservations.MemoryBytes),
  568. }
  569. }
  570. return resources, nil
  571. }
  572. func convertEndpointSpec(source []string) (*swarm.EndpointSpec, error) {
  573. portConfigs := []swarm.PortConfig{}
  574. ports, portBindings, err := nat.ParsePortSpecs(source)
  575. if err != nil {
  576. return nil, err
  577. }
  578. for port := range ports {
  579. portConfigs = append(
  580. portConfigs,
  581. servicecmd.ConvertPortToPortConfig(port, portBindings)...)
  582. }
  583. return &swarm.EndpointSpec{Ports: portConfigs}, nil
  584. }
  585. func convertEnvironment(source map[string]string) []string {
  586. var output []string
  587. for name, value := range source {
  588. output = append(output, fmt.Sprintf("%s=%s", name, value))
  589. }
  590. return output
  591. }
  592. func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error) {
  593. serviceMode := swarm.ServiceMode{}
  594. switch mode {
  595. case "global":
  596. if replicas != nil {
  597. return serviceMode, fmt.Errorf("replicas can only be used with replicated mode")
  598. }
  599. serviceMode.Global = &swarm.GlobalService{}
  600. case "replicated", "":
  601. serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
  602. default:
  603. return serviceMode, fmt.Errorf("Unknown mode: %s", mode)
  604. }
  605. return serviceMode, nil
  606. }