package web import ( "slices" "context" "strconv" "strings" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" ) // RegionStatus is the latest result of one region. type RegionStatus struct { Name string Status Status Detail string } // MonitorRow is a monitor on the dashboard. type MonitorRow struct { ID string GroupID string Name string Type string Target string Status Status Regions []RegionStatus Latency string Uptime string Bars []Bar } // GroupNode is a monitor group with its monitors and subgroups. type GroupNode struct { ID string Name string Status Status Total int Monitors []MonitorRow Children []GroupNode } // GroupOption is a group in a select; Label is indented by depth. type GroupOption struct { ID string Label string } // DashboardView is the data of the monitor list. Root holds ungrouped // monitors and the top-level groups. type DashboardView struct { Root GroupNode Empty bool CanWrite bool Counts map[Status]int Range string Ranges []RangeOption } // RangeOption is an entry of the range switcher. Disabled ranges are not // yet covered by enough data. type RangeOption struct { Key string Active bool URL string Disabled bool } // SLAEntry is one window of the SLA table. Partial windows are less than // half covered by data. type SLAEntry struct { Label string Value string Partial bool } // RegionHistory is one region's view of a monitor in the selected range. type RegionHistory struct { Name string Uptime string Bars []Bar // Enough is false when the region reported for less than half the range. Enough bool } templ rangeSwitch(opts []RangeOption) { } templ statusDot(s Status) { } templ bars(bs []Bar, height int) { for i, b := range bs { { b.Title } } } templ Dashboard(p Page, me Me, v DashboardView) { @consoleShell(p, me) {

{ i18n.T(ctx, "console.monitors.title") }

@rangeSwitch(v.Ranges) for _, s := range []Status{StatusUp, StatusDegraded, StatusDown, StatusMaintenance, StatusPaused} { if v.Counts[s] > 0 { @statusDot(s) { strconv.Itoa(v.Counts[s]) } } } if v.CanWrite { { i18n.T(ctx, "monitors.new") } }
if v.Empty {

{ i18n.T(ctx, "console.monitors.empty") }

} else {
@monitorList(v.Root.Monitors) for _, g := range v.Root.Children { @groupBlock(g) }

{ i18n.T(ctx, "monitors.range_note", "Range", v.Range) }

}

{ i18n.T(ctx, "groups.manage") }

} } templ monitorList(ms []MonitorRow) { if len(ms) > 0 { } } // groupBlock renders a group and, recursively, its subgroups.
// makes groups collapsible without JavaScript. templ groupBlock(g GroupNode) {
@statusDot(g.Status) { g.Name } { strconv.Itoa(g.Total) }
@monitorList(g.Monitors) for _, c := range g.Children { @groupBlock(c) }
} // ResultRow is one check result on the detail page. type ResultRow struct { Time string Region string OK bool Latency string Detail string // EvidenceURL links to what the checker saw, for editors. EvidenceURL string // Checker names the instance that ran the check. Checker CheckerLink } // IncidentRow is an incident in a list. type IncidentRow struct { ID string MonitorID string Monitor string Started string Duration string Open bool Cause []string } // MonitorDetailView is the data of a monitor page. type MonitorDetailView struct { Row MonitorRow Range string Ranges []RangeOption SLAs []SLAEntry Regions []RegionHistory Interval string Daily []Bar Uptime90 string Latency LatencyLine Recent []ResultRow Incidents []IncidentRow CanWrite bool // Maintenance lists current and upcoming maintenance. Maintenance []MaintenanceItem // PingURL is set for heartbeat monitors the viewer may change. PingURL string // Evidence lists what checkers saw; only editors get it. Evidence []EvidenceRow } // MaintenanceItem is one occurrence of planned maintenance. type MaintenanceItem struct { Title string When string Description string Active bool } templ MonitorDetail(p Page, me Me, v MonitorDetailView) { @consoleShell(p, me) {

← { i18n.T(ctx, "console.monitors.title") }

@statusDot(v.Row.Status) { v.Row.Name }

{ i18n.T(ctx, "monitors.type_"+v.Row.Type) } if v.Row.Target != "" { { " · " + v.Row.Target } } { " · " + v.Interval }

if v.CanWrite { { i18n.T(ctx, "sso.action.edit") } }

{ i18n.T(ctx, "monitors.history", "Range", v.Range) }

@rangeSwitch(v.Ranges)
{ i18n.T(ctx, "monitors.sla") } { v.Row.Uptime }
@bars(v.Row.Bars, 28) if v.Latency.Points != "" {
{ i18n.T(ctx, "monitors.latency") } max { strconv.Itoa(v.Latency.MaxMS) } ms
}
if len(v.Regions) > 1 {
@sectionHeading("monitors.by_region")

{ i18n.T(ctx, "monitors.by_region_hint") }

} if v.PingURL != "" { @pingSection(v.PingURL) } if len(v.Maintenance) > 0 {
@sectionHeading("maintenance.title") @maintenanceList(v.Maintenance)
}
@sectionHeading("monitors.sla_table")
for _, e := range v.SLAs {
{ e.Label }
{ e.Value }
}
@sectionHeading("monitors.last_90d") { v.Uptime90 }
@bars(v.Daily, 28)
@sectionHeading("monitors.regions")
    for _, r := range v.Row.Regions {
  • @statusDot(r.Status) { r.Name } { r.Detail }
  • }
if len(v.Incidents) > 0 {
@sectionHeading("incidents.title") @incidentList(v.Incidents, false)
} if len(v.Evidence) > 0 { @evidenceList(v.Evidence) }
@sectionHeading("monitors.recent") for _, r := range v.Recent { }
{ r.Time } { r.Region } @checkerCell(r.Checker) if r.OK { ● } else { ● } { r.Latency } { r.Detail } if r.EvidenceURL != "" { { i18n.T(ctx, "evidence.show") } }
} } templ incidentList(rows []IncidentRow, showMonitor bool) { } templ IncidentsPage(p Page, me Me, rows []IncidentRow) { @consoleShell(p, me) { @settingsHeading("incidents.title", "") if len(rows) == 0 {

{ i18n.T(ctx, "incidents.none") }

} else { @incidentList(rows, true) } } } // RegionOption is a selectable region in the monitor form. type RegionOption struct { ID string Name string Own bool Checked bool Live int64 } // MonitorForm is the data of the monitor editor; ID is empty for new ones. type MonitorForm struct { AlertGroups []AlertGroupOption ID string Name string Type string Target string IntervalSeconds int TimeoutMS int Confirmations int Enabled bool GroupID string Groups []GroupOption // TopLevel is set when the monitor may live outside any group. TopLevel bool Regions []RegionOption MinInterval int // Type-specific settings. Method string ExpectStatus string Keyword string KeywordAbsent bool FollowRedirects bool VerifyTLS bool DNSRecord string DNSResolver string DNSExpect string TLSMinDays int TLSServerName string GraceSeconds int // Headers are "Name: value" lines, shared by HTTP and JSON checks. Headers string JSONMethod string JSONBody string JSONExpect string JSONVerify bool Assertions []AssertionRow PromQuery string PromOp string PromThreshold string PromMode string PromEmptyOK bool PromVerify bool Matchers []MatcherRow StaleHours int DB DBForm Broker BrokerForm Proto ProtocolForm Game GameForm DockerHost string // Types are the check types to offer. Types []string } // BrokerForm holds the settings of message broker checks. type BrokerForm struct { User, TLS, Topic, Expect, Message, SASL, Vhost, Queue string PasswordSet bool } // ProtocolForm holds the settings of gRPC, SMTP, RADIUS and SNMP checks. // Secrets are never filled in; the *Set fields tell the form one is // stored. type ProtocolForm struct { Service, TLS string ImplicitTLS bool User, NASIdentifier string SecretSet, PasswordSet, CommunitySet bool Version, OID, Condition, Value string } // GameForm holds the settings of game server checks. type GameForm struct { Edition string MinFreeSlots int } // DBForm holds the settings of database checks. The password is never // filled in; PasswordSet tells the form one is stored. type DBForm struct { User string Database string TLS string Query string Expect string PasswordSet bool } // MatcherRow is one label matcher of an alertmanager monitor. type MatcherRow struct { Label string Op string Value string } // MatcherOps are Prometheus' label matching operators. var MatcherOps = []string{"=", "!=", "=~", "!~"} // AssertionRow is one condition of a JSON check; unused rows are empty. type AssertionRow struct { Path string Op string Value string } // AssertionOps are offered in the JSON check form. var AssertionOps = []string{"==", "!=", ">", ">=", "<", "<=", "contains", "exists", "absent"} templ headersField(value string) { } templ typeFields(typ, current string) {
{ children... }
} templ numberField(label, name string, value, min, max int, hint string) { } templ MonitorEditor(p Page, me Me, f MonitorForm) { @consoleShell(p, me) {

if f.ID == "" { ← { i18n.T(ctx, "console.monitors.title") } } else { ← { f.Name } }

{ i18n.T(ctx, p.TitleID) }

@formError() @valueField(i18n.T(ctx, "sso.field.name"), "name", f.Name, "", true)
{ i18n.T(ctx, "alert_groups.title") } @alertGroupOptions("alert_group_ids", f.AlertGroups)

{ i18n.T(ctx, "alert_groups.monitor_hint") }

@valueField(i18n.T(ctx, "monitors.target"), "target", f.Target, "https://example.com", f.Type != "heartbeat")

{ i18n.T(ctx, "monitors.target_hint") }

for _, t := range []string{"postgres", "mysql", "mssql", "mongodb", "redis"} { @typeFields(t, f.Type) { @dbFields(t, f.DB) } } for _, t := range []string{"mqtt", "kafka", "rabbitmq"} { @typeFields(t, f.Type) { @brokerFields(t, f.Broker) } } @typeFields("grpc", f.Type) {

{ i18n.T(ctx, "monitors.grpc_hint") }

@valueField(i18n.T(ctx, "monitors.grpc_service"), "config.service", f.Proto.Service, "shop.v1.Orders", false) @tlsField(f.Proto.TLS, "verify", "require", "disable") } @typeFields("smtp", f.Type) {

{ i18n.T(ctx, "monitors.smtp_hint") }

@tlsField(f.Proto.TLS, "verify", "require", "disable") @checkbox(i18n.T(ctx, "monitors.smtp_implicit_tls"), "config.implicit_tls", f.Proto.ImplicitTLS) } @typeFields("radius", f.Type) {

{ i18n.T(ctx, "monitors.radius_hint") }

@secretField(i18n.T(ctx, "monitors.radius_secret"), "config.secret", f.Proto.SecretSet) @valueField(i18n.T(ctx, "monitors.db_user"), "config.user", f.Proto.User, "", false) @secretField(i18n.T(ctx, "monitors.db_password"), "config.password", f.Proto.PasswordSet) @valueField(i18n.T(ctx, "monitors.radius_nas"), "config.nas_identifier", f.Proto.NASIdentifier, "uptimesebi", false) } @typeFields("snmp", f.Type) {

{ i18n.T(ctx, "monitors.snmp_hint") }

@secretField(i18n.T(ctx, "monitors.snmp_community"), "config.community", f.Proto.CommunitySet) @valueField(i18n.T(ctx, "monitors.snmp_oid"), "config.oid", f.Proto.OID, "1.3.6.1.2.1.1.3.0", false)
@valueField(i18n.T(ctx, "monitors.snmp_value"), "config.value", f.Proto.Value, "", false)
} @typeFields("steam", f.Type) {

{ i18n.T(ctx, "monitors.steam_hint") }

@numberField(i18n.T(ctx, "monitors.game_min_free_slots"), "config.min_free_slots", f.Game.MinFreeSlots, 0, 10000, i18n.T(ctx, "monitors.game_min_free_slots_hint")) } @typeFields("minecraft", f.Type) {

{ i18n.T(ctx, "monitors.minecraft_hint") }

@numberField(i18n.T(ctx, "monitors.game_min_free_slots"), "config.min_free_slots", f.Game.MinFreeSlots, 0, 10000, i18n.T(ctx, "monitors.game_min_free_slots_hint")) } @typeFields("docker", f.Type) {

{ i18n.T(ctx, "monitors.docker_hint") }

@valueField(i18n.T(ctx, "monitors.docker_host"), "config.host", f.DockerHost, "unix:///var/run/docker.sock", false) } @typeFields("alertmanager", f.Type) {

{ i18n.T(ctx, "monitors.alertmanager_hint") } { i18n.T(ctx, "alertmanager.title") }

{ i18n.T(ctx, "monitors.matchers") } for i, m := range f.Matchers {
}

{ i18n.T(ctx, "monitors.matchers_hint") }

@numberField(i18n.T(ctx, "monitors.stale_hours"), "config.stale_hours", f.StaleHours, 1, 720, i18n.T(ctx, "monitors.stale_hours_hint")) } @typeFields("heartbeat", f.Type) {

{ i18n.T(ctx, "monitors.heartbeat_hint") }

@numberField(i18n.T(ctx, "monitors.grace"), "config.grace_seconds", f.GraceSeconds, 0, 86400, i18n.T(ctx, "monitors.grace_hint")) } @typeFields("http", f.Type) { @valueField(i18n.T(ctx, "monitors.keyword"), "config.keyword", f.Keyword, "", false) @checkbox(i18n.T(ctx, "monitors.keyword_absent"), "config.keyword_absent", f.KeywordAbsent) @checkbox(i18n.T(ctx, "monitors.follow_redirects"), "config.follow_redirects", f.FollowRedirects) @checkbox(i18n.T(ctx, "monitors.verify_tls"), "config.verify_tls", f.VerifyTLS) @headersField(f.Headers) } @typeFields("prometheus", f.Type) {

{ i18n.T(ctx, "monitors.prom_hint") }

@checkbox(i18n.T(ctx, "monitors.prom_empty_ok"), "config.empty_ok", f.PromEmptyOK) @checkbox(i18n.T(ctx, "monitors.verify_tls"), "config.verify_tls", f.PromVerify) @headersField(f.Headers) } @typeFields("json", f.Type) { @checkbox(i18n.T(ctx, "monitors.verify_tls"), "config.verify_tls", f.JSONVerify) @headersField(f.Headers)
{ i18n.T(ctx, "monitors.assertions") }

{ i18n.T(ctx, "monitors.assertions_hint") }

for i, a := range f.Assertions {
}
} @typeFields("dns", f.Type) { @valueField(i18n.T(ctx, "monitors.dns_resolver"), "config.resolver", f.DNSResolver, "1.1.1.1:53", false) @valueField(i18n.T(ctx, "monitors.dns_expect"), "config.expect", f.DNSExpect, "", false) } @typeFields("tls", f.Type) { @numberField(i18n.T(ctx, "monitors.tls_min_days"), "config.min_days_valid", f.TLSMinDays, 0, 365, "") @valueField(i18n.T(ctx, "monitors.tls_server_name"), "config.server_name", f.TLSServerName, "", false) }
@numberField(i18n.T(ctx, "monitors.interval"), "interval_seconds", f.IntervalSeconds, f.MinInterval, 86400, i18n.T(ctx, "monitors.interval_hint", "Min", f.MinInterval))
@numberField(i18n.T(ctx, "monitors.timeout"), "timeout_ms", f.TimeoutMS, 100, 60000, "")
@numberField(i18n.T(ctx, "monitors.confirmations"), "confirmations", f.Confirmations, 1, 10, i18n.T(ctx, "monitors.confirmations_hint"))
{ i18n.T(ctx, "monitors.regions") }

{ i18n.T(ctx, "monitors.regions_hint") }

for _, r := range f.Regions { }
@checkbox(i18n.T(ctx, "sso.field.enabled"), "enabled", f.Enabled) @submit(i18n.T(ctx, "common.save")) if f.ID != "" { }
} } // ChannelRow is a notification channel in the list. type ChannelRow struct { ID string Name string Type string Target string Enabled bool } // ChannelsView is the data of the notification channels page. type ChannelsView struct { AlertGroups []AlertGroupRow Channels []ChannelRow EmailAvailable bool CanWrite bool Languages []string Providers []ProviderOption } templ ChannelsPage(p Page, me Me, v ChannelsView) { @consoleShell(p, me) { @settingsHeading("channels.title", "channels.intro") @alertGroupsSettings(v) if len(v.Channels) > 0 { } if v.CanWrite {
@sectionHeading("channels.new_webhook")
@formError() @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Ops", true) @valueField(i18n.T(ctx, "channels.url"), "url", "", "https://example.com/hooks/uptime", true) @submit(i18n.T(ctx, "channels.create"))
@sectionHeading("channels.new_email") if v.EmailAvailable {
@formError() @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "On-call", true) @submit(i18n.T(ctx, "channels.create"))
} else {

{ i18n.T(ctx, "error.email_not_configured") }

}
@sectionHeading("channels.new_service")

{ i18n.T(ctx, "channels.service_intro") }

@formError() @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Ops", true)
for i, pr := range v.Providers {
if pr.Help != "" {

{ pr.Help }

} for _, f := range pr.Fields { @providerField(f) }
} @submit(i18n.T(ctx, "channels.create"))
} } } // ProviderOption is a notification service the form offers. type ProviderOption struct { Type string Group string Help string Fields []ProviderField } // ProviderField is a setting of a service. type ProviderField struct { Name string Label string Required bool Secret bool Kind string Options []string Default string } templ providerField(f ProviderField) { } templ groupSelect(name string, groups []GroupOption, selected string, allowNone bool) { } // GroupRow is a group on the management page. type GroupRow struct { ID string Name string Depth int ParentID string CanWrite bool } // GroupsView is the data of the group management page. type GroupsView struct { Groups []GroupRow // Parents are the groups new groups can be placed in. Parents []GroupOption TopLevel bool CanWrite bool } templ GroupsPage(p Page, me Me, v GroupsView) { @consoleShell(p, me) {

← { i18n.T(ctx, "console.monitors.title") }

@settingsHeading("groups.title", "groups.intro") if len(v.Groups) > 0 { } if v.CanWrite {
@sectionHeading("groups.create")
@formError() @valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Production", true) @submit(i18n.T(ctx, "groups.create"))
} } } func partialTitle(ctx context.Context, partial bool) string { if !partial { return "" } return i18n.T(ctx, "monitors.range_not_enough") } templ pingSection(url string) {
@sectionHeading("monitors.ping_url")

{ i18n.T(ctx, "monitors.ping_intro") }

{ "curl -fsS -m 10 --retry 3 " + url + "\n" }{ "curl -fsS -m 10 --retry 3 --data-raw \"$output\" " + url + "/fail" }

{ i18n.T(ctx, "monitors.ping_secret") }

} // opKey names an assertion operator in message IDs. func opKey(op string) string { switch op { case "==": return "eq" case "!=": return "ne" case ">": return "gt" case ">=": return "ge" case "<": return "lt" case "<=": return "le" } return op } func passiveType(t string) bool { return t == "heartbeat" || t == "alertmanager" } templ dbFields(typ string, d DBForm) {

{ i18n.T(ctx, "monitors.db_hint") }

if typ != "redis" { @valueField(i18n.T(ctx, "monitors.db_user"), "config.user", d.User, "", false) } else { @valueField(i18n.T(ctx, "monitors.db_user_redis"), "config.user", d.User, "", false) } @secretField(i18n.T(ctx, "monitors.db_password"), "config.password", d.PasswordSet) @valueField(i18n.T(ctx, "monitors.db_database_"+typ), "config.database", d.Database, "", false) @tlsField(d.TLS, "require", "verify", "disable") if typ != "redis" && typ != "mongodb" { @valueField(i18n.T(ctx, "monitors.db_expect"), "config.expect", d.Expect, "", false) } } // secretField asks for a secret that is never shown again; left empty, // the stored one is kept. templ secretField(label, name string, set bool) { } // tlsField chooses a TLS mode; the first is preselected for new monitors. templ tlsField(value string, modes ...string) { } templ brokerFields(typ string, b BrokerForm) {

{ i18n.T(ctx, "monitors.broker_hint_"+typ) }

@valueField(i18n.T(ctx, "monitors.broker_user"), "config.user", b.User, "", false) @secretField(i18n.T(ctx, "monitors.db_password"), "config.password", b.PasswordSet) @tlsField(b.TLS, "disable", "require", "verify") switch typ { case "mqtt": @valueField(i18n.T(ctx, "monitors.broker_topic_mqtt"), "config.topic", b.Topic, "devices/pump/status", false) @valueField(i18n.T(ctx, "monitors.broker_expect"), "config.expect", b.Expect, "", false) case "kafka": @valueField(i18n.T(ctx, "monitors.broker_topic_kafka"), "config.topic", b.Topic, "", false) @valueField(i18n.T(ctx, "monitors.broker_message"), "config.message", b.Message, "", false) case "rabbitmq": @valueField(i18n.T(ctx, "monitors.broker_vhost"), "config.vhost", b.Vhost, "/", false) @valueField(i18n.T(ctx, "monitors.broker_queue"), "config.queue", b.Queue, "", false) } } func condKey(c string) string { if c == "" { return "any" } return c } // providerGroups lists the groups of providers in the order they come. func providerGroups(ps []ProviderOption) []string { var out []string for _, p := range ps { if !slices.Contains(out, p.Group) { out = append(out, p.Group) } } return out }