deploy.go 20 KB

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