deploy.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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. var aliases []string
  218. if network != nil {
  219. aliases = network.Aliases
  220. }
  221. nets = append(nets, swarm.NetworkAttachmentConfig{
  222. Target: namespace.scope(networkName),
  223. Aliases: append(aliases, name),
  224. })
  225. }
  226. return nets
  227. }
  228. func convertVolumes(
  229. serviceVolumes []string,
  230. stackVolumes map[string]composetypes.VolumeConfig,
  231. namespace namespace,
  232. ) ([]mount.Mount, error) {
  233. var mounts []mount.Mount
  234. for _, volumeSpec := range serviceVolumes {
  235. mount, err := convertVolumeToMount(volumeSpec, stackVolumes, namespace)
  236. if err != nil {
  237. return nil, err
  238. }
  239. mounts = append(mounts, mount)
  240. }
  241. return mounts, nil
  242. }
  243. func convertVolumeToMount(
  244. volumeSpec string,
  245. stackVolumes map[string]composetypes.VolumeConfig,
  246. namespace namespace,
  247. ) (mount.Mount, error) {
  248. var source, target string
  249. var mode []string
  250. // TODO: split Windows path mappings properly
  251. parts := strings.SplitN(volumeSpec, ":", 3)
  252. switch len(parts) {
  253. case 3:
  254. source = parts[0]
  255. target = parts[1]
  256. mode = strings.Split(parts[2], ",")
  257. case 2:
  258. source = parts[0]
  259. target = parts[1]
  260. case 1:
  261. target = parts[0]
  262. default:
  263. return mount.Mount{}, fmt.Errorf("invald volume: %s", volumeSpec)
  264. }
  265. // TODO: catch Windows paths here
  266. if strings.HasPrefix(source, "/") {
  267. return mount.Mount{
  268. Type: mount.TypeBind,
  269. Source: source,
  270. Target: target,
  271. ReadOnly: isReadOnly(mode),
  272. BindOptions: getBindOptions(mode),
  273. }, nil
  274. }
  275. stackVolume, exists := stackVolumes[source]
  276. if !exists {
  277. return mount.Mount{}, fmt.Errorf("undefined volume: %s", source)
  278. }
  279. var volumeOptions *mount.VolumeOptions
  280. if stackVolume.External.Name != "" {
  281. source = stackVolume.External.Name
  282. } else {
  283. volumeOptions = &mount.VolumeOptions{
  284. Labels: stackVolume.Labels,
  285. NoCopy: isNoCopy(mode),
  286. }
  287. if stackVolume.Driver != "" {
  288. volumeOptions.DriverConfig = &mount.Driver{
  289. Name: stackVolume.Driver,
  290. Options: stackVolume.DriverOpts,
  291. }
  292. }
  293. source = namespace.scope(source)
  294. }
  295. return mount.Mount{
  296. Type: mount.TypeVolume,
  297. Source: source,
  298. Target: target,
  299. ReadOnly: isReadOnly(mode),
  300. VolumeOptions: volumeOptions,
  301. }, nil
  302. }
  303. func modeHas(mode []string, field string) bool {
  304. for _, item := range mode {
  305. if item == field {
  306. return true
  307. }
  308. }
  309. return false
  310. }
  311. func isReadOnly(mode []string) bool {
  312. return modeHas(mode, "ro")
  313. }
  314. func isNoCopy(mode []string) bool {
  315. return modeHas(mode, "nocopy")
  316. }
  317. func getBindOptions(mode []string) *mount.BindOptions {
  318. for _, item := range mode {
  319. if strings.Contains(item, "private") || strings.Contains(item, "shared") || strings.Contains(item, "slave") {
  320. return &mount.BindOptions{Propagation: mount.Propagation(item)}
  321. }
  322. }
  323. return nil
  324. }
  325. func deployServices(
  326. ctx context.Context,
  327. dockerCli *command.DockerCli,
  328. services map[string]swarm.ServiceSpec,
  329. namespace namespace,
  330. sendAuth bool,
  331. ) error {
  332. apiClient := dockerCli.Client()
  333. out := dockerCli.Out()
  334. existingServices, err := getServices(ctx, apiClient, namespace.name)
  335. if err != nil {
  336. return err
  337. }
  338. existingServiceMap := make(map[string]swarm.Service)
  339. for _, service := range existingServices {
  340. existingServiceMap[service.Spec.Name] = service
  341. }
  342. for internalName, serviceSpec := range services {
  343. name := namespace.scope(internalName)
  344. encodedAuth := ""
  345. if sendAuth {
  346. // Retrieve encoded auth token from the image reference
  347. image := serviceSpec.TaskTemplate.ContainerSpec.Image
  348. encodedAuth, err = command.RetrieveAuthTokenFromImage(ctx, dockerCli, image)
  349. if err != nil {
  350. return err
  351. }
  352. }
  353. if service, exists := existingServiceMap[name]; exists {
  354. fmt.Fprintf(out, "Updating service %s (id: %s)\n", name, service.ID)
  355. updateOpts := types.ServiceUpdateOptions{}
  356. if sendAuth {
  357. updateOpts.EncodedRegistryAuth = encodedAuth
  358. }
  359. response, err := apiClient.ServiceUpdate(
  360. ctx,
  361. service.ID,
  362. service.Version,
  363. serviceSpec,
  364. updateOpts,
  365. )
  366. if err != nil {
  367. return err
  368. }
  369. for _, warning := range response.Warnings {
  370. fmt.Fprintln(dockerCli.Err(), warning)
  371. }
  372. } else {
  373. fmt.Fprintf(out, "Creating service %s\n", name)
  374. createOpts := types.ServiceCreateOptions{}
  375. if sendAuth {
  376. createOpts.EncodedRegistryAuth = encodedAuth
  377. }
  378. if _, err := apiClient.ServiceCreate(ctx, serviceSpec, createOpts); err != nil {
  379. return err
  380. }
  381. }
  382. }
  383. return nil
  384. }
  385. func convertServices(
  386. namespace namespace,
  387. config *composetypes.Config,
  388. ) (map[string]swarm.ServiceSpec, error) {
  389. result := make(map[string]swarm.ServiceSpec)
  390. services := config.Services
  391. volumes := config.Volumes
  392. for _, service := range services {
  393. serviceSpec, err := convertService(namespace, service, volumes)
  394. if err != nil {
  395. return nil, err
  396. }
  397. result[service.Name] = serviceSpec
  398. }
  399. return result, nil
  400. }
  401. func convertService(
  402. namespace namespace,
  403. service composetypes.ServiceConfig,
  404. volumes map[string]composetypes.VolumeConfig,
  405. ) (swarm.ServiceSpec, error) {
  406. name := namespace.scope(service.Name)
  407. endpoint, err := convertEndpointSpec(service.Ports)
  408. if err != nil {
  409. return swarm.ServiceSpec{}, err
  410. }
  411. mode, err := convertDeployMode(service.Deploy.Mode, service.Deploy.Replicas)
  412. if err != nil {
  413. return swarm.ServiceSpec{}, err
  414. }
  415. mounts, err := convertVolumes(service.Volumes, volumes, namespace)
  416. if err != nil {
  417. // TODO: better error message (include service name)
  418. return swarm.ServiceSpec{}, err
  419. }
  420. resources, err := convertResources(service.Deploy.Resources)
  421. if err != nil {
  422. return swarm.ServiceSpec{}, err
  423. }
  424. restartPolicy, err := convertRestartPolicy(
  425. service.Restart, service.Deploy.RestartPolicy)
  426. if err != nil {
  427. return swarm.ServiceSpec{}, err
  428. }
  429. healthcheck, err := convertHealthcheck(service.HealthCheck)
  430. if err != nil {
  431. return swarm.ServiceSpec{}, err
  432. }
  433. serviceSpec := swarm.ServiceSpec{
  434. Annotations: swarm.Annotations{
  435. Name: name,
  436. Labels: getStackLabels(namespace.name, service.Deploy.Labels),
  437. },
  438. TaskTemplate: swarm.TaskSpec{
  439. ContainerSpec: swarm.ContainerSpec{
  440. Image: service.Image,
  441. Command: service.Entrypoint,
  442. Args: service.Command,
  443. Hostname: service.Hostname,
  444. Hosts: convertExtraHosts(service.ExtraHosts),
  445. Healthcheck: healthcheck,
  446. Env: convertEnvironment(service.Environment),
  447. Labels: getStackLabels(namespace.name, service.Labels),
  448. Dir: service.WorkingDir,
  449. User: service.User,
  450. Mounts: mounts,
  451. StopGracePeriod: service.StopGracePeriod,
  452. TTY: service.Tty,
  453. OpenStdin: service.StdinOpen,
  454. },
  455. Resources: resources,
  456. RestartPolicy: restartPolicy,
  457. Placement: &swarm.Placement{
  458. Constraints: service.Deploy.Placement.Constraints,
  459. },
  460. },
  461. EndpointSpec: endpoint,
  462. Mode: mode,
  463. Networks: convertServiceNetworks(service.Networks, namespace, service.Name),
  464. UpdateConfig: convertUpdateConfig(service.Deploy.UpdateConfig),
  465. }
  466. return serviceSpec, nil
  467. }
  468. func convertExtraHosts(extraHosts map[string]string) []string {
  469. hosts := []string{}
  470. for host, ip := range extraHosts {
  471. hosts = append(hosts, fmt.Sprintf("%s %s", ip, host))
  472. }
  473. return hosts
  474. }
  475. func convertHealthcheck(healthcheck *composetypes.HealthCheckConfig) (*container.HealthConfig, error) {
  476. if healthcheck == nil {
  477. return nil, nil
  478. }
  479. var (
  480. err error
  481. timeout, interval time.Duration
  482. retries int
  483. )
  484. if healthcheck.Disable {
  485. if len(healthcheck.Test) != 0 {
  486. return nil, fmt.Errorf("command and disable key can't be set at the same time")
  487. }
  488. return &container.HealthConfig{
  489. Test: []string{"NONE"},
  490. }, nil
  491. }
  492. if healthcheck.Timeout != "" {
  493. timeout, err = time.ParseDuration(healthcheck.Timeout)
  494. if err != nil {
  495. return nil, err
  496. }
  497. }
  498. if healthcheck.Interval != "" {
  499. interval, err = time.ParseDuration(healthcheck.Interval)
  500. if err != nil {
  501. return nil, err
  502. }
  503. }
  504. if healthcheck.Retries != nil {
  505. retries = int(*healthcheck.Retries)
  506. }
  507. return &container.HealthConfig{
  508. Test: healthcheck.Test,
  509. Timeout: timeout,
  510. Interval: interval,
  511. Retries: retries,
  512. }, nil
  513. }
  514. func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*swarm.RestartPolicy, error) {
  515. // TODO: log if restart is being ignored
  516. if source == nil {
  517. policy, err := runconfigopts.ParseRestartPolicy(restart)
  518. if err != nil {
  519. return nil, err
  520. }
  521. // TODO: is this an accurate convertion?
  522. switch {
  523. case policy.IsNone():
  524. return nil, nil
  525. case policy.IsAlways(), policy.IsUnlessStopped():
  526. return &swarm.RestartPolicy{
  527. Condition: swarm.RestartPolicyConditionAny,
  528. }, nil
  529. case policy.IsOnFailure():
  530. attempts := uint64(policy.MaximumRetryCount)
  531. return &swarm.RestartPolicy{
  532. Condition: swarm.RestartPolicyConditionOnFailure,
  533. MaxAttempts: &attempts,
  534. }, nil
  535. }
  536. }
  537. return &swarm.RestartPolicy{
  538. Condition: swarm.RestartPolicyCondition(source.Condition),
  539. Delay: source.Delay,
  540. MaxAttempts: source.MaxAttempts,
  541. Window: source.Window,
  542. }, nil
  543. }
  544. func convertUpdateConfig(source *composetypes.UpdateConfig) *swarm.UpdateConfig {
  545. if source == nil {
  546. return nil
  547. }
  548. parallel := uint64(1)
  549. if source.Parallelism != nil {
  550. parallel = *source.Parallelism
  551. }
  552. return &swarm.UpdateConfig{
  553. Parallelism: parallel,
  554. Delay: source.Delay,
  555. FailureAction: source.FailureAction,
  556. Monitor: source.Monitor,
  557. MaxFailureRatio: source.MaxFailureRatio,
  558. }
  559. }
  560. func convertResources(source composetypes.Resources) (*swarm.ResourceRequirements, error) {
  561. resources := &swarm.ResourceRequirements{}
  562. if source.Limits != nil {
  563. cpus, err := opts.ParseCPUs(source.Limits.NanoCPUs)
  564. if err != nil {
  565. return nil, err
  566. }
  567. resources.Limits = &swarm.Resources{
  568. NanoCPUs: cpus,
  569. MemoryBytes: int64(source.Limits.MemoryBytes),
  570. }
  571. }
  572. if source.Reservations != nil {
  573. cpus, err := opts.ParseCPUs(source.Reservations.NanoCPUs)
  574. if err != nil {
  575. return nil, err
  576. }
  577. resources.Reservations = &swarm.Resources{
  578. NanoCPUs: cpus,
  579. MemoryBytes: int64(source.Reservations.MemoryBytes),
  580. }
  581. }
  582. return resources, nil
  583. }
  584. func convertEndpointSpec(source []string) (*swarm.EndpointSpec, error) {
  585. portConfigs := []swarm.PortConfig{}
  586. ports, portBindings, err := nat.ParsePortSpecs(source)
  587. if err != nil {
  588. return nil, err
  589. }
  590. for port := range ports {
  591. portConfigs = append(
  592. portConfigs,
  593. servicecmd.ConvertPortToPortConfig(port, portBindings)...)
  594. }
  595. return &swarm.EndpointSpec{Ports: portConfigs}, nil
  596. }
  597. func convertEnvironment(source map[string]string) []string {
  598. var output []string
  599. for name, value := range source {
  600. output = append(output, fmt.Sprintf("%s=%s", name, value))
  601. }
  602. return output
  603. }
  604. func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error) {
  605. serviceMode := swarm.ServiceMode{}
  606. switch mode {
  607. case "global":
  608. if replicas != nil {
  609. return serviceMode, fmt.Errorf("replicas can only be used with replicated mode")
  610. }
  611. serviceMode.Global = &swarm.GlobalService{}
  612. case "replicated", "":
  613. serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
  614. default:
  615. return serviceMode, fmt.Errorf("Unknown mode: %s", mode)
  616. }
  617. return serviceMode, nil
  618. }