deploy.go 17 KB

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