Use mux to handle req; get tail from req

This commit is contained in:
Rita Zhang
2017-12-21 21:42:05 -08:00
parent 04db926faa
commit 43137d09f7
6 changed files with 52 additions and 24 deletions

View File

@@ -6,40 +6,64 @@ import (
"log"
"net/http"
"os"
"strings"
"strconv"
"github.com/gorilla/mux"
)
var p Provider
var r mux.Router
func NotFound(w http.ResponseWriter, r *http.Request) {
log.Println("404 request not found")
http.Error(w, "404 request not found", http.StatusNotFound)
}
func ApiserverStart(provider Provider) {
p = provider
http.HandleFunc("/", ApiServerHandler)
certFilePath := os.Getenv("APISERVER_CERT_LOCATION")
keyFilePath := os.Getenv("APISERVER_KEY_LOCATION")
port := os.Getenv("KUBELET_PORT")
addr := fmt.Sprintf(":%s", port)
err := http.ListenAndServeTLS(addr, certFilePath, keyFilePath, nil)
r := mux.NewRouter()
r.HandleFunc("/containerLogs/{namespace}/{pod}/{container}", ApiServerHandler).Methods("GET")
r.NotFoundHandler = http.HandlerFunc(NotFound)
err := http.ListenAndServeTLS(addr, certFilePath, keyFilePath, r)
if err != nil {
log.Println(err)
}
}
func ApiServerHandler(w http.ResponseWriter, req *http.Request) {
if req.Method == "GET" {
if strings.ContainsAny(req.RequestURI, "containerLogs" ) {
reqParts := strings.Split(req.RequestURI, "/")
if len(reqParts) == 5 {
namespace := reqParts[2]
pod := reqParts[3]
container := reqParts[4]
podsLogs, err := p.GetContainerLogs(namespace, pod, container)
if err != nil {
io.WriteString(w, err.Error())
log.Println(err)
} else {
io.WriteString(w, podsLogs)
}
vars := mux.Vars(req)
if len(vars) == 3 {
namespace := vars["namespace"]
pod := vars["pod"]
container := vars["container"]
tail := 10
q := req.URL.Query()
queryTail := q.Get("tailLines")
if queryTail != "" {
t, err := strconv.Atoi(queryTail)
if err != nil {
log.Println(err)
io.WriteString(w, err.Error())
} else {
tail = t
}
}
log.Println(tail)
podsLogs, err := p.GetContainerLogs(namespace, pod, container, tail)
if err != nil {
log.Println(err)
io.WriteString(w, err.Error())
} else {
io.WriteString(w, podsLogs)
}
} else {
log.Println("404 request pattern not found")
NotFound(w, req)
}
}
}

View File

@@ -25,7 +25,7 @@ type Provider interface {
GetPod(namespace, name string) (*v1.Pod, error)
// GetContainerLogs retrieves the logs of a container by name from the provider.
GetContainerLogs(namespace, podName, containerName string) (string, error)
GetContainerLogs(namespace, podName, containerName string, tail int) (string, error)
// GetPodStatus retrieves the status of a pod by name from the provider.
GetPodStatus(namespace, name string) (*v1.PodStatus, error)