Oculus/main.go

248 lines
6.8 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
)
const (
notifyScript = "/notify.sh"
logDir = "/log"
)
// ContainerDiff represents the state of a container
type ContainerDiff struct {
ID string
Image string
Labels map[string]string
}
// getRunningContainers fetches the list of running containers with relevant labels
func getRunningContainers(cli *client.Client) ([]ContainerDiff, error) {
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
if err != nil {
return nil, err
}
var diffs []ContainerDiff
for _, container := range containers {
if _, ok := container.Labels["oculus.containerid"]; ok {
diffs = append(diffs, ContainerDiff{
ID: container.ID,
Image: container.Image,
Labels: container.Labels,
})
}
}
return diffs, nil
}
// saveDiffs writes the container diffs to a file
func saveDiffs(diffs []ContainerDiff, filePath string) error {
data, err := json.Marshal(diffs)
if err != nil {
return err
}
return ioutil.WriteFile(filePath, data, 0644)
}
// loadDiffs reads the container diffs from a file
func loadDiffs(filePath string) ([]ContainerDiff, error) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
var diffs []ContainerDiff
err = json.Unmarshal(data, &diffs)
return diffs, err
}
// shouldIgnore checks if the change should be ignored based on the ignore list
func shouldIgnore(change string, ignoreList []string) bool {
for _, ignore := range ignoreList {
if strings.Contains(change, ignore) {
return true
}
}
return false
}
// logDetection logs detection events to a file and sends to Go Glitch
func logDetection(containerID, message string) {
logFilePath := filepath.Join(logDir, fmt.Sprintf("%s.log", containerID))
f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Printf("Error opening log file: %v", err)
return
}
defer f.Close()
log.SetOutput(f)
log.Println(message)
sendToGlitchtip(logFilePath)
}
// sendToGlitchtip sends the log file content to Go Glitch
func sendToGlitchtip(logFilePath string) {
if dsn := os.Getenv("GLITCHTIP_DSN"); dsn != "" {
cmd := exec.Command("go-glitch", logFilePath)
err := cmd.Run()
if err != nil {
log.Printf("Error sending to Go Glitch: %v", err)
}
}
}
// profileContainers logs the current state of containers to a file
func profileContainers(cli *client.Client) {
diffs, err := getRunningContainers(cli)
if err != nil {
log.Fatalf("Error profiling containers: %v", err)
}
for _, diff := range diffs {
if diff.Labels["oculus.mode"] == "profile" {
filePath := fmt.Sprintf("%s.json", diff.Labels["oculus.containerid"])
err := saveDiffs([]ContainerDiff{diff}, filePath)
if err != nil {
log.Fatalf("Error saving diffs: %v", err)
}
}
}
log.Println("Profiled current containers and saved to file")
}
// compareContainers compares the current state of containers with the saved state
func compareContainers(cli *client.Client) {
currentDiffs, err := getRunningContainers(cli)
if err != nil {
log.Fatalf("Error getting current containers: %v", err)
}
for _, current := range currentDiffs {
if current.Labels["oculus.mode"] == "monitor" {
filePath := fmt.Sprintf("%s.json", current.Labels["oculus.containerid"])
savedDiffs, err := loadDiffs(filePath)
if err != nil {
log.Printf("Error loading saved diffs for %s: %v", current.ID, err)
continue
}
ignoreList := strings.Split(current.Labels["oculus.ignorelist"], ",")
if len(savedDiffs) > 0 {
saved := savedDiffs[0]
if current.Image != saved.Image && !shouldIgnore(current.Image, ignoreList) {
message := fmt.Sprintf("Container %s changed: Image %s -> %s", current.ID, saved.Image, current.Image)
logDetection(current.Labels["oculus.containerid"], message)
runNotifyScript(filepath.Join(logDir, fmt.Sprintf("%s.log", current.Labels["oculus.containerid"])))
}
if current.Labels["oculus.ignorelist"] != saved.Labels["oculus.ignorelist"] {
message := fmt.Sprintf("Container %s ignore list changed: %s -> %s", current.ID, saved.Labels["oculus.ignorelist"], current.Labels["oculus.ignorelist"])
if !shouldIgnore(message, ignoreList) {
logDetection(current.Labels["oculus.containerid"], message)
runNotifyScript(filepath.Join(logDir, fmt.Sprintf("%s.log", current.Labels["oculus.containerid"])))
}
}
} else {
message := fmt.Sprintf("New container detected: ID %s, Image %s", current.ID, current.Image)
if !shouldIgnore(current.Image, ignoreList) {
logDetection(current.Labels["oculus.containerid"], message)
runNotifyScript(filepath.Join(logDir, fmt.Sprintf("%s.log", current.Labels["oculus.containerid"])))
}
}
}
}
}
// runNotifyScript executes the notification script with the container details
func runNotifyScript(logFilePath string) {
cmd := exec.Command(notifyScript, logFilePath)
err := cmd.Run()
if err != nil {
log.Printf("Error running notify script: %v", err)
}
}
// watchDockerEvents listens for Docker events and triggers comparisons
func watchDockerEvents(cli *client.Client) {
eventFilter := filters.NewArgs()
eventFilter.Add("type", "container")
eventFilter.Add("event", "start")
eventFilter.Add("event", "stop")
eventFilter.Add("event", "destroy")
messages, errs := cli.Events(context.Background(), types.EventsOptions{
Filters: eventFilter,
})
for {
select {
case event := <-messages:
log.Printf("Docker event received: %s for container %s", event.Action, event.ID)
compareContainers(cli)
case err := <-errs:
log.Printf("Error watching Docker events: %v", err)
return
}
}
}
// monitorContainers sets up monitoring for containers based on the specified interval
func monitorContainers(cli *client.Client, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
compareContainers(cli)
}
}
}
func main() {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
log.Fatalf("Error creating Docker client: %v", err)
}
go watchDockerEvents(cli)
// Get running containers and set up monitoring intervals
containers, err := getRunningContainers(cli)
if err != nil {
log.Fatalf("Error getting running containers: %v", err)
}
for _, container := range containers {
if container.Labels["oculus.mode"] == "monitor" {
intervalStr := container.Labels["oculus.interval"]
interval, err := time.ParseDuration(intervalStr)
if err != nil {
log.Fatalf("Invalid interval format for container %s: %v", container.ID, err)
}
go monitorContainers(cli, interval)
}
}
// Keep the program running
select {}
}