helpers.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. "math/rand"
  17. "strconv"
  18. "strings"
  19. dockertypes "github.com/docker/engine-api/types"
  20. dockerfilters "github.com/docker/engine-api/types/filters"
  21. dockerapiversion "github.com/docker/engine-api/types/versions"
  22. dockernat "github.com/docker/go-connections/nat"
  23. "github.com/golang/glog"
  24. runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
  25. )
  26. const (
  27. // kubePrefix is used to identify the containers/sandboxes on the node managed by kubelet
  28. kubePrefix = "k8s"
  29. // kubeSandboxNamePrefix is used to keep sandbox name consistent with old podInfraContainer name
  30. kubeSandboxNamePrefix = "POD"
  31. )
  32. // apiVersion implements kubecontainer.Version interface by implementing
  33. // Compare() and String(). It uses the compare function of engine-api to
  34. // compare docker apiversions.
  35. type apiVersion string
  36. func (v apiVersion) String() string {
  37. return string(v)
  38. }
  39. func (v apiVersion) Compare(other string) (int, error) {
  40. if dockerapiversion.LessThan(string(v), other) {
  41. return -1, nil
  42. } else if dockerapiversion.GreaterThan(string(v), other) {
  43. return 1, nil
  44. }
  45. return 0, nil
  46. }
  47. // generateEnvList converts KeyValue list to a list of strings, in the form of
  48. // '<key>=<value>', which can be understood by docker.
  49. func generateEnvList(envs []*runtimeApi.KeyValue) (result []string) {
  50. for _, env := range envs {
  51. result = append(result, fmt.Sprintf("%s=%s", env.GetKey(), env.GetValue()))
  52. }
  53. return
  54. }
  55. // Merge annotations and labels because docker supports only labels.
  56. // TODO: Need to be able to distinguish annotations from labels; otherwise, we
  57. // couldn't restore the information when reading the labels back from docker.
  58. func makeLabels(labels, annotations map[string]string) map[string]string {
  59. merged := make(map[string]string)
  60. for k, v := range labels {
  61. merged[k] = v
  62. }
  63. for k, v := range annotations {
  64. if _, ok := merged[k]; !ok {
  65. // Don't overwrite the key if it already exists.
  66. merged[k] = v
  67. }
  68. }
  69. return merged
  70. }
  71. // generateMountBindings converts the mount list to a list of strings that
  72. // can be understood by docker.
  73. // Each element in the string is in the form of:
  74. // '<HostPath>:<ContainerPath>', or
  75. // '<HostPath>:<ContainerPath>:ro', if the path is read only, or
  76. // '<HostPath>:<ContainerPath>:Z', if the volume requires SELinux
  77. // relabeling and the pod provides an SELinux label
  78. func generateMountBindings(mounts []*runtimeApi.Mount) (result []string) {
  79. // TODO: resolve podHasSELinuxLabel
  80. for _, m := range mounts {
  81. bind := fmt.Sprintf("%s:%s", m.GetHostPath(), m.GetContainerPath())
  82. readOnly := m.GetReadonly()
  83. if readOnly {
  84. bind += ":ro"
  85. }
  86. if m.GetSelinuxRelabel() {
  87. if readOnly {
  88. bind += ",Z"
  89. } else {
  90. bind += ":Z"
  91. }
  92. }
  93. result = append(result, bind)
  94. }
  95. return
  96. }
  97. func makePortsAndBindings(pm []*runtimeApi.PortMapping) (map[dockernat.Port]struct{}, map[dockernat.Port][]dockernat.PortBinding) {
  98. exposedPorts := map[dockernat.Port]struct{}{}
  99. portBindings := map[dockernat.Port][]dockernat.PortBinding{}
  100. for _, port := range pm {
  101. exteriorPort := port.GetHostPort()
  102. if exteriorPort == 0 {
  103. // No need to do port binding when HostPort is not specified
  104. continue
  105. }
  106. interiorPort := port.GetContainerPort()
  107. // Some of this port stuff is under-documented voodoo.
  108. // See http://stackoverflow.com/questions/20428302/binding-a-port-to-a-host-interface-using-the-rest-api
  109. var protocol string
  110. switch strings.ToUpper(string(port.GetProtocol())) {
  111. case "UDP":
  112. protocol = "/udp"
  113. case "TCP":
  114. protocol = "/tcp"
  115. default:
  116. glog.Warningf("Unknown protocol %q: defaulting to TCP", port.Protocol)
  117. protocol = "/tcp"
  118. }
  119. dockerPort := dockernat.Port(strconv.Itoa(int(interiorPort)) + protocol)
  120. exposedPorts[dockerPort] = struct{}{}
  121. hostBinding := dockernat.PortBinding{
  122. HostPort: strconv.Itoa(int(exteriorPort)),
  123. HostIP: port.GetHostIp(),
  124. }
  125. // Allow multiple host ports bind to same docker port
  126. if existedBindings, ok := portBindings[dockerPort]; ok {
  127. // If a docker port already map to a host port, just append the host ports
  128. portBindings[dockerPort] = append(existedBindings, hostBinding)
  129. } else {
  130. // Otherwise, it's fresh new port binding
  131. portBindings[dockerPort] = []dockernat.PortBinding{
  132. hostBinding,
  133. }
  134. }
  135. }
  136. return exposedPorts, portBindings
  137. }
  138. // TODO: Seccomp support. Need to figure out how to pass seccomp options
  139. // through the runtime API (annotations?).See dockerManager.getSecurityOpts()
  140. // for the details. Always set the default seccomp profile for now.
  141. // Also need to support syntax for different docker versions.
  142. func getSeccompOpts() string {
  143. return fmt.Sprintf("%s=%s", "seccomp", defaultSeccompProfile)
  144. }
  145. func getNetworkNamespace(c *dockertypes.ContainerJSON) string {
  146. return fmt.Sprintf(dockerNetNSFmt, c.State.Pid)
  147. }
  148. // buildKubeGenericName creates a name which can be reversed to identify container/sandbox name.
  149. // This function returns the unique name.
  150. func buildKubeGenericName(sandboxConfig *runtimeApi.PodSandboxConfig, containerName string) string {
  151. stableName := fmt.Sprintf("%s_%s_%s_%s_%s",
  152. kubePrefix,
  153. containerName,
  154. sandboxConfig.Metadata.GetName(),
  155. sandboxConfig.Metadata.GetNamespace(),
  156. sandboxConfig.Metadata.GetUid(),
  157. )
  158. UID := fmt.Sprintf("%08x", rand.Uint32())
  159. return fmt.Sprintf("%s_%s", stableName, UID)
  160. }
  161. // buildSandboxName creates a name which can be reversed to identify sandbox full name.
  162. func buildSandboxName(sandboxConfig *runtimeApi.PodSandboxConfig) string {
  163. sandboxName := fmt.Sprintf("%s.%d", kubeSandboxNamePrefix, sandboxConfig.Metadata.GetAttempt())
  164. return buildKubeGenericName(sandboxConfig, sandboxName)
  165. }
  166. // parseSandboxName unpacks a sandbox full name, returning the pod name, namespace, uid and attempt.
  167. func parseSandboxName(name string) (string, string, string, uint32, error) {
  168. podName, podNamespace, podUID, _, attempt, err := parseContainerName(name)
  169. if err != nil {
  170. return "", "", "", 0, err
  171. }
  172. return podName, podNamespace, podUID, attempt, nil
  173. }
  174. // buildContainerName creates a name which can be reversed to identify container name.
  175. // This function returns stable name, unique name and an unique id.
  176. func buildContainerName(sandboxConfig *runtimeApi.PodSandboxConfig, containerConfig *runtimeApi.ContainerConfig) string {
  177. containerName := fmt.Sprintf("%s.%d", containerConfig.Metadata.GetName(), containerConfig.Metadata.GetAttempt())
  178. return buildKubeGenericName(sandboxConfig, containerName)
  179. }
  180. // parseContainerName unpacks a container name, returning the pod name, namespace, UID,
  181. // container name and attempt.
  182. func parseContainerName(name string) (podName, podNamespace, podUID, containerName string, attempt uint32, err error) {
  183. parts := strings.Split(name, "_")
  184. if len(parts) == 0 || parts[0] != kubePrefix {
  185. err = fmt.Errorf("failed to parse container name %q into parts", name)
  186. return "", "", "", "", 0, err
  187. }
  188. if len(parts) < 6 {
  189. glog.Warningf("Found a container with the %q prefix, but too few fields (%d): %q", kubePrefix, len(parts), name)
  190. err = fmt.Errorf("container name %q has fewer parts than expected %v", name, parts)
  191. return "", "", "", "", 0, err
  192. }
  193. nameParts := strings.Split(parts[1], ".")
  194. containerName = nameParts[0]
  195. if len(nameParts) > 1 {
  196. attemptNumber, err := strconv.ParseUint(nameParts[1], 10, 32)
  197. if err != nil {
  198. glog.Warningf("invalid container attempt %q in container %q", nameParts[1], name)
  199. }
  200. attempt = uint32(attemptNumber)
  201. }
  202. return parts[2], parts[3], parts[4], containerName, attempt, nil
  203. }
  204. // dockerFilter wraps around dockerfilters.Args and provides methods to modify
  205. // the filter easily.
  206. type dockerFilter struct {
  207. f *dockerfilters.Args
  208. }
  209. func newDockerFilter(args *dockerfilters.Args) *dockerFilter {
  210. return &dockerFilter{f: args}
  211. }
  212. func (f *dockerFilter) Add(key, value string) {
  213. f.Add(key, value)
  214. }
  215. func (f *dockerFilter) AddLabel(key, value string) {
  216. f.Add("label", fmt.Sprintf("%s=%s", key, value))
  217. }