Skip to content

Instantly share code, notes, and snippets.

@ShawnMilo
Created Jul 26, 2017
Embed
What would you like to do?
kubernetes log combiner
package main
import (
"log"
"os"
"os/exec"
"strings"
"sync"
"time"
)
var names = make(map[string]struct{})
var nameLock sync.RWMutex
var label string
func init() {
label = os.Args[len(os.Args)-1]
}
func main() {
for {
pods := podNames()
if len(pods) == 0 {
log.Printf("No more pods. Quitting.\n")
return
}
for _, pod := range pods {
go watch(pod)
}
time.Sleep(time.Second * 30)
}
}
func podNames() []string {
cmd := exec.Command("kubectl", "get", "pods", "-o", "go-template={{ range .items }}{{ .metadata.name }} {{ end }}")
out, err := cmd.CombinedOutput()
if err != nil {
log.Fatalf("Failed to get pod names: %s\n", err)
}
pods := make([]string, 0, 3)
for _, pod := range strings.Fields(string(out)) {
if strings.Contains(pod, label) {
pods = append(pods, pod)
}
}
return pods
}
func watch(name string) {
if !claimName(name) {
return
}
defer releaseName(name)
log.Printf("Starting watch on %q\n", name)
var cmd *exec.Cmd
// get full history the first time only
cmd = exec.Command("kubectl", "logs", "-f", name)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
err := cmd.Run()
if err != nil {
log.Printf("Error reading log for pod %q: %s\n", name, err)
}
}
func claimName(name string) bool {
nameLock.Lock()
defer nameLock.Unlock()
if _, found := names[name]; found {
return false
}
names[name] = struct{}{}
return true
}
func releaseName(name string) {
nameLock.Lock()
delete(names, name)
nameLock.Unlock()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment