deploy.go 20 KB

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