feat: ship backend logs to OmniLogger
Lint / Lint (push) Successful in 1m12s
Security / Secrets (gitleaks) (push) Successful in 59s
Security / Dependencies (Trivy) (push) Successful in 49s
Tests / Dashboard checks (push) Successful in 52s
Security / Code (Semgrep) (push) Successful in 1m33s
Tests / Go backend (push) Failing after 1m1s
Docker / Docker Build & Push (push) Failing after 5m16s
Lint / Lint (push) Successful in 1m12s
Security / Secrets (gitleaks) (push) Successful in 59s
Security / Dependencies (Trivy) (push) Successful in 49s
Tests / Dashboard checks (push) Successful in 52s
Security / Code (Semgrep) (push) Successful in 1m33s
Tests / Go backend (push) Failing after 1m1s
Docker / Docker Build & Push (push) Failing after 5m16s
This commit is contained in:
1 parent
ed3544acfe
commit
01b18be1e4
8 files changed
+320
-29
No files matched your search
@@ -58,6 +58,8 @@ The device-sync API token (generated from the dashboard's Settings page, used by
|
|||||||
| `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. |
|
| `PRODUCTION` | No | `false` | Set `true` to refuse plain HTTP: requests must arrive over TLS or through a `TRUSTED_PROXIES` proxy sending `X-Forwarded-Proto: https`. Requires `TRUSTED_PROXIES`. With `false`, the server logs a warning that TLS is off. |
|
||||||
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
| `DB_INIT_RETRY_INTERVAL_MS` | No | `5000` | Delay between database-connection retry attempts at startup |
|
||||||
| `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup |
|
| `DB_INIT_RETRY_MAX_ATTEMPTS` | No | `0` (retry forever) | Max database-connection retry attempts at startup |
|
||||||
|
| `OMNILOGGER_URL` | No | unset | Optional initial base URL of the OmniLogger log sink. Server log lines are also sent there when it and `OMNILOGGER_INGEST_TOKEN` are both set; console output is unchanged. ProjectConfigurator's push can supply or replace it at runtime. The `remap-users` command is not shipped. |
|
||||||
|
| `OMNILOGGER_INGEST_TOKEN` | No | unset | Optional initial ingest token for this service (`collabtable`). ProjectConfigurator normally supplies the token at runtime through its core-services push, which also starts shipping. Shipping stays off until both a URL and a token are known. |
|
||||||
| `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops |
|
| `SYNC_MAX_FUTURE_SKEW_MS` | No | `0` | Client clock skew tolerated in sync timestamps, to avoid re-sending future-dated rows in hot loops |
|
||||||
| `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup |
|
| `NOTIF_RETENTION_MS` | No | `604800000` (7 days) | How long sync notifications are retained before cleanup |
|
||||||
|
|
||||||
|
|||||||
@@ -78,3 +78,8 @@ NOTIF_RETENTION_MS=604800000
|
|||||||
SECRET=change-me-to-a-long-random-value
|
SECRET=change-me-to-a-long-random-value
|
||||||
# Set true only for local development or a standalone deployment.
|
# Set true only for local development or a standalone deployment.
|
||||||
AUTH_DISABLED=false
|
AUTH_DISABLED=false
|
||||||
|
|
||||||
|
# Optional initial values for shipping server log lines to OmniLogger. Shipping runs only when both are set.
|
||||||
|
# ProjectConfigurator normally supplies the ingest token at runtime, so these can stay empty.
|
||||||
|
OMNILOGGER_URL=
|
||||||
|
OMNILOGGER_INGEST_TOKEN=
|
||||||
+3
-2
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -314,7 +315,7 @@ func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
||||||
fmt.Printf("[db] session prune failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[db] session prune failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -334,7 +335,7 @@ func (d *DB) cleanupNotifications(ctx context.Context) {
|
|||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
cutoff := time.Now().UnixMilli() - retention
|
cutoff := time.Now().UnixMilli() - retention
|
||||||
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
||||||
fmt.Printf("[db] notification cleanup failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[db] notification cleanup failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import (
|
|||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
)
|
)
|
||||||
|
|
||||||
type queryExecutor interface {
|
type queryExecutor interface {
|
||||||
@@ -79,6 +81,6 @@ func ignoreNotificationError(err error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
// Notifications are an acceleration path for clients that poll. A failed
|
// Notifications are an acceleration path for clients that poll. A failed
|
||||||
// notification must never roll back the data mutation that produced it.
|
// notification must never roll back the data mutation that produced it.
|
||||||
fmt.Printf("[notifications] enqueue failed: %v\n", err)
|
logPrintf(logshipper.LevelWarn, "[notifications] enqueue failed: %v\n", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
|
)
|
||||||
|
|
||||||
|
// omniShipper mirrors the server's console lines to OmniLogger. It is always set: with no OMNILOGGER_URL or
|
||||||
|
// OMNILOGGER_INGEST_TOKEN it is disabled and ships nothing, until main hands it ProjectConfigurator's
|
||||||
|
// pushed token (see omniShipper.Follow in server.go).
|
||||||
|
var omniShipper = newOmniLoggerShipper()
|
||||||
|
|
||||||
|
// newOmniLoggerShipper returns a shipper for OmniLogger. OMNILOGGER_URL and OMNILOGGER_INGEST_TOKEN are
|
||||||
|
// optional initial values; ProjectConfigurator normally supplies the token at runtime.
|
||||||
|
func newOmniLoggerShipper() *logshipper.Shipper {
|
||||||
|
return logshipper.New(logshipper.Config{
|
||||||
|
BaseURL: strings.TrimSpace(os.Getenv("OMNILOGGER_URL")),
|
||||||
|
IngestToken: strings.TrimSpace(os.Getenv("OMNILOGGER_INGEST_TOKEN")),
|
||||||
|
Service: "collabtable",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// stdoutLog and stderrLog are the Loggers behind the helpers below. Each writes its line to its console stream
|
||||||
|
// exactly as the fmt function it replaced did, and ships the line to OmniLogger at the severity the caller names.
|
||||||
|
var (
|
||||||
|
stdoutLog = newConsoleLogger(os.Stdout, omniShipper)
|
||||||
|
stderrLog = newConsoleLogger(os.Stderr, omniShipper)
|
||||||
|
)
|
||||||
|
|
||||||
|
// newConsoleLogger returns a Logger for console. NewLogger copies the standard logger's flags, and these helper
|
||||||
|
// lines have never carried a timestamp, so the flags are cleared only while the Logger is made. The standard
|
||||||
|
// logger keeps its own flags.
|
||||||
|
func newConsoleLogger(console io.Writer, shipper *logshipper.Shipper) *logshipper.Logger {
|
||||||
|
previous := log.Flags()
|
||||||
|
log.SetFlags(0)
|
||||||
|
defer log.SetFlags(previous)
|
||||||
|
return logshipper.NewLogger(console, shipper)
|
||||||
|
}
|
||||||
|
|
||||||
|
// logPrintf, logPrintln, logErrorf and logErrorln write to stdout or stderr exactly as the fmt functions
|
||||||
|
// they wrap, and also ship the line to OmniLogger when shipping is enabled, at the severity the caller
|
||||||
|
// names. The console stream is the one the helper always used, whatever the severity.
|
||||||
|
func logPrintf(sev logshipper.Level, format string, args ...any) {
|
||||||
|
logLine(stdoutLog, sev, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logPrintln(sev logshipper.Level, args ...any) {
|
||||||
|
logLine(stdoutLog, sev, fmt.Sprintln(args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logErrorf(sev logshipper.Level, format string, args ...any) {
|
||||||
|
logLine(stderrLog, sev, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func logErrorln(sev logshipper.Level, args ...any) {
|
||||||
|
logLine(stderrLog, sev, fmt.Sprintln(args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// logLine writes msg to l's console and ships it at sev. msg keeps the newline its fmt call added, so the console
|
||||||
|
// line is the same bytes as before. Levels outside the five OmniLogger knows are reported as errors.
|
||||||
|
func logLine(l *logshipper.Logger, sev logshipper.Level, msg string) {
|
||||||
|
switch sev {
|
||||||
|
case logshipper.LevelDebug:
|
||||||
|
l.Debugf("%s", msg)
|
||||||
|
case logshipper.LevelInfo:
|
||||||
|
l.Infof("%s", msg)
|
||||||
|
case logshipper.LevelWarn:
|
||||||
|
l.Warnf("%s", msg)
|
||||||
|
case logshipper.LevelCritical:
|
||||||
|
l.Criticalf("%s", msg)
|
||||||
|
default:
|
||||||
|
l.Errorf("%s", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// exitAfterFlush sends the buffered log lines to OmniLogger and then exits. Use it instead of os.Exit after a
|
||||||
|
// line that must reach OmniLogger, such as a critical startup failure, which os.Exit would otherwise lose.
|
||||||
|
func exitAfterFlush(code int) {
|
||||||
|
omniShipper.Flush()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeOmniLogger is a stand-in OmniLogger that accepts only the bearer token it was started with and
|
||||||
|
// records every entry it receives.
|
||||||
|
type fakeOmniLogger struct {
|
||||||
|
*httptest.Server
|
||||||
|
mu sync.Mutex
|
||||||
|
requests int
|
||||||
|
entries []map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFakeOmniLogger(t *testing.T, token string) *fakeOmniLogger {
|
||||||
|
t.Helper()
|
||||||
|
f := &fakeOmniLogger{}
|
||||||
|
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.requests++
|
||||||
|
f.mu.Unlock()
|
||||||
|
if r.Header.Get("Authorization") != "Bearer "+token {
|
||||||
|
w.WriteHeader(http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var batch []map[string]any
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&batch); err != nil {
|
||||||
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f.mu.Lock()
|
||||||
|
f.entries = append(f.entries, batch...)
|
||||||
|
f.mu.Unlock()
|
||||||
|
w.WriteHeader(http.StatusAccepted)
|
||||||
|
}))
|
||||||
|
t.Cleanup(f.Close)
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
// received reports how many requests arrived and the entries that were accepted.
|
||||||
|
func (f *fakeOmniLogger) received() (int, []map[string]any) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
return f.requests, append([]map[string]any(nil), f.entries...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// hasMessage reports whether an entry for the collabtable service contains text.
|
||||||
|
func hasMessage(entries []map[string]any, text string) bool {
|
||||||
|
for _, entry := range entries {
|
||||||
|
message, _ := entry["message"].(string)
|
||||||
|
if entry["service"] == "collabtable" && strings.Contains(message, text) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// useOmniShipper makes shipper the package's omniShipper for the rest of the test. The helper Loggers are rebuilt
|
||||||
|
// on it with their consoles discarded, since they are made once at start-up and would otherwise keep the old shipper.
|
||||||
|
func useOmniShipper(t *testing.T, shipper *logshipper.Shipper) {
|
||||||
|
t.Helper()
|
||||||
|
previous, previousOut, previousErr := omniShipper, stdoutLog, stderrLog
|
||||||
|
omniShipper = shipper
|
||||||
|
stdoutLog = newConsoleLogger(io.Discard, shipper)
|
||||||
|
stderrLog = newConsoleLogger(io.Discard, shipper)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = shipper.Close()
|
||||||
|
omniShipper = previous
|
||||||
|
stdoutLog, stderrLog = previousOut, previousErr
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOmniLoggerShipperIsNeverNilAndDisabledWithoutConfig(t *testing.T) {
|
||||||
|
if omniShipper == nil {
|
||||||
|
t.Fatal("omniShipper must never be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Setenv("OMNILOGGER_URL", "")
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "")
|
||||||
|
shipper := newOmniLoggerShipper()
|
||||||
|
if shipper == nil {
|
||||||
|
t.Fatal("shipper must never be nil; with no configuration it is simply disabled")
|
||||||
|
}
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
logPrintf(logshipper.LevelInfo, "no configuration, nothing should ship\n")
|
||||||
|
shipper.Flush()
|
||||||
|
|
||||||
|
// A URL without a token is still disabled, so nothing reaches a reachable OmniLogger.
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
shipper = newOmniLoggerShipper()
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
logPrintf(logshipper.LevelInfo, "no token, nothing should ship\n")
|
||||||
|
shipper.Flush()
|
||||||
|
if requests, _ := sink.received(); requests != 0 {
|
||||||
|
t.Fatalf("disabled shipper sent %d requests to OmniLogger", requests)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogPrintfReachesOmniLogger(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token")
|
||||||
|
useOmniShipper(t, newOmniLoggerShipper())
|
||||||
|
|
||||||
|
logPrintf(logshipper.LevelInfo, "[test] hello from collabtable %d\n", 7)
|
||||||
|
_ = omniShipper.Close()
|
||||||
|
|
||||||
|
if _, entries := sink.received(); !hasMessage(entries, "hello from collabtable 7") {
|
||||||
|
t.Fatalf("OmniLogger did not receive the line; entries: %v", entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOmniLoggerFollowsCoreConfigPush(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "pushed-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", "")
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "")
|
||||||
|
shipper := newOmniLoggerShipper()
|
||||||
|
useOmniShipper(t, shipper)
|
||||||
|
store := coreconfig.NewStore(coreconfig.Info{})
|
||||||
|
shipper.Follow(store)
|
||||||
|
|
||||||
|
logPrintf(logshipper.LevelInfo, "before the push\n")
|
||||||
|
shipper.Flush()
|
||||||
|
if requests, _ := sink.received(); requests != 0 {
|
||||||
|
t.Fatalf("shipper sent %d requests before ProjectConfigurator pushed a token", requests)
|
||||||
|
}
|
||||||
|
|
||||||
|
store.Set(coreconfig.Info{OmniLoggerURL: sink.URL, OmniLoggerIngestToken: "pushed-token"})
|
||||||
|
logPrintf(logshipper.LevelInfo, "after the push\n")
|
||||||
|
_ = shipper.Close()
|
||||||
|
|
||||||
|
_, entries := sink.received()
|
||||||
|
if !hasMessage(entries, "after the push") {
|
||||||
|
t.Fatalf("OmniLogger did not receive the line after the push; entries: %v", entries)
|
||||||
|
}
|
||||||
|
if hasMessage(entries, "before the push") {
|
||||||
|
t.Fatal("a line logged before the push was shipped")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine runs a converted call site: a failed
|
||||||
|
// notification is printed on stdout as before, and reaches OmniLogger once, at warn.
|
||||||
|
func TestConvertedNotificationLineShipsOnceAtWarnAndKeepsConsoleLine(t *testing.T) {
|
||||||
|
sink := newFakeOmniLogger(t, "test-token")
|
||||||
|
t.Setenv("OMNILOGGER_URL", sink.URL)
|
||||||
|
t.Setenv("OMNILOGGER_INGEST_TOKEN", "test-token")
|
||||||
|
useOmniShipper(t, newOmniLoggerShipper())
|
||||||
|
|
||||||
|
reader, writer, err := os.Pipe()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
previousStdout := stdoutLog
|
||||||
|
stdoutLog = newConsoleLogger(writer, omniShipper)
|
||||||
|
ignoreNotificationError(errors.New("disk full"))
|
||||||
|
stdoutLog = previousStdout
|
||||||
|
_ = writer.Close()
|
||||||
|
console, _ := io.ReadAll(reader)
|
||||||
|
_ = reader.Close()
|
||||||
|
if got, want := string(console), "[notifications] enqueue failed: disk full\n"; got != want {
|
||||||
|
t.Fatalf("console output = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = omniShipper.Close()
|
||||||
|
_, entries := sink.received()
|
||||||
|
var levels []string
|
||||||
|
for _, entry := range entries {
|
||||||
|
message, _ := entry["message"].(string)
|
||||||
|
if entry["service"] == "collabtable" && message == "[notifications] enqueue failed: disk full" {
|
||||||
|
level, _ := entry["level"].(string)
|
||||||
|
levels = append(levels, level)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(levels) != 1 || levels[0] != "warn" {
|
||||||
|
t.Fatalf("OmniLogger levels for the notification line = %v, want exactly one warn (entries %v)", levels, entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-23
@@ -6,8 +6,9 @@ import (
|
|||||||
"embed"
|
"embed"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -20,6 +21,7 @@ import (
|
|||||||
|
|
||||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -53,25 +55,26 @@ func main() {
|
|||||||
if len(os.Args) > 1 && os.Args[1] == "remap-users" {
|
if len(os.Args) > 1 && os.Args[1] == "remap-users" {
|
||||||
os.Exit(runRemapUsers(os.Args[2:], os.Stdout))
|
os.Exit(runRemapUsers(os.Args[2:], os.Stdout))
|
||||||
}
|
}
|
||||||
|
log.SetOutput(io.MultiWriter(os.Stderr, omniShipper.Writer()))
|
||||||
port := envOrDefault("PORT", "8080")
|
port := envOrDefault("PORT", "8080")
|
||||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||||
if connectionString == "" {
|
if connectionString == "" {
|
||||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
logErrorln(logshipper.LevelCritical, "DATABASE_URL environment variable is required")
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
|
internalServiceSecret := strings.TrimSpace(os.Getenv("SECRET"))
|
||||||
|
|
||||||
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
|
trustedProxies, err := parseTrustedProxies(os.Getenv("TRUSTED_PROXIES"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintln(os.Stderr, err)
|
logErrorln(logshipper.LevelCritical, err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
|
// PRODUCTION=true refuses plain HTTP. This process has no TLS of its own, so
|
||||||
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
|
// the encrypted hop has to be a reverse proxy listed in TRUSTED_PROXIES.
|
||||||
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
|
production := strings.EqualFold(strings.TrimSpace(os.Getenv("PRODUCTION")), "true")
|
||||||
if production && len(trustedProxies) == 0 {
|
if production && len(trustedProxies) == 0 {
|
||||||
fmt.Fprintln(os.Stderr, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
|
logErrorln(logshipper.LevelCritical, "PRODUCTION=true requires TRUSTED_PROXIES: HTTPS must be terminated by a reverse proxy listed there")
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
@@ -79,8 +82,8 @@ func main() {
|
|||||||
|
|
||||||
database, err := connectWithRetry(ctx, connectionString)
|
database, err := connectWithRetry(ctx, connectionString)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "database initialization failed: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
defer database.close()
|
defer database.close()
|
||||||
go database.pruneExpiredSessions(ctx)
|
go database.pruneExpiredSessions(ctx)
|
||||||
@@ -98,11 +101,11 @@ func main() {
|
|||||||
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
|
authDisabled := strings.EqualFold(os.Getenv("AUTH_DISABLED"), "true")
|
||||||
switch {
|
switch {
|
||||||
case authDisabled:
|
case authDisabled:
|
||||||
fmt.Println("auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
|
logPrintln(logshipper.LevelWarn, "auth: DISABLED (AUTH_DISABLED=true) -- every request is treated as authenticated")
|
||||||
case authGuardURL != "":
|
case authGuardURL != "":
|
||||||
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
|
logPrintf(logshipper.LevelInfo, "auth: AuthGuard at %s\n", authGuardURL)
|
||||||
default:
|
default:
|
||||||
fmt.Println("auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
|
logPrintln(logshipper.LevelWarn, "auth: PENDING (AUTHGUARD_URL not set) -- waiting for ProjectConfigurator to push an AuthGuard URL; auth calls fail closed until then")
|
||||||
}
|
}
|
||||||
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
|
auth := newAuthService(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"), authDisabled)
|
||||||
|
|
||||||
@@ -115,6 +118,7 @@ func main() {
|
|||||||
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
|
// is a no-op when this service was constructed in auth-disabled mode (AUTH_DISABLED=true above).
|
||||||
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL"))
|
||||||
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL})
|
||||||
|
omniShipper.Follow(coreConfig)
|
||||||
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
coreConfig.OnUpdate(func(info coreconfig.Info) {
|
||||||
if info.AuthGuardURL != "" {
|
if info.AuthGuardURL != "" {
|
||||||
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
auth.SetAuthGuardBaseURL(info.AuthGuardURL)
|
||||||
@@ -132,8 +136,8 @@ func main() {
|
|||||||
|
|
||||||
webRoot, err := fs.Sub(webFS, "web")
|
webRoot, err := fs.Sub(webFS, "web")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "embedded web assets missing: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
@@ -142,9 +146,9 @@ func main() {
|
|||||||
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
|
handler := withSecurityHeaders(withGzip(withCORS(allowedOriginsFromEnv(), mux)))
|
||||||
if production {
|
if production {
|
||||||
handler = withHTTPSRequired(trustedProxies, handler)
|
handler = withHTTPSRequired(trustedProxies, handler)
|
||||||
fmt.Println("PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
|
logPrintln(logshipper.LevelInfo, "PRODUCTION=true: plain HTTP requests are refused unless they arrive over TLS or through a trusted proxy that sets X-Forwarded-Proto: https")
|
||||||
} else {
|
} else {
|
||||||
fmt.Fprintln(os.Stderr, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
|
logErrorln(logshipper.LevelWarn, "WARNING: TLS is off in this process, so passwords, session cookies and sync tokens cross the network unencrypted unless a TLS proxy is in front. Set PRODUCTION=true to refuse plain HTTP.")
|
||||||
}
|
}
|
||||||
|
|
||||||
httpServer := &http.Server{
|
httpServer := &http.Server{
|
||||||
@@ -156,11 +160,11 @@ func main() {
|
|||||||
IdleTimeout: 120 * time.Second,
|
IdleTimeout: 120 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("CollabTable Go server listening on :%s\n", port)
|
logPrintf(logshipper.LevelInfo, "CollabTable Go server listening on :%s\n", port)
|
||||||
fmt.Printf("Database: PostgreSQL (pgx)\n")
|
logPrintf(logshipper.LevelInfo, "Database: PostgreSQL (pgx)\n")
|
||||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||||
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
|
logErrorf(logshipper.LevelCritical, "server error: %v\n", err)
|
||||||
os.Exit(1)
|
exitAfterFlush(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +176,7 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
||||||
if attempt > 1 {
|
if attempt > 1 {
|
||||||
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
|
logPrintf(logshipper.LevelInfo, "[DB] Connected after %d attempt(s)\n", attempt)
|
||||||
}
|
}
|
||||||
return database, nil
|
return database, nil
|
||||||
} else {
|
} else {
|
||||||
@@ -181,11 +185,11 @@ func connectWithRetry(ctx context.Context, connectionString string) (*DB, error)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
logErrorf(logshipper.LevelWarn, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||||
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
if retryOptions.MaxAttempts > 0 && attempt >= retryOptions.MaxAttempts {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
fmt.Printf("[DB] Retrying in %s...\n", retryOptions.Interval)
|
logPrintf(logshipper.LevelWarn, "[DB] Retrying in %s...\n", retryOptions.Interval)
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return nil, ctx.Err()
|
return nil, ctx.Err()
|
||||||
|
|||||||
+4
-3
@@ -3,12 +3,13 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/logshipper"
|
||||||
)
|
)
|
||||||
|
|
||||||
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
// maxConcurrentSyncs caps sync requests in flight. It stays below the pool size
|
||||||
@@ -431,7 +432,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
|||||||
orphans := make([]OrphanValue, 0)
|
orphans := make([]OrphanValue, 0)
|
||||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||||
if incoming > 0 {
|
if incoming > 0 {
|
||||||
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
logPrintf(logshipper.LevelInfo, "[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
||||||
}
|
}
|
||||||
|
|
||||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||||
@@ -447,7 +448,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
logPrintf(logshipper.LevelError, "[SYNC] Failed: %v\n", err)
|
||||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user