Add proxy

This commit is contained in:
Simon Larsen
2025-01-03 14:21:47 +00:00
parent a0c0041cbd
commit fe9d3d3020
3 changed files with 49 additions and 16 deletions

View File

@@ -6,6 +6,7 @@ import (
"io"
"log/slog"
"net/http"
"net/url"
"oneuptime-infrastructure-agent/model"
"oneuptime-infrastructure-agent/utils"
"os"
@@ -18,22 +19,24 @@ import (
type Agent struct {
SecretKey string
OneUptimeURL string
ProxyURL string
scheduler gocron.Scheduler
mainJob gocron.Job
shutdownHook Hook
}
func NewAgent(secretKey string, url string) *Agent {
func NewAgent(secretKey string, oneuptimeUrl string, proxyUrl string) *Agent {
ag := &Agent{
SecretKey: secretKey,
OneUptimeURL: url,
OneUptimeURL: oneuptimeUrl,
ProxyURL: proxyUrl,
}
slog.Info("Starting agent...")
slog.Info("Agent configuration:")
slog.Info("Secret key: " + ag.SecretKey)
slog.Info("OneUptime URL: " + ag.OneUptimeURL)
slog.Info("Proxy URL: " + ag.ProxyURL)
if ag.SecretKey == "" || ag.OneUptimeURL == "" {
slog.Error("Secret key and OneUptime URL are required")
os.Exit(1)
@@ -41,7 +44,7 @@ func NewAgent(secretKey string, url string) *Agent {
}
// check if secret key is valid
if !checkIfSecretKeyIsValid(ag.SecretKey, ag.OneUptimeURL) {
if !checkIfSecretKeyIsValid(ag.SecretKey, ag.OneUptimeURL, ag.ProxyURL) {
slog.Error("Secret key is invalid")
os.Exit(1)
return ag
@@ -84,7 +87,7 @@ func (ag *Agent) Close() {
}
}
func collectMetricsJob(secretKey string, oneuptimeURL string) {
func collectMetricsJob(secretKey string, oneuptimeUrl string, proxyUrl string) {
memMetrics := utils.GetMemoryMetrics()
if memMetrics == nil {
slog.Warn("Failed to get memory metrics")
@@ -129,7 +132,7 @@ func collectMetricsJob(secretKey string, oneuptimeURL string) {
return
}
req, err := http.NewRequest(http.MethodPost, oneuptimeURL+"/server-monitor/response/ingest/"+secretKey, bytes.NewBuffer(reqBody))
req, err := http.NewRequest(http.MethodPost, oneuptimeUrl+"/server-monitor/response/ingest/"+secretKey, bytes.NewBuffer(reqBody))
if err != nil {
slog.Error("Failed to create request: ", err)
return
@@ -153,18 +156,29 @@ func collectMetricsJob(secretKey string, oneuptimeURL string) {
slog.Info("1 minute metrics have been sent to OneUptime.")
}
func checkIfSecretKeyIsValid(secretKey string, baseUrl string) bool {
func checkIfSecretKeyIsValid(secretKey string, oneuptimeUrl string, proxyUrl string) bool {
// if we have a proxy, we need to use that to make the request
client := &http.Client{}
if proxyUrl != "" {
proxyURL, _ := url.Parse("http://your-proxy-server:port")
transport := &http.Transport{Proxy: http.ProxyURL(proxyURL)}
client = &http.Client{Transport: transport}
}
if secretKey == "" {
slog.Error("Secret key is empty")
return false
}
resp, err := http.NewRequest(http.MethodGet, baseUrl+"/server-monitor/secret-key/verify/"+secretKey, nil)
resp, err := client.Get(oneuptimeUrl + "/server-monitor/secret-key/verify/" + secretKey)
if err != nil {
slog.Error(err.Error())
return false
}
if resp.Response.StatusCode != 200 {
slog.Error("Secret key verification failed with status code " + strconv.Itoa(resp.Response.StatusCode))
if resp.StatusCode != 200 {
slog.Error("Secret key verification failed with status code " + strconv.Itoa(resp.StatusCode))
return false
}
return true

View File

@@ -12,8 +12,12 @@ import (
)
type ConfigFile struct {
SecretKey string `json:"secret_key"`
OneUptimeURL string `json:"oneuptime_url"`
SecretKey string `json:"secret_key"`
OneUptimeURL string `json:"oneuptime_url"`
ProxyURL string `json:"proxy_url"`
ProxyPort string `json:"proxy_port"`
ProxyUsername string `json:"proxy_username"`
ProxyPassword string `json:"proxy_password"`
}
func newConfigFile() *ConfigFile {
@@ -38,7 +42,7 @@ func (c *ConfigFile) loadConfig() error {
return nil
}
func (c *ConfigFile) save(secretKey string, url string) error {
func (c *ConfigFile) save(secretKey string, oneuptimeUrl string, proxyUrl string) error {
err := c.loadConfig()
if err != nil && !os.IsNotExist(err) {
return err
@@ -47,10 +51,16 @@ func (c *ConfigFile) save(secretKey string, url string) error {
if err != nil {
return err
}
err = config.Set("oneuptime_url", url)
err = config.Set("oneuptime_url", oneuptimeUrl)
if err != nil {
return err
}
err = config.Set("proxy_url", proxyUrl)
if err != nil {
return err
}
// Open the file with os.Create, which truncates the file if it already exists,
// and creates it if it doesn't.
file, err := os.Create(c.configPath())

View File

@@ -44,7 +44,7 @@ func SetDefaultLogger() {
}
func (p *program) run() {
p.agent = NewAgent(p.config.SecretKey, p.config.OneUptimeURL)
p.agent = NewAgent(p.config.SecretKey, p.config.OneUptimeURL, p.config.ProxyURL)
p.agent.Start()
if service.Interactive() {
slog.Info("Running in terminal.")
@@ -112,19 +112,28 @@ func main() {
installFlags := flag.NewFlagSet("configure", flag.ExitOnError)
secretKey := installFlags.String("secret-key", "", "Secret key (required)")
oneuptimeURL := installFlags.String("oneuptime-url", "", "Oneuptime endpoint root URL (required)")
// Take input - proxy URL, proxy port, username / password - all optional
proxyURL := installFlags.String("proxy-url", "", "Proxy URL - if you are using a proxy (optional)")
err := installFlags.Parse(os.Args[2:])
if err != nil {
slog.Error(err.Error())
os.Exit(2)
}
prg.config.SecretKey = *secretKey
prg.config.OneUptimeURL = *oneuptimeURL
prg.config.ProxyURL = *proxyURL
if prg.config.SecretKey == "" || prg.config.OneUptimeURL == "" {
slog.Error("The --secret-key and --oneuptime-url flags are required for the 'configure' command")
os.Exit(2)
}
// save configuration
err = prg.config.save(prg.config.SecretKey, prg.config.OneUptimeURL)
err = prg.config.save(prg.config.SecretKey, prg.config.OneUptimeURL, prg.config.ProxyURL)
if err != nil {
slog.Error(err.Error())
os.Exit(2)