executor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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/moby/swarmkit/v2/agent"
  19. "github.com/moby/swarmkit/v2/agent/exec"
  20. "github.com/moby/swarmkit/v2/api"
  21. "github.com/moby/swarmkit/v2/api/naming"
  22. "github.com/moby/swarmkit/v2/log"
  23. "github.com/moby/swarmkit/v2/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(b.PluginGetter()),
  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. k, v, ok := strings.Cut(l, "=")
  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 ok {
  108. labels[k] = v
  109. }
  110. }
  111. // TODO(dperny): don't ignore the error here
  112. csiInfo, _ := e.Volumes().Plugins().NodeInfo(ctx)
  113. description := &api.NodeDescription{
  114. Hostname: info.Name,
  115. Platform: &api.Platform{
  116. Architecture: info.Architecture,
  117. OS: info.OSType,
  118. },
  119. Engine: &api.EngineDescription{
  120. EngineVersion: info.ServerVersion,
  121. Labels: labels,
  122. Plugins: pluginFields,
  123. },
  124. Resources: &api.Resources{
  125. NanoCPUs: int64(info.NCPU) * 1e9,
  126. MemoryBytes: info.MemTotal,
  127. Generic: convert.GenericResourcesToGRPC(info.GenericResources),
  128. },
  129. CSIInfo: csiInfo,
  130. }
  131. // Save the node information in the executor field
  132. e.mutex.Lock()
  133. e.node = description
  134. e.mutex.Unlock()
  135. return description, nil
  136. }
  137. func (e *executor) Configure(ctx context.Context, node *api.Node) error {
  138. var ingressNA *api.NetworkAttachment
  139. attachments := make(map[string]string)
  140. for _, na := range node.Attachments {
  141. if na == nil || na.Network == nil || len(na.Addresses) == 0 {
  142. // this should not happen, but we got a panic here and don't have a
  143. // good idea about what the underlying data structure looks like.
  144. logrus.WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).
  145. Warnf("skipping nil or malformed node network attachment entry")
  146. continue
  147. }
  148. if na.Network.Spec.Ingress {
  149. ingressNA = na
  150. }
  151. attachments[na.Network.ID] = na.Addresses[0]
  152. }
  153. // discover which, if any, attachments have been removed.
  154. //
  155. // we aren't responsible directly for creating these networks. that is
  156. // handled indirectly when a container using that network is created.
  157. // however, when it comes time to remove the network, none of the relevant
  158. // tasks may exist anymore. this means we should go ahead and try to remove
  159. // any network we know to no longer be in use.
  160. // removeAttachments maps the network ID to a boolean. This boolean
  161. // indicates whether the attachment in question is totally removed (true),
  162. // or has just had its IP changed (false)
  163. removeAttachments := make(map[string]bool)
  164. // the first time we Configure, nodeObj wil be nil, because it will not be
  165. // set yet. in that case, skip this check.
  166. if e.nodeObj != nil {
  167. for _, na := range e.nodeObj.Attachments {
  168. // same thing as above, check sanity of the attachments so we don't
  169. // get a panic.
  170. if na == nil || na.Network == nil || len(na.Addresses) == 0 {
  171. logrus.WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).
  172. Warnf("skipping nil or malformed node network attachment entry")
  173. continue
  174. }
  175. // now, check if the attachment exists and shares the same IP address.
  176. if ip, ok := attachments[na.Network.ID]; !ok || na.Addresses[0] != ip {
  177. // if the map entry exists, then the network still exists, and the
  178. // IP must be what has changed
  179. removeAttachments[na.Network.ID] = !ok
  180. }
  181. }
  182. }
  183. if (ingressNA == nil) && (node.Attachment != nil) && (len(node.Attachment.Addresses) > 0) {
  184. ingressNA = node.Attachment
  185. attachments[ingressNA.Network.ID] = ingressNA.Addresses[0]
  186. }
  187. if ingressNA == nil {
  188. e.backend.ReleaseIngress()
  189. return e.backend.GetAttachmentStore().ResetAttachments(attachments)
  190. }
  191. options := types.NetworkCreate{
  192. Driver: ingressNA.Network.DriverState.Name,
  193. IPAM: &network.IPAM{
  194. Driver: ingressNA.Network.IPAM.Driver.Name,
  195. },
  196. Options: ingressNA.Network.DriverState.Options,
  197. Ingress: true,
  198. CheckDuplicate: true,
  199. }
  200. for _, ic := range ingressNA.Network.IPAM.Configs {
  201. c := network.IPAMConfig{
  202. Subnet: ic.Subnet,
  203. IPRange: ic.Range,
  204. Gateway: ic.Gateway,
  205. }
  206. options.IPAM.Config = append(options.IPAM.Config, c)
  207. }
  208. _, err := e.backend.SetupIngress(clustertypes.NetworkCreateRequest{
  209. ID: ingressNA.Network.ID,
  210. NetworkCreateRequest: types.NetworkCreateRequest{
  211. Name: ingressNA.Network.Spec.Annotations.Name,
  212. NetworkCreate: options,
  213. },
  214. }, ingressNA.Addresses[0])
  215. if err != nil {
  216. return err
  217. }
  218. var (
  219. activeEndpointsError *libnetwork.ActiveEndpointsError
  220. errNoSuchNetwork libnetwork.ErrNoSuchNetwork
  221. )
  222. // now, finally, remove any network LB attachments that we no longer have.
  223. for nw, gone := range removeAttachments {
  224. err := e.backend.DeleteManagedNetwork(nw)
  225. switch {
  226. case err == nil:
  227. continue
  228. case errors.As(err, &activeEndpointsError):
  229. // this is the purpose of the boolean in the map. it's literally
  230. // just to log an appropriate, informative error. i'm unsure if
  231. // this can ever actually occur, but we need to know if it does.
  232. if gone {
  233. log.G(ctx).Warnf("network %s should be removed, but still has active attachments", nw)
  234. } else {
  235. log.G(ctx).Warnf(
  236. "network %s should have its node LB IP changed, but cannot be removed because of active attachments",
  237. nw,
  238. )
  239. }
  240. continue
  241. case errors.As(err, &errNoSuchNetwork):
  242. // NoSuchNetworkError indicates the network is already gone.
  243. continue
  244. default:
  245. log.G(ctx).Errorf("network %s remove failed: %v", nw, err)
  246. }
  247. }
  248. // now update our copy of the node object, reset the attachment store, and
  249. // return
  250. e.nodeObj = node
  251. return e.backend.GetAttachmentStore().ResetAttachments(attachments)
  252. }
  253. // Controller returns a docker container runner.
  254. func (e *executor) Controller(t *api.Task) (exec.Controller, error) {
  255. dependencyGetter := template.NewTemplatedDependencyGetter(agent.Restrict(e.dependencies, t), t, nil)
  256. // Get the node description from the executor field
  257. e.mutex.Lock()
  258. nodeDescription := e.node
  259. e.mutex.Unlock()
  260. if t.Spec.GetAttachment() != nil {
  261. return newNetworkAttacherController(e.backend, e.imageBackend, e.volumeBackend, t, nodeDescription, dependencyGetter)
  262. }
  263. var ctlr exec.Controller
  264. switch r := t.Spec.GetRuntime().(type) {
  265. case *api.TaskSpec_Generic:
  266. logrus.WithFields(logrus.Fields{
  267. "kind": r.Generic.Kind,
  268. "type_url": r.Generic.Payload.TypeUrl,
  269. }).Debug("custom runtime requested")
  270. runtimeKind, err := naming.Runtime(t.Spec)
  271. if err != nil {
  272. return ctlr, err
  273. }
  274. switch runtimeKind {
  275. case string(swarmtypes.RuntimePlugin):
  276. if !e.backend.HasExperimental() {
  277. return ctlr, fmt.Errorf("runtime type %q only supported in experimental", swarmtypes.RuntimePlugin)
  278. }
  279. c, err := plugin.NewController(e.pluginBackend, t)
  280. if err != nil {
  281. return ctlr, err
  282. }
  283. ctlr = c
  284. default:
  285. return ctlr, fmt.Errorf("unsupported runtime type: %q", runtimeKind)
  286. }
  287. case *api.TaskSpec_Container:
  288. c, err := newController(e.backend, e.imageBackend, e.volumeBackend, t, nodeDescription, dependencyGetter)
  289. if err != nil {
  290. return ctlr, err
  291. }
  292. ctlr = c
  293. default:
  294. return ctlr, fmt.Errorf("unsupported runtime: %q", r)
  295. }
  296. return ctlr, nil
  297. }
  298. func (e *executor) SetNetworkBootstrapKeys(keys []*api.EncryptionKey) error {
  299. nwKeys := []*networktypes.EncryptionKey{}
  300. for _, key := range keys {
  301. nwKey := &networktypes.EncryptionKey{
  302. Subsystem: key.Subsystem,
  303. Algorithm: int32(key.Algorithm),
  304. Key: make([]byte, len(key.Key)),
  305. LamportTime: key.LamportTime,
  306. }
  307. copy(nwKey.Key, key.Key)
  308. nwKeys = append(nwKeys, nwKey)
  309. }
  310. e.backend.SetNetworkBootstrapKeys(nwKeys)
  311. return nil
  312. }
  313. func (e *executor) Secrets() exec.SecretsManager {
  314. return e.dependencies.Secrets()
  315. }
  316. func (e *executor) Configs() exec.ConfigsManager {
  317. return e.dependencies.Configs()
  318. }
  319. func (e *executor) Volumes() exec.VolumesManager {
  320. return e.dependencies.Volumes()
  321. }
  322. type sortedPlugins []api.PluginDescription
  323. func (sp sortedPlugins) Len() int { return len(sp) }
  324. func (sp sortedPlugins) Swap(i, j int) { sp[i], sp[j] = sp[j], sp[i] }
  325. func (sp sortedPlugins) Less(i, j int) bool {
  326. if sp[i].Type != sp[j].Type {
  327. return sp[i].Type < sp[j].Type
  328. }
  329. return sp[i].Name < sp[j].Name
  330. }