Created
July 26, 2017 23:22
-
-
Save ShawnMilo/5afd59d1ddcb56e98e1222458f119506 to your computer and use it in GitHub Desktop.
kubernetes log combiner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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