executor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. package container // import "github.com/docker/docker/daemon/cluster/executor/container"
  2. import (
  3. "context"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "sync"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/api/types/filters"
  10. "github.com/docker/docker/api/types/network"
  11. swarmtypes "github.com/docker/docker/api/types/swarm"
  12. "github.com/docker/docker/daemon/cluster/controllers/plugin"
  13. "github.com/docker/docker/daemon/cluster/convert"
  14. executorpkg "github.com/docker/docker/daemon/cluster/executor"
  15. clustertypes "github.com/docker/docker/daemon/cluster/provider"
  16. "github.com/docker/docker/libnetwork"
  17. networktypes "github.com/docker/docker/libnetwork/types"
  18. "github.com/docker/swarmkit/agent"
  19. "github.com/docker/swarmkit/agent/exec"
  20. "github.com/docker/swarmkit/api"
  21. "github.com/docker/swarmkit/api/naming"
  22. "github.com/docker/swarmkit/log"
  23. "github.com/docker/swarmkit/template"
  24. "github.com/pkg/errors"
  25. "github.com/sirupsen/logrus"
  26. )
  27. type executor struct {
  28. backend executorpkg.Backend
  29. imageBackend executorpkg.ImageBackend
  30. pluginBackend plugin.Backend
  31. volumeBackend executorpkg.VolumeBackend
  32. dependencies exec.DependencyManager
  33. mutex sync.Mutex // This mutex protects the following node field
  34. node *api.NodeDescription
  35. // nodeObj holds a copy of the swarmkit Node object from the time of the
  36. // last call to executor.Configure. This allows us to discover which
  37. // network attachments the node previously had, which further allows us to
  38. // determine which, if any, need to be removed. nodeObj is not protected by
  39. // a mutex, because it is only written to in the method (Configure) that it
  40. // is read from. If that changes, it may need to be guarded.
  41. nodeObj *api.Node
  42. }
  43. // NewExecutor returns an executor from the docker client.
  44. func NewExecutor(b executorpkg.Backend, p plugin.Backend, i executorpkg.ImageBackend, v executorpkg.VolumeBackend) exec.Executor {
  45. return &executor{
  46. backend: b,
  47. pluginBackend: p,
  48. imageBackend: i,
  49. volumeBackend: v,
  50. dependencies: agent.NewDependencyManager(),
  51. }
  52. }
  53. // Describe returns the underlying node description from the docker client.
  54. func (e *executor) Describe(ctx context.Context) (*api.NodeDescription, error) {
  55. info := e.backend.SystemInfo()
  56. plugins := map[api.PluginDescription]struct{}{}
  57. addPlugins := func(typ string, names []string) {
  58. for _, name := range names {
  59. plugins[api.PluginDescription{
  60. Type: typ,
  61. Name: name,
  62. }] = struct{}{}
  63. }
  64. }
  65. // add v1 plugins
  66. addPlugins("Volume", info.Plugins.Volume)
  67. // Add builtin driver "overlay" (the only builtin multi-host driver) to
  68. // the plugin list by default.
  69. addPlugins("Network", append([]string{"overlay"}, info.Plugins.Network...))
  70. addPlugins("Authorization", info.Plugins.Authorization)
  71. addPlugins("Log", info.Plugins.Log)
  72. // add v2 plugins
  73. v2Plugins, err := e.backend.PluginManager().List(filters.NewArgs())
  74. if err == nil {
  75. for _, plgn := range v2Plugins {
  76. for _, typ := range plgn.Config.Interface.Types {
  77. if typ.Prefix != "docker" || !plgn.Enabled {
  78. continue
  79. }
  80. plgnTyp := typ.Capability
  81. switch typ.Capability {
  82. case "volumedriver":
  83. plgnTyp = "Volume"
  84. case "networkdriver":
  85. plgnTyp = "Network"
  86. case "logdriver":
  87. plgnTyp = "Log"
  88. }
  89. plugins[api.PluginDescription{
  90. Type: plgnTyp,
  91. Name: plgn.Name,
  92. }] = struct{}{}
  93. }
  94. }
  95. }
  96. pluginFields := make([]api.PluginDescription, 0, len(plugins))
  97. for k := range plugins {
  98. pluginFields = append(pluginFields, k)
  99. }
  100. sort.Sort(sortedPlugins(pluginFields))
  101. // parse []string labels into a map[string]string
  102. labels := map[string]string{}
  103. for _, l := range info.Labels {
  104. stringSlice := strings.SplitN(l, "=", 2)
  105. // this will take the last value in the list for a given key
  106. // ideally, one shouldn't assign multiple values to the same key
  107. if len(stringSlice) > 1 {
  108. labels[stringSlice[0]] = stringSlice[1]
  109. }
  110. }
  111. description := &api.NodeDescription{
  112. Hostname: info.Name,
  113. Platform: &api.Platform{
  114. Architecture: info.Architecture,
  115. OS: info.OSType,
  116. },
  117. Engine: &api.EngineDescription{
  118. EngineVersion: info.ServerVersion,
  119. Labels: labels,
  120. Plugins: pluginFields,
  121. },
  122. Resources: &api.Resources{
  123. NanoCPUs: int64(info.NCPU) * 1e9,
  124. MemoryBytes: info.MemTotal,
  125. Generic: convert.GenericResourcesToGRPC(info.GenericResources),
  126. },
  127. }
  128. // Save the node information in the executor field
  129. e.mutex.Lock()
  130. e.node = description
  131. e.mutex.Unlock()
  132. return description, nil
  133. }
  134. func (e *executor) Configure(ctx context.Context, node *api.Node) error {
  135. var ingressNA *api.NetworkAttachment
  136. attachments := make(map[string]string)
  137. for _, na := range node.Attachments {
  138. if na == nil || na.Network == nil || len(na.Addresses) == 0 {
  139. // this should not happen, but we got a panic here and don't have a
  140. // good idea about what the underlying data structure looks like.
  141. logrus.WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).
  142. Warnf("skipping nil or malformed node network attachment entry")
  143. continue
  144. }
  145. if na.Network.Spec.Ingress {
  146. ingressNA = na
  147. }
  148. attachments[na.Network.ID] = na.Addresses[0]
  149. }
  150. // discover which, if any, attachments have been removed.
  151. //
  152. // we aren't responsible directly for creating these networks. that is
  153. // handled indirectly when a container using that network is created.
  154. // however, when it comes time to remove the network, none of the relevant
  155. // tasks may exist anymore. this means we should go ahead and try to remove
  156. // any network we know to no longer be in use.
  157. // removeAttachments maps the network ID to a boolean. This boolean
  158. // indicates whether the attachment in question is totally removed (true),
  159. // or has just had its IP changed (false)
  160. removeAttachments := make(map[string]bool)
  161. // the first time we Configure, nodeObj wil be nil, because it will not be
  162. // set yet. in that case, skip this check.
  163. if e.nodeObj != nil {
  164. for _, na := range e.nodeObj.Attachments {
  165. // same thing as above, check sanity of the attachments so we don't
  166. // get a panic.
  167. if na == nil || na.Network == nil || len(na.Addresses) == 0 {
  168. logrus.WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).
  169. Warnf("skipping nil or malformed node network attachment entry")
  170. continue
  171. }
  172. // now, check if the attachment exists and shares the same IP address.
  173. if ip, ok := attachments[na.Network.ID]; !ok || na.Addresses[0] != ip {
  174. // if the map entry exists, then the network still exists, and the
  175. // IP must be what has changed
  176. removeAttachments[na.Network.ID] = !ok
  177. }
  178. }
  179. }
  180. if (ingressNA == nil) && (node.Attachment != nil) && (len(node.Attachment.Addresses) > 0) {
  181. ingressNA = node.Attachment
  182. attachments[ingressNA.Network.ID] = ingressNA.Addresses[0]
  183. }
  184. if ingressNA == nil {
  185. e.backend.ReleaseIngress()
  186. return e.backend.GetAttachmentStore().ResetAttachments(attachments)
  187. }
  188. options := types.NetworkCreate{
  189. Driver: ingressNA.Network.DriverState.Name,
  190. IPAM: &network.IPAM{
  191. Driver: ingressNA.Network.IPAM.Driver.Name,
  192. },
  193. Options: ingressNA.Network.DriverState.Options,
  194. Ingress: true,
  195. CheckDuplicate: true,
  196. }
  197. for _, ic := range ingressNA.Network.IPAM.Configs {
  198. c := network.IPAMConfig{
  199. Subnet: ic.Subnet,
  200. IPRange: ic.Range,
  201. Gateway: ic.Gateway,
  202. }
  203. options.IPAM.Config = append(options.IPAM.Config, c)
  204. }
  205. _, err := e.backend.SetupIngress(clustertypes.NetworkCreateRequest{
  206. ID: ingressNA.Network.ID,
  207. NetworkCreateRequest: types.NetworkCreateRequest{
  208. Name: ingressNA.Network.Spec.Annotations.Name,
  209. NetworkCreate: options,
  210. },
  211. }, ingressNA.Addresses[0])
  212. if err != nil {
  213. return err
  214. }
  215. var (
  216. activeEndpointsError *libnetwork.ActiveEndpointsError
  217. errNoSuchNetwork libnetwork.ErrNoSuchNetwork
  218. )
  219. // now, finally, remove any network LB attachments that we no longer have.
  220. for nw, gone := range removeAttachments {
  221. err := e.backend.DeleteManagedNetwork(nw)
  222. switch {
  223. case err == nil:
  224. continue
  225. case errors.As(err, &activeEndpointsError):
  226. // this is the purpose of the boolean in the map. it's literally
  227. // just to log an appropriate, informative error. i'm unsure if
  228. // this can ever actually occur, but we need to know if it does.
  229. if gone {
  230. log.G(ctx).Warnf("network %s should be removed, but still has active attachments", nw)
  231. } else {
  232. log.G(ctx).Warnf(
  233. "network %s should have its node LB IP changed, but cannot be removed because of active attachments",
  234. nw,
  235. )
  236. }
  237. continue
  238. case errors.As(err, &errNoSuchNetwork):
  239. // NoSuchNetworkError indicates the network is already gone.
  240. continue
  241. default:
  242. log.G(ctx).Errorf("network %s remove failed: %v", nw, err)
  243. }
  244. }
  245. // now update our copy of the node object, reset the attachment store, and
  246. // return
  247. e.nodeObj = node
  248. return e.backend.GetAttachmentStore().ResetAttachments(attachments)
  249. }
  250. // Controller returns a docker container runner.
  251. func (e *executor) Controller(t *api.Task) (exec.Controller, error) {
  252. dependencyGetter := template.NewTemplatedDependencyGetter(agent.Restrict(e.dependencies, t), t, nil)
  253. // Get the node description from the executor field
  254. e.mutex.Lock()
  255. nodeDescription := e.node
  256. e.mutex.Unlock()
  257. if t.Spec.GetAttachment() != nil {
  258. return newNetworkAttacherController(e.backend, e.imageBackend, e.volumeBackend, t, nodeDescription, dependencyGetter)
  259. }
  260. var ctlr exec.Controller
  261. switch r := t.Spec.GetRuntime().(type) {
  262. case *api.TaskSpec_Generic:
  263. logrus.WithFields(logrus.Fields{
  264. "kind": r.Generic.Kind,
  265. "type_url": r.Generic.Payload.TypeUrl,
  266. }).Debug("custom runtime requested")
  267. runtimeKind, err := naming.Runtime(t.Spec)
  268. if err != nil {
  269. return ctlr, err
  270. }
  271. switch runtimeKind {
  272. case string(swarmtypes.RuntimePlugin):
  273. if !e.backend.HasExperimental() {
  274. return ctlr, fmt.Errorf("runtime type %q only supported in experimental", swarmtypes.RuntimePlugin)
  275. }
  276. c, err := plugin.NewController(e.pluginBackend, t)
  277. if err != nil {
  278. return ctlr, err
  279. }
  280. ctlr = c
  281. default:
  282. return ctlr, fmt.Errorf("unsupported runtime type: %q", runtimeKind)
  283. }
  284. case *api.TaskSpec_Container:
  285. c, err := newController(e.backend, e.imageBackend, e.volumeBackend, t, nodeDescription, dependencyGetter)
  286. if err != nil {
  287. return ctlr, err
  288. }
  289. ctlr = c
  290. default:
  291. return ctlr, fmt.Errorf("unsupported runtime: %q", r)
  292. }
  293. return ctlr, nil
  294. }
  295. func (e *executor) SetNetworkBootstrapKeys(keys []*api.EncryptionKey) error {
  296. nwKeys := []*networktypes.EncryptionKey{}
  297. for _, key := range keys {
  298. nwKey := &networktypes.EncryptionKey{
  299. Subsystem: key.Subsystem,
  300. Algorithm: int32(key.Algorithm),
  301. Key: make([]byte, len(key.Key)),
  302. LamportTime: key.LamportTime,
  303. }
  304. copy(nwKey.Key, key.Key)
  305. nwKeys = append(nwKeys, nwKey)
  306. }
  307. e.backend.SetNetworkBootstrapKeys(nwKeys)
  308. return nil
  309. }
  310. func (e *executor) Secrets() exec.SecretsManager {
  311. return e.dependencies.Secrets()
  312. }
  313. func (e *executor) Configs() exec.ConfigsManager {
  314. return e.dependencies.Configs()
  315. }
  316. type sortedPlugins []api.PluginDescription
  317. func (sp sortedPlugins) Len() int { return len(sp) }
  318. func (sp sortedPlugins) Swap(i, j int) { sp[i], sp[j] = sp[j], sp[i] }
  319. func (sp sortedPlugins) Less(i, j int) bool {
  320. if sp[i].Type != sp[j].Type {
  321. return sp[i].Type < sp[j].Type
  322. }
  323. return sp[i].Name < sp[j].Name
  324. }