1
0
Fork 0
httpprocprobed/main.go

107 lines
2.6 KiB
Go

package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
)
var configPath *string = flag.String("c", "config.conf", "path to configuration file")
var showVersion *bool = flag.Bool("v", false, "show version")
var listProcesses *bool = flag.Bool("l", false, "list watched processes")
var addProcess *string = flag.String("a", "", "add process to list")
var removeProcess *string = flag.String("r", "", "remove process from list")
func main() {
log.SetFlags(0)
flag.Parse()
if *showVersion {
fmt.Println("httpprocprobed ver. 2.0.1")
fmt.Println("Copyright (c) 2021-2023 Alexander \"Arav\" Andreev <me@arav.top>")
fmt.Println("This program is licensed under terms of MIT+NIGGER license.")
os.Exit(0)
}
conf, err := LoadConfiguration(*configPath)
if err != nil {
log.Fatalf("[ERR] Cannot load configuration file: %s\n", err)
}
if *listProcesses {
for _, v := range conf.Processes {
fmt.Printf("%s, ", v)
}
fmt.Println()
os.Exit(0)
}
if *addProcess != "" {
err := conf.AddProcess(*addProcess, *configPath)
if err != nil {
log.Fatalf("[ERR] Cannot add process: %s\n", err)
}
}
if *removeProcess != "" {
err := conf.RemoveProcess(*removeProcess, *configPath)
if err != nil {
log.Fatalf("[ERR] Cannot remove process: %s\n", err)
}
}
// If we modified a list then let's look for a running program and
// send SIGHUP to it to reload a list. Here we assume that there
// is only one process running, so we just filter our PID.
if *addProcess != "" || *removeProcess != "" {
if err := conf.StoreConfiguration(*configPath); err != nil {
log.Fatalf("[ERR] Cannot write configuration. Error: %s\n", err)
}
pids, _ := GetProcessPIDs("httpprocprobed")
if len(pids) > 1 {
var trgt_pid int
if pids[0] == os.Getpid() {
trgt_pid = pids[1]
} else {
trgt_pid = pids[0]
}
if proc, err := os.FindProcess(trgt_pid); err == nil {
proc.Signal(syscall.SIGHUP)
}
}
os.Exit(0)
}
srv := CreateAndStartHTTPServer(conf)
syssignal := make(chan os.Signal, 1)
signal.Notify(syssignal, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
log.Printf("httpprocprobed is running on \"%s\".", conf.ListenAddress)
for {
switch <-syssignal {
case os.Interrupt:
fallthrough
case syscall.SIGINT | syscall.SIGTERM:
ShutdownHTTPServer(srv)
log.Println("Server shutted down.")
os.Exit(0)
case syscall.SIGHUP:
newconf, err := LoadConfiguration(*configPath)
if err != nil {
log.Fatalf("Failed to reload a list of processes from configuration: %s\n", err)
}
conf.Processes = newconf.Processes
log.Println("Successfully reloaded a list of watched processes.")
}
}
}