adapter.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package container
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "runtime"
  10. "strings"
  11. "syscall"
  12. "time"
  13. "github.com/docker/distribution/reference"
  14. "github.com/docker/docker/api/types"
  15. "github.com/docker/docker/api/types/backend"
  16. containertypes "github.com/docker/docker/api/types/container"
  17. "github.com/docker/docker/api/types/events"
  18. containerpkg "github.com/docker/docker/container"
  19. "github.com/docker/docker/daemon/cluster/convert"
  20. executorpkg "github.com/docker/docker/daemon/cluster/executor"
  21. "github.com/docker/libnetwork"
  22. "github.com/docker/swarmkit/agent/exec"
  23. "github.com/docker/swarmkit/api"
  24. "github.com/docker/swarmkit/log"
  25. gogotypes "github.com/gogo/protobuf/types"
  26. "github.com/opencontainers/go-digest"
  27. "github.com/sirupsen/logrus"
  28. "golang.org/x/net/context"
  29. "golang.org/x/time/rate"
  30. )
  31. // containerAdapter conducts remote operations for a container. All calls
  32. // are mostly naked calls to the client API, seeded with information from
  33. // containerConfig.
  34. type containerAdapter struct {
  35. backend executorpkg.Backend
  36. container *containerConfig
  37. dependencies exec.DependencyGetter
  38. }
  39. func newContainerAdapter(b executorpkg.Backend, task *api.Task, node *api.NodeDescription, dependencies exec.DependencyGetter) (*containerAdapter, error) {
  40. ctnr, err := newContainerConfig(task, node)
  41. if err != nil {
  42. return nil, err
  43. }
  44. return &containerAdapter{
  45. container: ctnr,
  46. backend: b,
  47. dependencies: dependencies,
  48. }, nil
  49. }
  50. func (c *containerAdapter) pullImage(ctx context.Context) error {
  51. spec := c.container.spec()
  52. // Skip pulling if the image is referenced by image ID.
  53. if _, err := digest.Parse(spec.Image); err == nil {
  54. return nil
  55. }
  56. // Skip pulling if the image is referenced by digest and already
  57. // exists locally.
  58. named, err := reference.ParseNormalizedNamed(spec.Image)
  59. if err == nil {
  60. if _, ok := named.(reference.Canonical); ok {
  61. _, err := c.backend.LookupImage(spec.Image)
  62. if err == nil {
  63. return nil
  64. }
  65. }
  66. }
  67. // if the image needs to be pulled, the auth config will be retrieved and updated
  68. var encodedAuthConfig string
  69. if spec.PullOptions != nil {
  70. encodedAuthConfig = spec.PullOptions.RegistryAuth
  71. }
  72. authConfig := &types.AuthConfig{}
  73. if encodedAuthConfig != "" {
  74. if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuthConfig))).Decode(authConfig); err != nil {
  75. logrus.Warnf("invalid authconfig: %v", err)
  76. }
  77. }
  78. pr, pw := io.Pipe()
  79. metaHeaders := map[string][]string{}
  80. go func() {
  81. // TODO @jhowardmsft LCOW Support: This will need revisiting as
  82. // the stack is built up to include LCOW support for swarm.
  83. platform := runtime.GOOS
  84. err := c.backend.PullImage(ctx, c.container.image(), "", platform, metaHeaders, authConfig, pw)
  85. pw.CloseWithError(err)
  86. }()
  87. dec := json.NewDecoder(pr)
  88. dec.UseNumber()
  89. m := map[string]interface{}{}
  90. spamLimiter := rate.NewLimiter(rate.Every(time.Second), 1)
  91. lastStatus := ""
  92. for {
  93. if err := dec.Decode(&m); err != nil {
  94. if err == io.EOF {
  95. break
  96. }
  97. return err
  98. }
  99. l := log.G(ctx)
  100. // limit pull progress logs unless the status changes
  101. if spamLimiter.Allow() || lastStatus != m["status"] {
  102. // if we have progress details, we have everything we need
  103. if progress, ok := m["progressDetail"].(map[string]interface{}); ok {
  104. // first, log the image and status
  105. l = l.WithFields(logrus.Fields{
  106. "image": c.container.image(),
  107. "status": m["status"],
  108. })
  109. // then, if we have progress, log the progress
  110. if progress["current"] != nil && progress["total"] != nil {
  111. l = l.WithFields(logrus.Fields{
  112. "current": progress["current"],
  113. "total": progress["total"],
  114. })
  115. }
  116. }
  117. l.Debug("pull in progress")
  118. }
  119. // sometimes, we get no useful information at all, and add no fields
  120. if status, ok := m["status"].(string); ok {
  121. lastStatus = status
  122. }
  123. }
  124. // if the final stream object contained an error, return it
  125. if errMsg, ok := m["error"]; ok {
  126. return fmt.Errorf("%v", errMsg)
  127. }
  128. return nil
  129. }
  130. func (c *containerAdapter) createNetworks(ctx context.Context) error {
  131. for name := range c.container.networksAttachments {
  132. ncr, err := c.container.networkCreateRequest(name)
  133. if err != nil {
  134. return err
  135. }
  136. if err := c.backend.CreateManagedNetwork(ncr); err != nil { // todo name missing
  137. if _, ok := err.(libnetwork.NetworkNameError); ok {
  138. continue
  139. }
  140. return err
  141. }
  142. }
  143. return nil
  144. }
  145. func (c *containerAdapter) removeNetworks(ctx context.Context) error {
  146. for name, v := range c.container.networksAttachments {
  147. if err := c.backend.DeleteManagedNetwork(v.Network.ID); err != nil {
  148. switch err.(type) {
  149. case *libnetwork.ActiveEndpointsError:
  150. continue
  151. case libnetwork.ErrNoSuchNetwork:
  152. continue
  153. default:
  154. log.G(ctx).Errorf("network %s remove failed: %v", name, err)
  155. return err
  156. }
  157. }
  158. }
  159. return nil
  160. }
  161. func (c *containerAdapter) networkAttach(ctx context.Context) error {
  162. config := c.container.createNetworkingConfig(c.backend)
  163. var (
  164. networkName string
  165. networkID string
  166. )
  167. if config != nil {
  168. for n, epConfig := range config.EndpointsConfig {
  169. networkName = n
  170. networkID = epConfig.NetworkID
  171. break
  172. }
  173. }
  174. return c.backend.UpdateAttachment(networkName, networkID, c.container.networkAttachmentContainerID(), config)
  175. }
  176. func (c *containerAdapter) waitForDetach(ctx context.Context) error {
  177. config := c.container.createNetworkingConfig(c.backend)
  178. var (
  179. networkName string
  180. networkID string
  181. )
  182. if config != nil {
  183. for n, epConfig := range config.EndpointsConfig {
  184. networkName = n
  185. networkID = epConfig.NetworkID
  186. break
  187. }
  188. }
  189. return c.backend.WaitForDetachment(ctx, networkName, networkID, c.container.taskID(), c.container.networkAttachmentContainerID())
  190. }
  191. func (c *containerAdapter) create(ctx context.Context) error {
  192. var cr containertypes.ContainerCreateCreatedBody
  193. var err error
  194. if cr, err = c.backend.CreateManagedContainer(types.ContainerCreateConfig{
  195. Name: c.container.name(),
  196. Config: c.container.config(),
  197. HostConfig: c.container.hostConfig(),
  198. // Use the first network in container create
  199. NetworkingConfig: c.container.createNetworkingConfig(c.backend),
  200. }); err != nil {
  201. return err
  202. }
  203. // Docker daemon currently doesn't support multiple networks in container create
  204. // Connect to all other networks
  205. nc := c.container.connectNetworkingConfig(c.backend)
  206. if nc != nil {
  207. for n, ep := range nc.EndpointsConfig {
  208. if err := c.backend.ConnectContainerToNetwork(cr.ID, n, ep); err != nil {
  209. return err
  210. }
  211. }
  212. }
  213. container := c.container.task.Spec.GetContainer()
  214. if container == nil {
  215. return errors.New("unable to get container from task spec")
  216. }
  217. if err := c.backend.SetContainerDependencyStore(cr.ID, c.dependencies); err != nil {
  218. return err
  219. }
  220. // configure secrets
  221. secretRefs := convert.SecretReferencesFromGRPC(container.Secrets)
  222. if err := c.backend.SetContainerSecretReferences(cr.ID, secretRefs); err != nil {
  223. return err
  224. }
  225. configRefs := convert.ConfigReferencesFromGRPC(container.Configs)
  226. if err := c.backend.SetContainerConfigReferences(cr.ID, configRefs); err != nil {
  227. return err
  228. }
  229. return c.backend.UpdateContainerServiceConfig(cr.ID, c.container.serviceConfig())
  230. }
  231. // checkMounts ensures that the provided mounts won't have any host-specific
  232. // problems at start up. For example, we disallow bind mounts without an
  233. // existing path, which slightly different from the container API.
  234. func (c *containerAdapter) checkMounts() error {
  235. spec := c.container.spec()
  236. for _, mount := range spec.Mounts {
  237. switch mount.Type {
  238. case api.MountTypeBind:
  239. if _, err := os.Stat(mount.Source); os.IsNotExist(err) {
  240. return fmt.Errorf("invalid bind mount source, source path not found: %s", mount.Source)
  241. }
  242. }
  243. }
  244. return nil
  245. }
  246. func (c *containerAdapter) start(ctx context.Context) error {
  247. if err := c.checkMounts(); err != nil {
  248. return err
  249. }
  250. return c.backend.ContainerStart(c.container.name(), nil, "", "")
  251. }
  252. func (c *containerAdapter) inspect(ctx context.Context) (types.ContainerJSON, error) {
  253. cs, err := c.backend.ContainerInspectCurrent(c.container.name(), false)
  254. if ctx.Err() != nil {
  255. return types.ContainerJSON{}, ctx.Err()
  256. }
  257. if err != nil {
  258. return types.ContainerJSON{}, err
  259. }
  260. return *cs, nil
  261. }
  262. // events issues a call to the events API and returns a channel with all
  263. // events. The stream of events can be shutdown by cancelling the context.
  264. func (c *containerAdapter) events(ctx context.Context) <-chan events.Message {
  265. log.G(ctx).Debugf("waiting on events")
  266. buffer, l := c.backend.SubscribeToEvents(time.Time{}, time.Time{}, c.container.eventFilter())
  267. eventsq := make(chan events.Message, len(buffer))
  268. for _, event := range buffer {
  269. eventsq <- event
  270. }
  271. go func() {
  272. defer c.backend.UnsubscribeFromEvents(l)
  273. for {
  274. select {
  275. case ev := <-l:
  276. jev, ok := ev.(events.Message)
  277. if !ok {
  278. log.G(ctx).Warnf("unexpected event message: %q", ev)
  279. continue
  280. }
  281. select {
  282. case eventsq <- jev:
  283. case <-ctx.Done():
  284. return
  285. }
  286. case <-ctx.Done():
  287. return
  288. }
  289. }
  290. }()
  291. return eventsq
  292. }
  293. func (c *containerAdapter) wait(ctx context.Context) (<-chan containerpkg.StateStatus, error) {
  294. return c.backend.ContainerWait(ctx, c.container.nameOrID(), containerpkg.WaitConditionNotRunning)
  295. }
  296. func (c *containerAdapter) shutdown(ctx context.Context) error {
  297. // Default stop grace period to nil (daemon will use the stopTimeout of the container)
  298. var stopgrace *int
  299. spec := c.container.spec()
  300. if spec.StopGracePeriod != nil {
  301. stopgraceValue := int(spec.StopGracePeriod.Seconds)
  302. stopgrace = &stopgraceValue
  303. }
  304. return c.backend.ContainerStop(c.container.name(), stopgrace)
  305. }
  306. func (c *containerAdapter) terminate(ctx context.Context) error {
  307. return c.backend.ContainerKill(c.container.name(), uint64(syscall.SIGKILL))
  308. }
  309. func (c *containerAdapter) remove(ctx context.Context) error {
  310. return c.backend.ContainerRm(c.container.name(), &types.ContainerRmConfig{
  311. RemoveVolume: true,
  312. ForceRemove: true,
  313. })
  314. }
  315. func (c *containerAdapter) createVolumes(ctx context.Context) error {
  316. // Create plugin volumes that are embedded inside a Mount
  317. for _, mount := range c.container.task.Spec.GetContainer().Mounts {
  318. if mount.Type != api.MountTypeVolume {
  319. continue
  320. }
  321. if mount.VolumeOptions == nil {
  322. continue
  323. }
  324. if mount.VolumeOptions.DriverConfig == nil {
  325. continue
  326. }
  327. req := c.container.volumeCreateRequest(&mount)
  328. // Check if this volume exists on the engine
  329. if _, err := c.backend.VolumeCreate(req.Name, req.Driver, req.DriverOpts, req.Labels); err != nil {
  330. // TODO(amitshukla): Today, volume create through the engine api does not return an error
  331. // when the named volume with the same parameters already exists.
  332. // It returns an error if the driver name is different - that is a valid error
  333. return err
  334. }
  335. }
  336. return nil
  337. }
  338. func (c *containerAdapter) activateServiceBinding() error {
  339. return c.backend.ActivateContainerServiceBinding(c.container.name())
  340. }
  341. func (c *containerAdapter) deactivateServiceBinding() error {
  342. return c.backend.DeactivateContainerServiceBinding(c.container.name())
  343. }
  344. func (c *containerAdapter) logs(ctx context.Context, options api.LogSubscriptionOptions) (<-chan *backend.LogMessage, error) {
  345. apiOptions := &types.ContainerLogsOptions{
  346. Follow: options.Follow,
  347. // Always say yes to Timestamps and Details. we make the decision
  348. // of whether to return these to the user or not way higher up the
  349. // stack.
  350. Timestamps: true,
  351. Details: true,
  352. }
  353. if options.Since != nil {
  354. since, err := gogotypes.TimestampFromProto(options.Since)
  355. if err != nil {
  356. return nil, err
  357. }
  358. // print since as this formatted string because the docker container
  359. // logs interface expects it like this.
  360. // see github.com/docker/docker/api/types/time.ParseTimestamps
  361. apiOptions.Since = fmt.Sprintf("%d.%09d", since.Unix(), int64(since.Nanosecond()))
  362. }
  363. if options.Tail < 0 {
  364. // See protobuf documentation for details of how this works.
  365. apiOptions.Tail = fmt.Sprint(-options.Tail - 1)
  366. } else if options.Tail > 0 {
  367. return nil, errors.New("tail relative to start of logs not supported via docker API")
  368. }
  369. if len(options.Streams) == 0 {
  370. // empty == all
  371. apiOptions.ShowStdout, apiOptions.ShowStderr = true, true
  372. } else {
  373. for _, stream := range options.Streams {
  374. switch stream {
  375. case api.LogStreamStdout:
  376. apiOptions.ShowStdout = true
  377. case api.LogStreamStderr:
  378. apiOptions.ShowStderr = true
  379. }
  380. }
  381. }
  382. msgs, _, err := c.backend.ContainerLogs(ctx, c.container.name(), apiOptions)
  383. if err != nil {
  384. return nil, err
  385. }
  386. return msgs, nil
  387. }
  388. // todo: typed/wrapped errors
  389. func isContainerCreateNameConflict(err error) bool {
  390. return strings.Contains(err.Error(), "Conflict. The name")
  391. }
  392. func isUnknownContainer(err error) bool {
  393. return strings.Contains(err.Error(), "No such container:")
  394. }
  395. func isStoppedContainer(err error) bool {
  396. return strings.Contains(err.Error(), "is already stopped")
  397. }