handlers.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. /*
  2. Copyright 2014 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 lifecycle
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "strconv"
  21. "github.com/golang/glog"
  22. "k8s.io/kubernetes/pkg/api"
  23. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  24. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  25. "k8s.io/kubernetes/pkg/kubelet/util/format"
  26. "k8s.io/kubernetes/pkg/kubelet/util/ioutils"
  27. "k8s.io/kubernetes/pkg/security/apparmor"
  28. "k8s.io/kubernetes/pkg/types"
  29. "k8s.io/kubernetes/pkg/util/intstr"
  30. )
  31. type HandlerRunner struct {
  32. httpGetter kubetypes.HttpGetter
  33. commandRunner kubecontainer.ContainerCommandRunner
  34. containerManager podStatusProvider
  35. }
  36. type podStatusProvider interface {
  37. GetPodStatus(uid types.UID, name, namespace string) (*kubecontainer.PodStatus, error)
  38. }
  39. func NewHandlerRunner(httpGetter kubetypes.HttpGetter, commandRunner kubecontainer.ContainerCommandRunner, containerManager podStatusProvider) kubecontainer.HandlerRunner {
  40. return &HandlerRunner{
  41. httpGetter: httpGetter,
  42. commandRunner: commandRunner,
  43. containerManager: containerManager,
  44. }
  45. }
  46. func (hr *HandlerRunner) Run(containerID kubecontainer.ContainerID, pod *api.Pod, container *api.Container, handler *api.Handler) (string, error) {
  47. switch {
  48. case handler.Exec != nil:
  49. var (
  50. buffer bytes.Buffer
  51. msg string
  52. )
  53. output := ioutils.WriteCloserWrapper(&buffer)
  54. err := hr.commandRunner.ExecInContainer(containerID, handler.Exec.Command, nil, output, output, false, nil)
  55. if err != nil {
  56. msg := fmt.Sprintf("Exec lifecycle hook (%v) for Container %q in Pod %q failed - %q", handler.Exec.Command, container.Name, format.Pod(pod), buffer.String())
  57. glog.V(1).Infof(msg)
  58. }
  59. return msg, err
  60. case handler.HTTPGet != nil:
  61. msg, err := hr.runHTTPHandler(pod, container, handler)
  62. if err != nil {
  63. msg := fmt.Sprintf("Http lifecycle hook (%s) for Container %q in Pod %q failed - %q", handler.HTTPGet.Path, container.Name, format.Pod(pod), msg)
  64. glog.V(1).Infof(msg)
  65. }
  66. return msg, err
  67. default:
  68. err := fmt.Errorf("Invalid handler: %v", handler)
  69. msg := fmt.Sprintf("Cannot run handler: %v", err)
  70. glog.Errorf(msg)
  71. return msg, err
  72. }
  73. }
  74. // resolvePort attempts to turn an IntOrString port reference into a concrete port number.
  75. // If portReference has an int value, it is treated as a literal, and simply returns that value.
  76. // If portReference is a string, an attempt is first made to parse it as an integer. If that fails,
  77. // an attempt is made to find a port with the same name in the container spec.
  78. // If a port with the same name is found, it's ContainerPort value is returned. If no matching
  79. // port is found, an error is returned.
  80. func resolvePort(portReference intstr.IntOrString, container *api.Container) (int, error) {
  81. if portReference.Type == intstr.Int {
  82. return portReference.IntValue(), nil
  83. }
  84. portName := portReference.StrVal
  85. port, err := strconv.Atoi(portName)
  86. if err == nil {
  87. return port, nil
  88. }
  89. for _, portSpec := range container.Ports {
  90. if portSpec.Name == portName {
  91. return int(portSpec.ContainerPort), nil
  92. }
  93. }
  94. return -1, fmt.Errorf("couldn't find port: %v in %v", portReference, container)
  95. }
  96. func (hr *HandlerRunner) runHTTPHandler(pod *api.Pod, container *api.Container, handler *api.Handler) (string, error) {
  97. host := handler.HTTPGet.Host
  98. if len(host) == 0 {
  99. status, err := hr.containerManager.GetPodStatus(pod.UID, pod.Name, pod.Namespace)
  100. if err != nil {
  101. glog.Errorf("Unable to get pod info, event handlers may be invalid.")
  102. return "", err
  103. }
  104. if status.IP == "" {
  105. return "", fmt.Errorf("failed to find networking container: %v", status)
  106. }
  107. host = status.IP
  108. }
  109. var port int
  110. if handler.HTTPGet.Port.Type == intstr.String && len(handler.HTTPGet.Port.StrVal) == 0 {
  111. port = 80
  112. } else {
  113. var err error
  114. port, err = resolvePort(handler.HTTPGet.Port, container)
  115. if err != nil {
  116. return "", err
  117. }
  118. }
  119. url := fmt.Sprintf("http://%s/%s", net.JoinHostPort(host, strconv.Itoa(port)), handler.HTTPGet.Path)
  120. resp, err := hr.httpGetter.Get(url)
  121. return getHttpRespBody(resp), err
  122. }
  123. func getHttpRespBody(resp *http.Response) string {
  124. if resp == nil {
  125. return ""
  126. }
  127. defer resp.Body.Close()
  128. if bytes, err := ioutil.ReadAll(resp.Body); err == nil {
  129. return string(bytes)
  130. }
  131. return ""
  132. }
  133. func NewAppArmorAdmitHandler(validator apparmor.Validator) PodAdmitHandler {
  134. return &appArmorAdmitHandler{
  135. Validator: validator,
  136. }
  137. }
  138. type appArmorAdmitHandler struct {
  139. apparmor.Validator
  140. }
  141. func (a *appArmorAdmitHandler) Admit(attrs *PodAdmitAttributes) PodAdmitResult {
  142. err := a.Validate(attrs.Pod)
  143. if err == nil {
  144. return PodAdmitResult{Admit: true}
  145. }
  146. return PodAdmitResult{
  147. Admit: false,
  148. Reason: "AppArmor",
  149. Message: fmt.Sprintf("Cannot enforce AppArmor: %v", err),
  150. }
  151. }