deploy.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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. serviceSpec := swarm.ServiceSpec{
  491. Annotations: swarm.Annotations{
  492. Name: name,
  493. Labels: getStackLabels(namespace.name, service.Deploy.Labels),
  494. },
  495. TaskTemplate: swarm.TaskSpec{
  496. ContainerSpec: swarm.ContainerSpec{
  497. Image: service.Image,
  498. Command: service.Entrypoint,
  499. Args: service.Command,
  500. Hostname: service.Hostname,
  501. Hosts: convertExtraHosts(service.ExtraHosts),
  502. Healthcheck: healthcheck,
  503. Env: convertEnvironment(service.Environment),
  504. Labels: getStackLabels(namespace.name, service.Labels),
  505. Dir: service.WorkingDir,
  506. User: service.User,
  507. Mounts: mounts,
  508. StopGracePeriod: service.StopGracePeriod,
  509. TTY: service.Tty,
  510. OpenStdin: service.StdinOpen,
  511. },
  512. Resources: resources,
  513. RestartPolicy: restartPolicy,
  514. Placement: &swarm.Placement{
  515. Constraints: service.Deploy.Placement.Constraints,
  516. },
  517. },
  518. EndpointSpec: endpoint,
  519. Mode: mode,
  520. Networks: networks,
  521. UpdateConfig: convertUpdateConfig(service.Deploy.UpdateConfig),
  522. }
  523. return serviceSpec, nil
  524. }
  525. func convertExtraHosts(extraHosts map[string]string) []string {
  526. hosts := []string{}
  527. for host, ip := range extraHosts {
  528. hosts = append(hosts, fmt.Sprintf("%s %s", ip, host))
  529. }
  530. return hosts
  531. }
  532. func convertHealthcheck(healthcheck *composetypes.HealthCheckConfig) (*container.HealthConfig, error) {
  533. if healthcheck == nil {
  534. return nil, nil
  535. }
  536. var (
  537. err error
  538. timeout, interval time.Duration
  539. retries int
  540. )
  541. if healthcheck.Disable {
  542. if len(healthcheck.Test) != 0 {
  543. return nil, fmt.Errorf("command and disable key can't be set at the same time")
  544. }
  545. return &container.HealthConfig{
  546. Test: []string{"NONE"},
  547. }, nil
  548. }
  549. if healthcheck.Timeout != "" {
  550. timeout, err = time.ParseDuration(healthcheck.Timeout)
  551. if err != nil {
  552. return nil, err
  553. }
  554. }
  555. if healthcheck.Interval != "" {
  556. interval, err = time.ParseDuration(healthcheck.Interval)
  557. if err != nil {
  558. return nil, err
  559. }
  560. }
  561. if healthcheck.Retries != nil {
  562. retries = int(*healthcheck.Retries)
  563. }
  564. return &container.HealthConfig{
  565. Test: healthcheck.Test,
  566. Timeout: timeout,
  567. Interval: interval,
  568. Retries: retries,
  569. }, nil
  570. }
  571. func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*swarm.RestartPolicy, error) {
  572. // TODO: log if restart is being ignored
  573. if source == nil {
  574. policy, err := runconfigopts.ParseRestartPolicy(restart)
  575. if err != nil {
  576. return nil, err
  577. }
  578. // TODO: is this an accurate convertion?
  579. switch {
  580. case policy.IsNone():
  581. return nil, nil
  582. case policy.IsAlways(), policy.IsUnlessStopped():
  583. return &swarm.RestartPolicy{
  584. Condition: swarm.RestartPolicyConditionAny,
  585. }, nil
  586. case policy.IsOnFailure():
  587. attempts := uint64(policy.MaximumRetryCount)
  588. return &swarm.RestartPolicy{
  589. Condition: swarm.RestartPolicyConditionOnFailure,
  590. MaxAttempts: &attempts,
  591. }, nil
  592. }
  593. }
  594. return &swarm.RestartPolicy{
  595. Condition: swarm.RestartPolicyCondition(source.Condition),
  596. Delay: source.Delay,
  597. MaxAttempts: source.MaxAttempts,
  598. Window: source.Window,
  599. }, nil
  600. }
  601. func convertUpdateConfig(source *composetypes.UpdateConfig) *swarm.UpdateConfig {
  602. if source == nil {
  603. return nil
  604. }
  605. parallel := uint64(1)
  606. if source.Parallelism != nil {
  607. parallel = *source.Parallelism
  608. }
  609. return &swarm.UpdateConfig{
  610. Parallelism: parallel,
  611. Delay: source.Delay,
  612. FailureAction: source.FailureAction,
  613. Monitor: source.Monitor,
  614. MaxFailureRatio: source.MaxFailureRatio,
  615. }
  616. }
  617. func convertResources(source composetypes.Resources) (*swarm.ResourceRequirements, error) {
  618. resources := &swarm.ResourceRequirements{}
  619. if source.Limits != nil {
  620. cpus, err := opts.ParseCPUs(source.Limits.NanoCPUs)
  621. if err != nil {
  622. return nil, err
  623. }
  624. resources.Limits = &swarm.Resources{
  625. NanoCPUs: cpus,
  626. MemoryBytes: int64(source.Limits.MemoryBytes),
  627. }
  628. }
  629. if source.Reservations != nil {
  630. cpus, err := opts.ParseCPUs(source.Reservations.NanoCPUs)
  631. if err != nil {
  632. return nil, err
  633. }
  634. resources.Reservations = &swarm.Resources{
  635. NanoCPUs: cpus,
  636. MemoryBytes: int64(source.Reservations.MemoryBytes),
  637. }
  638. }
  639. return resources, nil
  640. }
  641. func convertEndpointSpec(source []string) (*swarm.EndpointSpec, error) {
  642. portConfigs := []swarm.PortConfig{}
  643. ports, portBindings, err := nat.ParsePortSpecs(source)
  644. if err != nil {
  645. return nil, err
  646. }
  647. for port := range ports {
  648. portConfigs = append(
  649. portConfigs,
  650. servicecmd.ConvertPortToPortConfig(port, portBindings)...)
  651. }
  652. return &swarm.EndpointSpec{Ports: portConfigs}, nil
  653. }
  654. func convertEnvironment(source map[string]string) []string {
  655. var output []string
  656. for name, value := range source {
  657. output = append(output, fmt.Sprintf("%s=%s", name, value))
  658. }
  659. return output
  660. }
  661. func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error) {
  662. serviceMode := swarm.ServiceMode{}
  663. switch mode {
  664. case "global":
  665. if replicas != nil {
  666. return serviceMode, fmt.Errorf("replicas can only be used with replicated mode")
  667. }
  668. serviceMode.Global = &swarm.GlobalService{}
  669. case "replicated", "":
  670. serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
  671. default:
  672. return serviceMode, fmt.Errorf("Unknown mode: %s", mode)
  673. }
  674. return serviceMode, nil
  675. }