Skip to content

Instantly share code, notes, and snippets.

@resouer
Last active March 18, 2016 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save resouer/112448583601f452a80f to your computer and use it in GitHub Desktop.
Save resouer/112448583601f452a80f to your computer and use it in GitHub Desktop.
//A simplest case to call a independently running remote container runtime (e.g. sever.go).
func (r *runtime) GetContainerLogs(pod *api.Pod, containerID kubecontainer.ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) error {
args := &Args{Pod: pod, ContainerID: containerID, LogOptions: logOptions}
url := "http://localhost:1234/logs"
message, err := json.Marshal(args)
if err != nil {
log.Fatalf("Fail to marshal args %v", err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(message))
if err != nil {
log.Fatalf("%s", err)
}
req.Header.Set("Content-Type", "application/json")
client := new(http.Client)
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Error in sending request to %s. %s", url, err)
}
defer resp.Body.Close()
if stdout != nil {
io.Copy(stdout, resp.Body)
}
return nil
}
// server.go
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
"k8s.io/kubernetes/pkg/api"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/kubelet/hyper"
)
type Args struct {
Pod *api.Pod
ContainerID kubecontainer.ContainerID
LogOptions *api.PodLogOptions
}
// A simplest http server to serve GetContainerLogs request.
func main() {
router := mux.NewRouter()
router.HandleFunc("/logs", HandleContainerLogs).Methods("POST")
http.ListenAndServe(":1234", router)
}
func HandleContainerLogs(res http.ResponseWriter, req *http.Request) {
var args Args
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&args)
if err != nil {
log.Fatal("Fail to decode request body: %v", err)
}
containerID := args.ContainerID
logOptions := args.LogOptions
hyperClient := hyper.NewHyperClient()
var tailLines, since int64
if logOptions.SinceSeconds != nil && *logOptions.SinceSeconds != 0 {
since = *logOptions.SinceSeconds
}
if logOptions.TailLines != nil && *logOptions.TailLines != 0 {
tailLines = *logOptions.TailLines
}
opts := hyper.ContainerLogsOptions{
Container: containerID.ID,
OutputStream: res,
ErrorStream: os.Stderr,
Follow: logOptions.Follow,
Timestamps: logOptions.Timestamps,
Since: since,
TailLines: tailLines,
}
hyperClient.ContainerLogs(opts)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment