k3s/pkg/kubelet/server.go

395 lines
11 KiB
Go
Raw Normal View History

2014-06-06 23:40:48 +00:00
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2014-06-06 23:40:48 +00:00
package kubelet
import (
2014-06-19 01:26:23 +00:00
"encoding/json"
2014-07-01 21:05:10 +00:00
"errors"
2014-06-06 23:40:48 +00:00
"fmt"
"io"
"net"
2014-06-06 23:40:48 +00:00
"net/http"
"net/url"
2014-07-01 21:05:10 +00:00
"path"
"strconv"
2014-07-01 21:05:10 +00:00
"strings"
"time"
2014-06-06 23:40:48 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
2014-10-22 23:52:38 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/latest"
"github.com/GoogleCloudPlatform/kubernetes/pkg/healthz"
"github.com/GoogleCloudPlatform/kubernetes/pkg/httplog"
"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
2015-01-14 23:22:21 +00:00
"github.com/GoogleCloudPlatform/kubernetes/pkg/types"
"github.com/golang/glog"
"github.com/google/cadvisor/info"
2014-06-06 23:40:48 +00:00
)
2014-07-15 13:54:23 +00:00
// Server is a http.Handler which exposes kubelet functionality over HTTP.
type Server struct {
host HostInterface
mux *http.ServeMux
2014-06-06 23:40:48 +00:00
}
// ListenAndServeKubeletServer initializes a server to respond to HTTP network requests on the Kubelet.
func ListenAndServeKubeletServer(host HostInterface, address net.IP, port uint, enableDebuggingHandlers bool) {
glog.V(1).Infof("Starting to listen on %s:%d", address, port)
handler := NewServer(host, enableDebuggingHandlers)
s := &http.Server{
2014-10-04 04:34:30 +00:00
Addr: net.JoinHostPort(address.String(), strconv.FormatUint(uint64(port), 10)),
Handler: &handler,
2014-11-10 16:09:50 +00:00
ReadTimeout: 5 * time.Minute,
WriteTimeout: 5 * time.Minute,
MaxHeaderBytes: 1 << 20,
}
glog.Fatal(s.ListenAndServe())
}
// HostInterface contains all the kubelet methods required by the server.
// For testablitiy.
type HostInterface interface {
2015-01-14 23:22:21 +00:00
GetContainerInfo(podFullName string, uid types.UID, containerName string, req *info.ContainerInfoRequest) (*info.ContainerInfo, error)
2014-07-15 22:40:02 +00:00
GetRootInfo(req *info.ContainerInfoRequest) (*info.ContainerInfo, error)
GetMachineInfo() (*info.MachineInfo, error)
2014-10-22 23:52:38 +00:00
GetBoundPods() ([]api.BoundPod, error)
GetPodByName(namespace, name string) (*api.BoundPod, bool)
2015-01-14 23:22:21 +00:00
GetPodInfo(name string, uid types.UID) (api.PodInfo, error)
RunInContainer(name string, uid types.UID, container string, cmd []string) ([]byte, error)
2014-09-22 20:14:23 +00:00
GetKubeletContainerLogs(podFullName, containerName, tail string, follow bool, stdout, stderr io.Writer) error
ServeLogs(w http.ResponseWriter, req *http.Request)
}
// NewServer initializes and configures a kubelet.Server object to handle HTTP requests.
func NewServer(host HostInterface, enableDebuggingHandlers bool) Server {
2014-08-20 18:24:51 +00:00
server := Server{
host: host,
mux: http.NewServeMux(),
2014-08-20 18:24:51 +00:00
}
server.InstallDefaultHandlers()
if enableDebuggingHandlers {
server.InstallDebuggingHandlers()
}
2014-08-20 18:24:51 +00:00
return server
}
// InstallDefaultHandlers registers the default set of supported HTTP request patterns with the mux.
2014-08-20 18:24:51 +00:00
func (s *Server) InstallDefaultHandlers() {
healthz.InstallHandler(s.mux)
s.mux.HandleFunc("/podInfo", s.handlePodInfoOld)
s.mux.HandleFunc("/api/v1beta1/podInfo", s.handlePodInfoVersioned)
2014-10-22 23:52:38 +00:00
s.mux.HandleFunc("/boundPods", s.handleBoundPods)
2014-08-20 18:24:51 +00:00
s.mux.HandleFunc("/stats/", s.handleStats)
s.mux.HandleFunc("/spec/", s.handleSpec)
}
// InstallDeguggingHandlers registers the HTTP request patterns that serve logs or run commands/containers
func (s *Server) InstallDebuggingHandlers() {
2014-08-26 19:57:44 +00:00
s.mux.HandleFunc("/run/", s.handleRun)
s.mux.HandleFunc("/logs/", s.handleLogs)
s.mux.HandleFunc("/containerLogs/", s.handleContainerLogs)
2014-08-20 18:24:51 +00:00
}
// error serializes an error object into an HTTP response.
2014-07-15 13:54:23 +00:00
func (s *Server) error(w http.ResponseWriter, err error) {
http.Error(w, fmt.Sprintf("Internal Error: %v", err), http.StatusInternalServerError)
2014-06-06 23:40:48 +00:00
}
2014-09-15 16:20:01 +00:00
// handleContainerLogs handles containerLogs request against the Kubelet
func (s *Server) handleContainerLogs(w http.ResponseWriter, req *http.Request) {
defer req.Body.Close()
u, err := url.ParseRequestURI(req.RequestURI)
if err != nil {
s.error(w, err)
return
}
parts := strings.Split(u.Path, "/")
// req URI: /containerLogs/<podNamespace>/<podID>/<containerName>
var podNamespace, podID, containerName string
if len(parts) == 5 {
podNamespace = parts[2]
podID = parts[3]
containerName = parts[4]
} else {
http.Error(w, "Unexpected path for command running", http.StatusBadRequest)
return
}
if len(podID) == 0 {
http.Error(w, `{"message": "Missing podID."}`, http.StatusBadRequest)
return
}
if len(containerName) == 0 {
http.Error(w, `{"message": "Missing container name."}`, http.StatusBadRequest)
return
}
if len(podNamespace) == 0 {
http.Error(w, `{"message": "Missing podNamespace."}`, http.StatusBadRequest)
return
}
2014-09-24 21:27:10 +00:00
uriValues := u.Query()
2014-09-15 16:20:01 +00:00
follow, _ := strconv.ParseBool(uriValues.Get("follow"))
tail := uriValues.Get("tail")
pod, ok := s.host.GetPodByName(podNamespace, podID)
if !ok {
http.Error(w, "Pod does not exist", http.StatusNotFound)
return
}
fw := FlushWriter{writer: w}
2014-10-20 23:41:23 +00:00
if flusher, ok := fw.writer.(http.Flusher); ok {
fw.flusher = flusher
2014-10-20 23:41:23 +00:00
} else {
s.error(w, fmt.Errorf("unable to convert %v into http.Flusher", fw))
}
w.Header().Set("Transfer-Encoding", "chunked")
w.WriteHeader(http.StatusOK)
err = s.host.GetKubeletContainerLogs(GetPodFullName(pod), containerName, tail, follow, &fw, &fw)
if err != nil {
s.error(w, err)
return
}
}
2014-10-22 23:52:38 +00:00
// handleBoundPods returns a list of pod bound to the Kubelet and their spec
func (s *Server) handleBoundPods(w http.ResponseWriter, req *http.Request) {
pods, err := s.host.GetBoundPods()
if err != nil {
s.error(w, err)
return
}
boundPods := &api.BoundPods{
Items: pods,
}
data, err := latest.Codec.Encode(boundPods)
if err != nil {
s.error(w, err)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-type", "application/json")
w.Write(data)
}
func (s *Server) handlePodInfoOld(w http.ResponseWriter, req *http.Request) {
s.handlePodInfo(w, req, false)
}
func (s *Server) handlePodInfoVersioned(w http.ResponseWriter, req *http.Request) {
s.handlePodInfo(w, req, true)
}
// handlePodInfo handles podInfo requests against the Kubelet
func (s *Server) handlePodInfo(w http.ResponseWriter, req *http.Request, versioned bool) {
2014-06-06 23:40:48 +00:00
u, err := url.ParseRequestURI(req.RequestURI)
if err != nil {
s.error(w, err)
return
}
2014-08-20 18:24:51 +00:00
podID := u.Query().Get("podID")
2015-01-14 23:22:21 +00:00
podUID := types.UID(u.Query().Get("UUID"))
podNamespace := u.Query().Get("podNamespace")
2014-08-20 18:24:51 +00:00
if len(podID) == 0 {
w.WriteHeader(http.StatusBadRequest)
http.Error(w, "Missing 'podID=' query entry.", http.StatusBadRequest)
return
}
if len(podNamespace) == 0 {
w.WriteHeader(http.StatusBadRequest)
http.Error(w, "Missing 'podNamespace=' query entry.", http.StatusBadRequest)
return
}
pod, ok := s.host.GetPodByName(podNamespace, podID)
if !ok {
http.Error(w, "Pod does not exist", http.StatusNotFound)
2014-08-20 18:24:51 +00:00
return
}
2015-01-14 21:53:43 +00:00
info, err := s.host.GetPodInfo(GetPodFullName(pod), podUID)
2014-08-20 18:24:51 +00:00
if err != nil {
s.error(w, err)
return
}
data, err := exportPodInfo(info, versioned)
2014-08-20 18:24:51 +00:00
if err != nil {
s.error(w, err)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-type", "application/json")
w.Write(data)
}
// handleStats handles stats requests against the Kubelet.
2014-08-20 18:24:51 +00:00
func (s *Server) handleStats(w http.ResponseWriter, req *http.Request) {
s.serveStats(w, req)
}
// handleLogs handles logs requests against the Kubelet.
2014-08-20 18:24:51 +00:00
func (s *Server) handleLogs(w http.ResponseWriter, req *http.Request) {
s.host.ServeLogs(w, req)
}
// handleSpec handles spec requests against the Kubelet.
2014-08-20 18:24:51 +00:00
func (s *Server) handleSpec(w http.ResponseWriter, req *http.Request) {
info, err := s.host.GetMachineInfo()
if err != nil {
s.error(w, err)
return
}
data, err := json.Marshal(info)
if err != nil {
s.error(w, err)
return
2014-06-06 23:40:48 +00:00
}
2014-08-20 18:24:51 +00:00
w.Header().Add("Content-type", "application/json")
w.Write(data)
}
// handleRun handles requests to run a command inside a container.
2014-08-26 19:57:44 +00:00
func (s *Server) handleRun(w http.ResponseWriter, req *http.Request) {
u, err := url.ParseRequestURI(req.RequestURI)
if err != nil {
s.error(w, err)
return
}
parts := strings.Split(u.Path, "/")
2015-01-14 21:53:43 +00:00
var podNamespace, podID, container string
2015-01-14 23:22:21 +00:00
var uid types.UID
if len(parts) == 5 {
podNamespace = parts[2]
podID = parts[3]
2014-09-05 09:49:11 +00:00
container = parts[4]
} else if len(parts) == 6 {
podNamespace = parts[2]
podID = parts[3]
2015-01-14 23:22:21 +00:00
uid = types.UID(parts[4])
container = parts[5]
2014-09-05 09:49:11 +00:00
} else {
2014-08-26 19:57:44 +00:00
http.Error(w, "Unexpected path for command running", http.StatusBadRequest)
return
}
pod, ok := s.host.GetPodByName(podNamespace, podID)
if !ok {
http.Error(w, "Pod does not exist", http.StatusNotFound)
return
}
2014-08-26 19:57:44 +00:00
command := strings.Split(u.Query().Get("cmd"), " ")
2015-01-14 21:53:43 +00:00
data, err := s.host.RunInContainer(GetPodFullName(pod), uid, container, command)
2014-08-26 19:57:44 +00:00
if err != nil {
s.error(w, err)
return
}
w.Header().Add("Content-type", "text/plain")
w.Write(data)
}
// ServeHTTP responds to HTTP requests on the Kubelet.
2014-08-20 18:24:51 +00:00
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer httplog.NewLogged(req, &w).StacktraceWhen(
2014-08-20 18:24:51 +00:00
httplog.StatusIsNot(
http.StatusOK,
http.StatusMovedPermanently,
http.StatusTemporaryRedirect,
2014-08-20 18:24:51 +00:00
http.StatusNotFound,
),
).Log()
s.mux.ServeHTTP(w, req)
2014-06-06 23:40:48 +00:00
}
2014-07-01 21:05:10 +00:00
// serveStats implements stats logic.
2014-07-15 13:54:23 +00:00
func (s *Server) serveStats(w http.ResponseWriter, req *http.Request) {
2015-01-14 21:53:43 +00:00
// /stats/<podfullname>/<containerName> or /stats/<namespace>/<podfullname>/<uid>/<containerName>
2014-07-01 21:05:10 +00:00
components := strings.Split(strings.TrimPrefix(path.Clean(req.URL.Path), "/"), "/")
var stats *info.ContainerInfo
2014-07-01 21:05:10 +00:00
var err error
var query info.ContainerInfoRequest
2014-07-15 22:40:02 +00:00
err = json.NewDecoder(req.Body).Decode(&query)
if err != nil && err != io.EOF {
s.error(w, err)
return
}
2014-07-01 21:05:10 +00:00
switch len(components) {
case 1:
// Machine stats
stats, err = s.host.GetRootInfo(&query)
2014-07-01 21:05:10 +00:00
case 2:
// pod stats
// TODO(monnand) Implement this
errors.New("pod level status currently unimplemented")
case 3:
2015-01-14 21:53:43 +00:00
// Backward compatibility without uid information, does not support namespace
pod, ok := s.host.GetPodByName(api.NamespaceDefault, components[1])
if !ok {
http.Error(w, "Pod does not exist", http.StatusNotFound)
return
}
stats, err = s.host.GetContainerInfo(GetPodFullName(pod), "", components[2], &query)
case 5:
pod, ok := s.host.GetPodByName(components[1], components[2])
if !ok {
http.Error(w, "Pod does not exist", http.StatusNotFound)
return
}
2015-01-14 23:22:21 +00:00
stats, err = s.host.GetContainerInfo(GetPodFullName(pod), types.UID(components[3]), components[4], &query)
2014-07-01 21:05:10 +00:00
default:
http.Error(w, "unknown resource.", http.StatusNotFound)
2014-07-01 21:05:10 +00:00
return
}
if err != nil {
s.error(w, err)
2014-07-01 21:05:10 +00:00
return
}
if stats == nil {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "{}")
return
}
data, err := json.Marshal(stats)
if err != nil {
s.error(w, err)
2014-07-01 21:05:10 +00:00
return
}
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-type", "application/json")
w.Write(data)
return
}
func exportPodInfo(info api.PodInfo, versioned bool) ([]byte, error) {
if versioned {
// TODO: support arbitrary versions here
codec, err := findCodec("v1beta1")
if err != nil {
return nil, err
}
return codec.Encode(&api.PodContainerInfo{ContainerInfo: info})
}
return json.Marshal(info)
}
func findCodec(version string) (runtime.Codec, error) {
versions, err := latest.InterfacesFor(version)
if err != nil {
return nil, err
}
return versions.Codec, nil
}