helpers.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package dockershim
  14. import (
  15. "fmt"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. dockertypes "github.com/docker/docker/api/types"
  20. dockercontainer "github.com/docker/docker/api/types/container"
  21. dockerfilters "github.com/docker/docker/api/types/filters"
  22. dockernat "github.com/docker/go-connections/nat"
  23. "k8s.io/klog"
  24. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  25. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  26. "k8s.io/kubernetes/pkg/credentialprovider"
  27. "k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker"
  28. "k8s.io/kubernetes/pkg/kubelet/types"
  29. "k8s.io/kubernetes/pkg/security/apparmor"
  30. "k8s.io/kubernetes/pkg/util/parsers"
  31. )
  32. const (
  33. annotationPrefix = "annotation."
  34. securityOptSeparator = '='
  35. )
  36. var (
  37. conflictRE = regexp.MustCompile(`Conflict. (?:.)+ is already in use by container \"?([0-9a-z]+)\"?`)
  38. // this is hacky, but extremely common.
  39. // if a container starts but the executable file is not found, runc gives a message that matches
  40. startRE = regexp.MustCompile(`\\\\\\\"(.*)\\\\\\\": executable file not found`)
  41. defaultSeccompOpt = []dockerOpt{{"seccomp", "unconfined", ""}}
  42. )
  43. // generateEnvList converts KeyValue list to a list of strings, in the form of
  44. // '<key>=<value>', which can be understood by docker.
  45. func generateEnvList(envs []*runtimeapi.KeyValue) (result []string) {
  46. for _, env := range envs {
  47. result = append(result, fmt.Sprintf("%s=%s", env.Key, env.Value))
  48. }
  49. return
  50. }
  51. // makeLabels converts annotations to labels and merge them with the given
  52. // labels. This is necessary because docker does not support annotations;
  53. // we *fake* annotations using labels. Note that docker labels are not
  54. // updatable.
  55. func makeLabels(labels, annotations map[string]string) map[string]string {
  56. merged := make(map[string]string)
  57. for k, v := range labels {
  58. merged[k] = v
  59. }
  60. for k, v := range annotations {
  61. // Assume there won't be conflict.
  62. merged[fmt.Sprintf("%s%s", annotationPrefix, k)] = v
  63. }
  64. return merged
  65. }
  66. // extractLabels converts raw docker labels to the CRI labels and annotations.
  67. // It also filters out internal labels used by this shim.
  68. func extractLabels(input map[string]string) (map[string]string, map[string]string) {
  69. labels := make(map[string]string)
  70. annotations := make(map[string]string)
  71. for k, v := range input {
  72. // Check if the key is used internally by the shim.
  73. internal := false
  74. for _, internalKey := range internalLabelKeys {
  75. if k == internalKey {
  76. internal = true
  77. break
  78. }
  79. }
  80. if internal {
  81. continue
  82. }
  83. // Delete the container name label for the sandbox. It is added in the shim,
  84. // should not be exposed via CRI.
  85. if k == types.KubernetesContainerNameLabel &&
  86. input[containerTypeLabelKey] == containerTypeLabelSandbox {
  87. continue
  88. }
  89. // Check if the label should be treated as an annotation.
  90. if strings.HasPrefix(k, annotationPrefix) {
  91. annotations[strings.TrimPrefix(k, annotationPrefix)] = v
  92. continue
  93. }
  94. labels[k] = v
  95. }
  96. return labels, annotations
  97. }
  98. // generateMountBindings converts the mount list to a list of strings that
  99. // can be understood by docker.
  100. // '<HostPath>:<ContainerPath>[:options]', where 'options'
  101. // is a comma-separated list of the following strings:
  102. // 'ro', if the path is read only
  103. // 'Z', if the volume requires SELinux relabeling
  104. // propagation mode such as 'rslave'
  105. func generateMountBindings(mounts []*runtimeapi.Mount) []string {
  106. result := make([]string, 0, len(mounts))
  107. for _, m := range mounts {
  108. bind := fmt.Sprintf("%s:%s", m.HostPath, m.ContainerPath)
  109. var attrs []string
  110. if m.Readonly {
  111. attrs = append(attrs, "ro")
  112. }
  113. // Only request relabeling if the pod provides an SELinux context. If the pod
  114. // does not provide an SELinux context relabeling will label the volume with
  115. // the container's randomly allocated MCS label. This would restrict access
  116. // to the volume to the container which mounts it first.
  117. if m.SelinuxRelabel {
  118. attrs = append(attrs, "Z")
  119. }
  120. switch m.Propagation {
  121. case runtimeapi.MountPropagation_PROPAGATION_PRIVATE:
  122. // noop, private is default
  123. case runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL:
  124. attrs = append(attrs, "rshared")
  125. case runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER:
  126. attrs = append(attrs, "rslave")
  127. default:
  128. klog.Warningf("unknown propagation mode for hostPath %q", m.HostPath)
  129. // Falls back to "private"
  130. }
  131. if len(attrs) > 0 {
  132. bind = fmt.Sprintf("%s:%s", bind, strings.Join(attrs, ","))
  133. }
  134. result = append(result, bind)
  135. }
  136. return result
  137. }
  138. func makePortsAndBindings(pm []*runtimeapi.PortMapping) (dockernat.PortSet, map[dockernat.Port][]dockernat.PortBinding) {
  139. exposedPorts := dockernat.PortSet{}
  140. portBindings := map[dockernat.Port][]dockernat.PortBinding{}
  141. for _, port := range pm {
  142. exteriorPort := port.HostPort
  143. if exteriorPort == 0 {
  144. // No need to do port binding when HostPort is not specified
  145. continue
  146. }
  147. interiorPort := port.ContainerPort
  148. // Some of this port stuff is under-documented voodoo.
  149. // See http://stackoverflow.com/questions/20428302/binding-a-port-to-a-host-interface-using-the-rest-api
  150. var protocol string
  151. switch port.Protocol {
  152. case runtimeapi.Protocol_UDP:
  153. protocol = "/udp"
  154. case runtimeapi.Protocol_TCP:
  155. protocol = "/tcp"
  156. case runtimeapi.Protocol_SCTP:
  157. protocol = "/sctp"
  158. default:
  159. klog.Warningf("Unknown protocol %q: defaulting to TCP", port.Protocol)
  160. protocol = "/tcp"
  161. }
  162. dockerPort := dockernat.Port(strconv.Itoa(int(interiorPort)) + protocol)
  163. exposedPorts[dockerPort] = struct{}{}
  164. hostBinding := dockernat.PortBinding{
  165. HostPort: strconv.Itoa(int(exteriorPort)),
  166. HostIP: port.HostIp,
  167. }
  168. // Allow multiple host ports bind to same docker port
  169. if existedBindings, ok := portBindings[dockerPort]; ok {
  170. // If a docker port already map to a host port, just append the host ports
  171. portBindings[dockerPort] = append(existedBindings, hostBinding)
  172. } else {
  173. // Otherwise, it's fresh new port binding
  174. portBindings[dockerPort] = []dockernat.PortBinding{
  175. hostBinding,
  176. }
  177. }
  178. }
  179. return exposedPorts, portBindings
  180. }
  181. // getApparmorSecurityOpts gets apparmor options from container config.
  182. func getApparmorSecurityOpts(sc *runtimeapi.LinuxContainerSecurityContext, separator rune) ([]string, error) {
  183. if sc == nil || sc.ApparmorProfile == "" {
  184. return nil, nil
  185. }
  186. appArmorOpts, err := getAppArmorOpts(sc.ApparmorProfile)
  187. if err != nil {
  188. return nil, err
  189. }
  190. fmtOpts := fmtDockerOpts(appArmorOpts, separator)
  191. return fmtOpts, nil
  192. }
  193. // dockerFilter wraps around dockerfilters.Args and provides methods to modify
  194. // the filter easily.
  195. type dockerFilter struct {
  196. args *dockerfilters.Args
  197. }
  198. func newDockerFilter(args *dockerfilters.Args) *dockerFilter {
  199. return &dockerFilter{args: args}
  200. }
  201. func (f *dockerFilter) Add(key, value string) {
  202. f.args.Add(key, value)
  203. }
  204. func (f *dockerFilter) AddLabel(key, value string) {
  205. f.Add("label", fmt.Sprintf("%s=%s", key, value))
  206. }
  207. // parseUserFromImageUser splits the user out of an user:group string.
  208. func parseUserFromImageUser(id string) string {
  209. if id == "" {
  210. return id
  211. }
  212. // split instances where the id may contain user:group
  213. if strings.Contains(id, ":") {
  214. return strings.Split(id, ":")[0]
  215. }
  216. // no group, just return the id
  217. return id
  218. }
  219. // getUserFromImageUser gets uid or user name of the image user.
  220. // If user is numeric, it will be treated as uid; or else, it is treated as user name.
  221. func getUserFromImageUser(imageUser string) (*int64, string) {
  222. user := parseUserFromImageUser(imageUser)
  223. // return both nil if user is not specified in the image.
  224. if user == "" {
  225. return nil, ""
  226. }
  227. // user could be either uid or user name. Try to interpret as numeric uid.
  228. uid, err := strconv.ParseInt(user, 10, 64)
  229. if err != nil {
  230. // If user is non numeric, assume it's user name.
  231. return nil, user
  232. }
  233. // If user is a numeric uid.
  234. return &uid, ""
  235. }
  236. // See #33189. If the previous attempt to create a sandbox container name FOO
  237. // failed due to "device or resource busy", it is possible that docker did
  238. // not clean up properly and has inconsistent internal state. Docker would
  239. // not report the existence of FOO, but would complain if user wants to
  240. // create a new container named FOO. To work around this, we parse the error
  241. // message to identify failure caused by naming conflict, and try to remove
  242. // the old container FOO.
  243. // See #40443. Sometimes even removal may fail with "no such container" error.
  244. // In that case we have to create the container with a randomized name.
  245. // TODO(random-liu): Remove this work around after docker 1.11 is deprecated.
  246. // TODO(#33189): Monitor the tests to see if the fix is sufficient.
  247. func recoverFromCreationConflictIfNeeded(client libdocker.Interface, createConfig dockertypes.ContainerCreateConfig, err error) (*dockercontainer.ContainerCreateCreatedBody, error) {
  248. matches := conflictRE.FindStringSubmatch(err.Error())
  249. if len(matches) != 2 {
  250. return nil, err
  251. }
  252. id := matches[1]
  253. klog.Warningf("Unable to create pod sandbox due to conflict. Attempting to remove sandbox %q", id)
  254. if rmErr := client.RemoveContainer(id, dockertypes.ContainerRemoveOptions{RemoveVolumes: true}); rmErr == nil {
  255. klog.V(2).Infof("Successfully removed conflicting container %q", id)
  256. return nil, err
  257. } else {
  258. klog.Errorf("Failed to remove the conflicting container %q: %v", id, rmErr)
  259. // Return if the error is not container not found error.
  260. if !libdocker.IsContainerNotFoundError(rmErr) {
  261. return nil, err
  262. }
  263. }
  264. // randomize the name to avoid conflict.
  265. createConfig.Name = randomizeName(createConfig.Name)
  266. klog.V(2).Infof("Create the container with randomized name %s", createConfig.Name)
  267. return client.CreateContainer(createConfig)
  268. }
  269. // transformStartContainerError does regex parsing on returned error
  270. // for where container runtimes are giving less than ideal error messages.
  271. func transformStartContainerError(err error) error {
  272. if err == nil {
  273. return nil
  274. }
  275. matches := startRE.FindStringSubmatch(err.Error())
  276. if len(matches) > 0 {
  277. return fmt.Errorf("executable not found in $PATH")
  278. }
  279. return err
  280. }
  281. // ensureSandboxImageExists pulls the sandbox image when it's not present.
  282. func ensureSandboxImageExists(client libdocker.Interface, image string) error {
  283. _, err := client.InspectImageByRef(image)
  284. if err == nil {
  285. return nil
  286. }
  287. if !libdocker.IsImageNotFoundError(err) {
  288. return fmt.Errorf("failed to inspect sandbox image %q: %v", image, err)
  289. }
  290. repoToPull, _, _, err := parsers.ParseImageName(image)
  291. if err != nil {
  292. return err
  293. }
  294. keyring := credentialprovider.NewDockerKeyring()
  295. creds, withCredentials := keyring.Lookup(repoToPull)
  296. if !withCredentials {
  297. klog.V(3).Infof("Pulling image %q without credentials", image)
  298. err := client.PullImage(image, dockertypes.AuthConfig{}, dockertypes.ImagePullOptions{})
  299. if err != nil {
  300. return fmt.Errorf("failed pulling image %q: %v", image, err)
  301. }
  302. return nil
  303. }
  304. var pullErrs []error
  305. for _, currentCreds := range creds {
  306. authConfig := dockertypes.AuthConfig(credentialprovider.LazyProvide(currentCreds, repoToPull))
  307. err := client.PullImage(image, authConfig, dockertypes.ImagePullOptions{})
  308. // If there was no error, return success
  309. if err == nil {
  310. return nil
  311. }
  312. pullErrs = append(pullErrs, err)
  313. }
  314. return utilerrors.NewAggregate(pullErrs)
  315. }
  316. func getAppArmorOpts(profile string) ([]dockerOpt, error) {
  317. if profile == "" || profile == apparmor.ProfileRuntimeDefault {
  318. // The docker applies the default profile by default.
  319. return nil, nil
  320. }
  321. // Return unconfined profile explicitly
  322. if profile == apparmor.ProfileNameUnconfined {
  323. return []dockerOpt{{"apparmor", apparmor.ProfileNameUnconfined, ""}}, nil
  324. }
  325. // Assume validation has already happened.
  326. profileName := strings.TrimPrefix(profile, apparmor.ProfileNamePrefix)
  327. return []dockerOpt{{"apparmor", profileName, ""}}, nil
  328. }
  329. // fmtDockerOpts formats the docker security options using the given separator.
  330. func fmtDockerOpts(opts []dockerOpt, sep rune) []string {
  331. fmtOpts := make([]string, len(opts))
  332. for i, opt := range opts {
  333. fmtOpts[i] = fmt.Sprintf("%s%c%s", opt.key, sep, opt.value)
  334. }
  335. return fmtOpts
  336. }
  337. type dockerOpt struct {
  338. // The key-value pair passed to docker.
  339. key, value string
  340. // The alternative value to use in log/event messages.
  341. msg string
  342. }
  343. // Expose key/value from dockerOpt.
  344. func (d dockerOpt) GetKV() (string, string) {
  345. return d.key, d.value
  346. }