All checks were successful
release / build (push) Successful in 4m13s
One line per job: label, source -> target, method, state text, age and schedule, from the RS10-Z /v1/backups metadata. hub status adds critical alerts and a backup summary token from /v1/summary. Servers without the new fields keep the previous output.
364 lines
9.3 KiB
Go
364 lines
9.3 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
package fleet
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// WriteJSON prints v like Python's json.dumps(indent=2, sort_keys=True): sorted keys (maps), two-space indent,
|
|
// no HTML escaping, numbers as written, trailing newline.
|
|
func WriteJSON(w io.Writer, v any) error {
|
|
enc := json.NewEncoder(w)
|
|
enc.SetIndent("", " ")
|
|
enc.SetEscapeHTML(false)
|
|
return enc.Encode(v)
|
|
}
|
|
|
|
func parseTime(v any) (time.Time, bool) {
|
|
s, ok := v.(string)
|
|
if !ok {
|
|
return time.Time{}, false
|
|
}
|
|
for _, layout := range []string{time.RFC3339Nano, "2006-01-02T15:04:05", "2006-01-02 15:04:05"} {
|
|
if t, err := time.Parse(layout, s); err == nil {
|
|
return t.UTC(), true
|
|
}
|
|
}
|
|
return time.Time{}, false
|
|
}
|
|
|
|
// age renders generated_at minus at in whole seconds ("-" when either is unparseable), like fleetctl._age.
|
|
func age(env *Envelope, at any) string {
|
|
moment, ok1 := parseTime(at)
|
|
generated, ok2 := parseTime(env.Raw["generated_at"])
|
|
if !ok1 || !ok2 {
|
|
return "-"
|
|
}
|
|
secs := int64(generated.Sub(moment).Seconds())
|
|
if secs < 0 {
|
|
secs = 0
|
|
}
|
|
return fmt.Sprintf("%ds", secs)
|
|
}
|
|
|
|
func short(v any) string {
|
|
if s, ok := v.(string); ok && s != "" {
|
|
if len(s) > 12 {
|
|
return s[:12]
|
|
}
|
|
return s
|
|
}
|
|
return "-"
|
|
}
|
|
|
|
func dash(v any) string {
|
|
switch t := v.(type) {
|
|
case nil:
|
|
return "-"
|
|
case json.Number:
|
|
return t.String()
|
|
case string:
|
|
return t
|
|
case bool:
|
|
if t {
|
|
return "True"
|
|
}
|
|
return "False"
|
|
default:
|
|
return fmt.Sprint(t)
|
|
}
|
|
}
|
|
|
|
func obj(v any) map[string]any {
|
|
m, _ := v.(map[string]any)
|
|
if m == nil {
|
|
return map[string]any{}
|
|
}
|
|
return m
|
|
}
|
|
|
|
func sortedKeys(m map[string]any) []string {
|
|
keys := make([]string, 0, len(m))
|
|
for k := range m {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
return keys
|
|
}
|
|
|
|
// Status fetches /v1/summary, prints it, and returns the exit code (1 when the snapshot is stale or the oldest
|
|
// intel feed is missing or older than 36 hours, or any feed is failing).
|
|
func Status(ctx context.Context, c *Client, w io.Writer, asJSON bool) (int, error) {
|
|
env, err := c.Summary(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
code := ExitOK
|
|
if env.Stale {
|
|
code = ExitDrift
|
|
}
|
|
intelLine, intelBad := intelCheck(env)
|
|
if intelBad {
|
|
code = ExitDrift
|
|
}
|
|
if asJSON {
|
|
return code, WriteJSON(w, env.Raw)
|
|
}
|
|
first := fmt.Sprintf("snapshot %s age %ss", dash(env.Raw["generated_at"]), dash(env.Raw["snapshot_age_seconds"]))
|
|
if env.Stale {
|
|
first += ", STALE"
|
|
}
|
|
if env.CoverageComplete != nil && !*env.CoverageComplete {
|
|
first += ", coverage incomplete"
|
|
}
|
|
for _, token := range []string{criticalAlertsToken(env), backupSummaryToken(env)} {
|
|
if token != "" {
|
|
first += ", " + token
|
|
}
|
|
}
|
|
fmt.Fprintln(w, first)
|
|
data := obj(env.Raw["data"])
|
|
for _, host := range sortedKeys(data) {
|
|
row := obj(data[host])
|
|
publish := obj(row["publish"])
|
|
highstate := obj(row["highstate"])
|
|
failed := "0"
|
|
if v, ok := row["publish_failed_24h"]; ok && v != nil {
|
|
failed = dash(v)
|
|
}
|
|
fmt.Fprintf(w, "%s publish rc=%s %s failed24h=%s highstate %s/%s %s\n", host,
|
|
dash(publish["retcode"]), age(env, publish["at"]), failed,
|
|
dash(highstate["states_result_false"]), dash(highstate["state_count"]), age(env, highstate["at"]))
|
|
}
|
|
if len(env.SilentHosts) > 0 {
|
|
silent := append([]string(nil), env.SilentHosts...)
|
|
sort.Strings(silent)
|
|
fmt.Fprintf(w, "accepted but silent: %s\n", strings.Join(silent, ", "))
|
|
}
|
|
fmt.Fprintln(w, intelLine)
|
|
return code, nil
|
|
}
|
|
|
|
// Jobs fetches /v1/jobs and prints it (exit 0 unless an error is returned).
|
|
func Jobs(ctx context.Context, c *Client, w io.Writer, asJSON bool, host, fun string, limit int) (int, error) {
|
|
env, err := c.Jobs(ctx, host, fun, limit)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if asJSON {
|
|
return ExitOK, WriteJSON(w, env.Raw)
|
|
}
|
|
rows, _ := env.Raw["data"].([]any)
|
|
for _, r := range rows {
|
|
row := obj(r)
|
|
fmt.Fprintf(w, "%s %s %s rc=%s\n", dash(row["at"]), dash(row["minion"]), dash(row["function"]), dash(row["retcode"]))
|
|
}
|
|
return ExitOK, nil
|
|
}
|
|
|
|
// DriftMap lists repo files (relative to the hub directory) copied verbatim to the deployed paths.
|
|
var DriftMap = []struct {
|
|
Repo string
|
|
Deployed []string
|
|
}{
|
|
{"salt/_modules/security_hub_audit.py", []string{
|
|
"/srv/salt/_modules/security_hub_audit.py",
|
|
"/var/cache/salt/minion/extmods/modules/security_hub_audit.py",
|
|
}},
|
|
{"salt/_runners/security_hub_event.py", []string{
|
|
"/srv/salt/_runners/security_hub_event.py",
|
|
"/var/cache/salt/master/extmods/runners/security_hub_event.py",
|
|
}},
|
|
}
|
|
|
|
// DriftRow is one comparison; JSON keys match fleetctl (alphabetical, as sort_keys prints them).
|
|
type DriftRow struct {
|
|
Deployed string `json:"deployed"`
|
|
LiveSHA *string `json:"live_sha256"`
|
|
Repo string `json:"repo"`
|
|
RepoSHA string `json:"repo_sha256"`
|
|
Status string `json:"status"`
|
|
}
|
|
|
|
// Drift compares repo module hashes with the deployed ones. hubDir is the salt-security-hub directory.
|
|
func Drift(ctx context.Context, c *Client, w io.Writer, asJSON bool, hubDir string) (int, error) {
|
|
env, err := c.Modules(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
modules := obj(env.Raw["data"])
|
|
var rows []DriftRow
|
|
for _, m := range DriftMap {
|
|
raw, err := os.ReadFile(filepath.Join(hubDir, m.Repo))
|
|
if err != nil {
|
|
return 0, &ConfigError{"repo file unreadable: " + filepath.Join(hubDir, m.Repo)}
|
|
}
|
|
sum := sha256.Sum256(raw)
|
|
repoSHA := hex.EncodeToString(sum[:])
|
|
for _, deployed := range m.Deployed {
|
|
row := DriftRow{Deployed: deployed, Repo: m.Repo, RepoSHA: repoSHA}
|
|
if live, ok := obj(modules[deployed])["sha256"].(string); ok {
|
|
row.LiveSHA = &live
|
|
}
|
|
switch {
|
|
case row.LiveSHA == nil:
|
|
row.Status = "absent"
|
|
case *row.LiveSHA == repoSHA:
|
|
row.Status = "match"
|
|
default:
|
|
row.Status = "differs"
|
|
}
|
|
rows = append(rows, row)
|
|
}
|
|
}
|
|
if asJSON {
|
|
var buf bytes.Buffer
|
|
if err := WriteJSON(&buf, rows); err != nil {
|
|
return 0, err
|
|
}
|
|
if _, err := w.Write(buf.Bytes()); err != nil {
|
|
return 0, err
|
|
}
|
|
} else {
|
|
for _, r := range rows {
|
|
live := "-"
|
|
if r.LiveSHA != nil {
|
|
live = short(*r.LiveSHA)
|
|
}
|
|
fmt.Fprintf(w, "%s %s repo=%s live=%s\n", r.Status, r.Deployed, short(r.RepoSHA), live)
|
|
}
|
|
}
|
|
code := ExitOK
|
|
for _, r := range rows {
|
|
if r.Status != "match" {
|
|
code = ExitDrift
|
|
}
|
|
}
|
|
if env.Stale {
|
|
code = ExitDrift
|
|
}
|
|
return code, nil
|
|
}
|
|
|
|
// humanBytes renders a byte count with binary units ("-" when absent or not a number).
|
|
func humanBytes(v any) string {
|
|
n, ok := v.(json.Number)
|
|
if !ok {
|
|
return "-"
|
|
}
|
|
f, err := n.Float64()
|
|
if err != nil || f < 0 {
|
|
return "-"
|
|
}
|
|
if f < 1024 {
|
|
return fmt.Sprintf("%d B", int64(f))
|
|
}
|
|
for _, unit := range []string{"KiB", "MiB", "GiB", "TiB"} {
|
|
f /= 1024
|
|
if f < 1024 || unit == "TiB" {
|
|
return fmt.Sprintf("%.1f %s", f, unit)
|
|
}
|
|
}
|
|
return "-"
|
|
}
|
|
|
|
func backupFlagged(job map[string]any) bool {
|
|
state, _ := job["state"].(string)
|
|
overdue, _ := job["overdue"].(bool)
|
|
return state == "failed" || state == "never_succeeded" || overdue
|
|
}
|
|
|
|
// Backups fetches /v1/backups and prints one block per job. Exit 1 when any job is failed, never_succeeded or
|
|
// overdue (running is not flagged), like fleetctl backups.
|
|
func Backups(ctx context.Context, c *Client, w io.Writer, asJSON bool) (int, error) {
|
|
env, err := c.Backups(ctx)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
data := obj(env.Raw["data"])
|
|
jobs := map[string]any{}
|
|
if status, _ := data["status"].(string); status == "ok" {
|
|
if m, ok := data["jobs"].(map[string]any); ok {
|
|
jobs = m
|
|
}
|
|
}
|
|
code := ExitOK
|
|
for _, j := range jobs {
|
|
if m, ok := j.(map[string]any); ok && backupFlagged(m) {
|
|
code = ExitDrift
|
|
}
|
|
}
|
|
if asJSON {
|
|
return code, WriteJSON(w, env.Raw)
|
|
}
|
|
if status, _ := data["status"].(string); status != "ok" {
|
|
if status == "" {
|
|
status = "unavailable"
|
|
}
|
|
fmt.Fprintf(w, "backups %s\n", status)
|
|
return ExitOK, nil
|
|
}
|
|
for _, name := range sortedKeys(jobs) {
|
|
job := obj(jobs[name])
|
|
if _, labelled := job["display_state"].(string); labelled {
|
|
writeBackupLine(w, name, job)
|
|
continue
|
|
}
|
|
last := "-"
|
|
if s, _ := job["last_success_at"].(string); s != "" {
|
|
last = s
|
|
}
|
|
fmt.Fprintf(w, "%s %s last_success=%s age_h=%s max_age_h=%s", name, dash(job["state"]), last,
|
|
dash(job["age_h"]), dash(job["max_age_hours"]))
|
|
if overdue, _ := job["overdue"].(bool); overdue {
|
|
fmt.Fprint(w, " OVERDUE")
|
|
}
|
|
if r, _ := job["reason"].(string); r != "" {
|
|
fmt.Fprintf(w, " reason=%s", r)
|
|
}
|
|
fmt.Fprintln(w)
|
|
if p, ok := job["progress"].(map[string]any); ok {
|
|
fmt.Fprintf(w, " progress %s %s/%s received=%s\n", dash(p["dataset"]), dash(p["index"]), dash(p["total"]),
|
|
humanBytes(p["bytes_received"]))
|
|
}
|
|
if p, ok := job["previous"].(map[string]any); ok && job["state"] == "running" {
|
|
status := "-"
|
|
if s, _ := p["status"].(string); s != "" {
|
|
status = s
|
|
}
|
|
fin := "-"
|
|
if s, _ := p["finished_at"].(string); s != "" {
|
|
fin = s
|
|
}
|
|
fmt.Fprintf(w, " previous %s finished %s\n", status, fin)
|
|
}
|
|
items, _ := job["datasets"].([]any)
|
|
for _, it := range items {
|
|
d := obj(it)
|
|
src, tgt, snap := "-", "-", "-"
|
|
if s, _ := d["source"].(string); s != "" {
|
|
src = s
|
|
}
|
|
if s, _ := d["target"].(string); s != "" {
|
|
tgt = s
|
|
}
|
|
if s, _ := d["latest_snapshot_at"].(string); s != "" {
|
|
snap = s
|
|
}
|
|
fmt.Fprintf(w, " %s -> %s rc=%s snapshot=%s\n", src, tgt, dash(d["returncode"]), snap)
|
|
}
|
|
}
|
|
return code, nil
|
|
}
|