82 lines
2.3 KiB
Go
82 lines
2.3 KiB
Go
package application
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/gorilla/mux"
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
log "github.com/sirupsen/logrus"
|
|
"gopkg.in/yaml.v2"
|
|
"lostak.dev/pve-exporter/configuration"
|
|
"lostak.dev/pve-exporter/metrics"
|
|
"lostak.dev/pve-exporter/proxmox"
|
|
)
|
|
|
|
// Application context.
|
|
type Application struct {
|
|
Configuration *configuration.Configuration // Application configuration.
|
|
Router *mux.Router // Gorilla MUX router instance.
|
|
Server *http.Server // HTTP server instance.
|
|
MetricsManager *metrics.PveMetricsManager // PVE metrics manager.
|
|
PveApiClient *proxmox.PveApiClient // PVE API client instance.
|
|
}
|
|
|
|
// Create new instance of the PVE exporter.
|
|
func NewApplication(configPath string) *Application {
|
|
app := Application{}
|
|
app.Router = mux.NewRouter()
|
|
|
|
// Load configuration file.
|
|
file, err := os.ReadFile(configPath)
|
|
if err != nil {
|
|
log.Panicf("Can't open config.yaml. Error: %s.", err)
|
|
}
|
|
|
|
// Unmarshal configuration file.
|
|
if err := yaml.Unmarshal(file, &app.Configuration); err != nil {
|
|
log.Panicf("Can't parse config.yaml. Error: %s.", err)
|
|
}
|
|
|
|
// Validate configuration file.
|
|
err = app.Configuration.Validate()
|
|
if err != nil {
|
|
log.Fatalf("Configuration error: %s", err)
|
|
}
|
|
|
|
// Set log level.
|
|
log.SetLevel(log.AllLevels[app.Configuration.LogLevel])
|
|
|
|
// Create proxmox API client instance.
|
|
pvec := app.Configuration.PVE
|
|
app.PveApiClient = proxmox.NewPveApiClient(pvec.Hosts, pvec.Token.TokenId, pvec.Token.Secret)
|
|
|
|
// Create metrics collector.
|
|
app.MetricsManager = metrics.NewPveMetricsManager(app.PveApiClient, &app.Configuration.PVE)
|
|
|
|
return &app
|
|
}
|
|
|
|
// Initialize application internals such as HTTP server, router, PVE metrics scraper.
|
|
func (app *Application) Start() {
|
|
// Prepare web server.
|
|
hostaddr := fmt.Sprintf("%s:%d", app.Configuration.Host, app.Configuration.Port)
|
|
app.Server = &http.Server{
|
|
Handler: app.Router,
|
|
Addr: hostaddr,
|
|
WriteTimeout: 15 * time.Second,
|
|
ReadTimeout: 15 * time.Second,
|
|
}
|
|
|
|
// Prepare metrics handler
|
|
app.Router.Handle("/metrics", promhttp.Handler())
|
|
|
|
// Start the metrics manager.
|
|
app.MetricsManager.Start()
|
|
|
|
log.Infof("Proxmox exporter started on %s.", hostaddr)
|
|
log.Fatal(app.Server.ListenAndServe())
|
|
}
|