adapter.go 13 KB

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