// Copyright 2023 wanderer // SPDX-License-Identifier: AGPL-3.0-only package main import ( "context" "flag" "fmt" "net/http" "os" "os/signal" "strconv" "syscall" "time" "golang.org/x/exp/slog" // pure go postgres driver. _ "github.com/lib/pq" // ent pure go sqlite3 driver instead of "github.com/mattn/go-sqlite3". _ "github.com/xiaoqidun/entps" "git.dotya.ml/mirre-mt/pcmt/app" "git.dotya.ml/mirre-mt/pcmt/app/settings" "git.dotya.ml/mirre-mt/pcmt/config" "git.dotya.ml/mirre-mt/pcmt/ent" moddb "git.dotya.ml/mirre-mt/pcmt/modules/db" "git.dotya.ml/mirre-mt/pcmt/slogging" ) const ( banner = ` ██████╗ ██████╗███╗ ███╗████████╗ ██╔══██╗██╔════╝████╗ ████║╚══██╔══╝ ██████╔╝██║ ██╔████╔██║ ██║ ██╔═══╝ ██║ ██║╚██╔╝██║ ██║ ██║ ╚██████╗██║ ╚═╝ ██║ ██║ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ` slug = `Password Compromise Monitoring Tool version: '%s' https://git.dotya.ml/mirre-mt/pcmt ____________________________________` licenseHeader = `pcmt - Password Compromise Monitoring Tool Copyright (C) git.dotya.ml/wanderer This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see .` ) var ( host = flag.String("host", "unset", "host address to listen on") port = flag.Int("port", 0, "TCP port to listen on") configFlag = flag.String("config", "config.dhall", "Default path of the config file") configIsPathFlag = flag.Bool("configIsPath", true, "Whether the provided config is path or raw config") devel = flag.Bool("devel", false, "Run the application in dev mode, connect to a local browser-sync instance for hot-reloading") license = flag.Bool("license", false, "Print licensing information and exit") versionFlag = flag.Bool("version", false, "Print version and exit") importFlag = flag.String("import", "", "Path to import breach data from") version = "dev" // the global logger. slogger *slogging.Slogger // local logger instance. log slogging.Slogger ) func run() error { //nolint:gocognit flag.Parse() if *license { fmt.Fprintln(os.Stderr, licenseHeader) return nil } if *versionFlag { fmt.Fprintf(os.Stderr, "pcmt version %s\n", version) return nil } var doingImport bool if importFlag != nil && *importFlag != "" { doingImport = true } if !doingImport { printHeader() } slogger = slogging.Logger() if slogger == nil { slogger = slogging.Init(true) } log = *slogger // local copy. log.Logger = log.Logger.With( // local attrs. slog.Group("pcmt extra", slog.String("module", "run")), ) // TODO: allow different configuration formats (toml, ini) // TODO: rename main.go to pcmt.go // TODO: add flake.nix // TODO: SBOM: https://actuated.dev/blog/sbom-in-github-actions // TODO: SBOM: https://www.docker.com/blog/generate-sboms-with-buildkit/ // TODO: integrate with Graylog (https://github.com/samber/slog-graylog). // TODO: add mailer (https://github.com/wneessen/go-mail). // TODO: deploy containers with podman using Ansible (https://www.redhat.com/sysadmin/automate-podman-ansible) // TODO: add health checks for pod's containers (db, app) conf, err := config.Load(*configFlag, *configIsPathFlag) if err != nil { return fmt.Errorf("couldn't load the configuration (isPath: '%t') '%s', full err: %w", *configIsPathFlag, *configFlag, err, ) } setting := settings.New() setting.Consolidate( conf, host, port, devel, version, ) // expected connstring form for "github.com/xiaoqidun/entps": // "file:ent?mode=memory&cache=shared&_fk=1" // and for the postgres driver "github.com/lib/pq": // "host=127.0.0.1 sslmode=disable port=5432 user=postgres dbname=postgres password=postgres". connstr := os.Getenv("PCMT_CONNSTRING") dbtype := os.Getenv("PCMT_DBTYPE") // check and bail early. switch { case connstr == "" || dbtype == "": log.Errorf("PCMT_CONNSTRING or PCMT_DBTYPE or *both* were UNSET, bailing...") return errDBNotConfigured case dbtype != "postgres" && dbtype != "sqlite3": log.Errorf("unsupported DB type specified, bailing...") return errUnsupportedDBType default: setting.SetDbConnstring(connstr) // type can be one of "postgres" or "sqlite3". setting.SetDbType(dbtype) } log.Infof("connecting to db at '%s'", connstr) db, err := ent.Open(setting.DbType(), setting.DbConnstring()) if err != nil { if doingImport { log.Error("import not possible") } return fmt.Errorf("failed to open a connection to database: %v", err) } defer db.Close() ctx := context.WithValue(context.Background(), moddb.CtxKey{}, slogger) log.Info("ensuring the db is set up and attempting to automatically migrate db schema") // make sure the database is set up and optionally creates an administrator // user (only when setting up the db). if err = moddb.SetUp(ctx, db, setting.InitCreateAdmin(), setting.InitAdminPassword()); err != nil { return err } setting.SetDbIsSetUp(true) a := &app.App{} if err = a.Init(setting, slogger, db); err != nil { return err } a.PrintConfiguration() a.SetEmbeds(templates, assets) if err = a.SetupRoutes(); err != nil { return err } a.SetEchoSettings() if err = setting.EraseENVs(); err != nil { log.Error("failed to erase PCMT ENVs") return err } log.Debug("erased PCMT ENVs") e := a.E() // channel used to check whether the app had troubles starting up. started := make(chan error, 1) defer close(started) go func(ok chan error) { p := setting.Port() h := setting.Host() address := h + ":" + strconv.Itoa(p) if err := e.Start(address); err != nil && err != http.ErrServerClosed { log.Error("troubles running the server, bailing...", "error", err) ok <- err return } ok <- nil }(started) quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt) signal.Notify(quit, syscall.SIGTERM) signal.Notify(quit, syscall.SIGHUP) // non-blocking channel receive. select { case err := <-started: if err != nil { return err } case <-quit: shutdownTimeout := 10 * time.Second ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) defer func() { log.Infof("Interrupt received, gracefully shutting down the server (timeout %s)", shutdownTimeout) cancel() signal.Stop(quit) close(quit) log.Info("Bye!") }() if err = e.Shutdown(ctx); err != nil { log.Error("There was an error shutting the server down") return err } } return nil } func printHeader() { slug := fmt.Sprintf(slug, version) fmt.Fprintf(os.Stderr, "\033[34m%s%s\033[0m\n\n\n", banner, slug, ) }