deploy.go 20 KB

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