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