package app // Import of a 1.x data directory into a 2.0 hub (see docs/migration-2.0.md). // // The rule that shapes everything here: no byte registered in production may // be lost. So the import never merges, never rewrites and never deletes: it // copies the whole directory (every file, known or not) into the node // directory of the probe, byte for byte, and proves the copy with sha256 of // every file plus counts loaded with the real store, evlog and incident code. import ( "bufio" "bytes" "compress/gzip" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "flag" "fmt" "io" "io/fs" "os" "path/filepath" "sort" "strings" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire" ) // ManifestName is the proof of a finished import, written inside the node // directory (and so renamed into place together with the data). const ManifestName = "import-manifest.json" // lockName is the lock the hub holds on its data directory while it runs. const lockName = ".lock" // ImportOptions tune Import. type ImportOptions struct { // DryRun reads and compares everything but writes nothing at all. DryRun bool // Force replaces a divergent destination by moving it to .bak- // (it is never deleted). Force bool // IncludeGeo also copies geo/ (the databases are re-downloaded by the hub, // so by default they are skipped with a warning). IncludeGeo bool } // FileCopy is one entry of the copy. type FileCopy struct { Path string `json:"path"` // relative, slash separated Kind string `json:"kind"` // file, dir or symlink Size int64 `json:"size"` // bytes (files) Mode uint32 `json:"mode"` // permission bits MTime int64 `json:"mtime_ns"` // modification time, unix ns SHA256 string `json:"sha256,omitempty"` // files: content; symlinks: of the target text Target string `json:"target,omitempty"` // symlinks } // Counts is what a data directory holds, measured by loading it with the real // code of the 1.x store, evlog and incidents. type Counts struct { Events int `json:"events"` // lines of events/*.jsonl and *.jsonl.gz EventFiles int `json:"event_files"` // day files in events/ IPs int `json:"ips"` // addresses of the snapshot Offsets int `json:"offsets"` // saved read positions of the snapshot Incidents int `json:"incidents"` // tickets of incidents.json Comments int `json:"comments"` // comments over all tickets Suppressed int `json:"suppressed"` // tickets with an active suppression EnforceBans int `json:"enforce_bans"` // bans (with history) of enforce.json EnforceAllow int `json:"enforce_allow"` // allows of enforce.json } // ImportReport is the result of Import and VerifyImport. type ImportReport struct { Counts Files []FileCopy `json:"files"` Skipped bool `json:"skipped"` // already imported, nothing done DryRun bool `json:"dry_run"` // nothing was written Dest string `json:"dest"` // node directory Backup string `json:"backup,omitempty"` // where --force moved the old destination Warnings []string `json:"warnings,omitempty"` } type manifest struct { Version int `json:"version"` Host string `json:"host"` From string `json:"from"` ImportedAt string `json:"imported_at"` Files []FileCopy `json:"files"` Counts Counts `json:"counts"` } // importDest is where the files of a probe live: /probes/. func importDest(dataDir, host string) string { return NodeDir(dataDir, host, false) } // FormatCounts is the stable text of `urutau import --count`. func FormatCounts(c Counts) string { return fmt.Sprintf("events=%d event_files=%d ips=%d offsets=%d incidents=%d comments=%d suppressed=%d enforce_bans=%d enforce_allow=%d\n", c.Events, c.EventFiles, c.IPs, c.Offsets, c.Incidents, c.Comments, c.Suppressed, c.EnforceBans, c.EnforceAllow) } // --------------------------------------------------------------------------- // counting // CountDir loads a data directory read-only and counts what is in it. The // directory is never modified: the incident store is opened on a private copy // because Open renames a corrupt file. func CountDir(dir string) (Counts, error) { var c Counts fi, err := os.Stat(dir) if err != nil { return c, err } if !fi.IsDir() { return c, fmt.Errorf("%s is not a directory", dir) } // snapshot, with the real store code (no IP cap: the snapshot is measured, not trimmed) snap := SnapshotPath(dir) if _, err := os.Stat(snap); err == nil { st := store.New(store.Config{Name: "count", MaxIPs: 1 << 30}) offs, err := st.Load(snap) if err != nil { return c, fmt.Errorf("snapshot %s: %w", snap, err) } c.IPs, c.Offsets = st.IPCount(), len(offs) } // event registry ents, err := os.ReadDir(filepath.Join(dir, "events")) if err != nil && !errors.Is(err, os.ErrNotExist) { return c, err } for _, e := range ents { n := e.Name() if e.IsDir() || !(strings.HasSuffix(n, ".jsonl") || strings.HasSuffix(n, ".jsonl.gz")) { continue } k, err := countLines(filepath.Join(dir, "events", n), strings.HasSuffix(n, ".gz")) if err != nil { return c, fmt.Errorf("events/%s: %w", n, err) } c.Events += k c.EventFiles++ } // incidents, with the real incident code on a private copy if b, err := os.ReadFile(filepath.Join(dir, "incidents.json")); err == nil { if !json.Valid(b) { return c, errors.New("incidents.json is not valid JSON") } tmp, err := os.MkdirTemp("", "urutau-count-") if err != nil { return c, err } defer os.RemoveAll(tmp) p := filepath.Join(tmp, "incidents.json") if err := os.WriteFile(p, b, 0o600); err != nil { return c, err } is, err := incidents.Open(p, nil) if err != nil { return c, err } c.Incidents = is.Stats().Size now := time.Now().Unix() for _, s := range is.All(incidents.Query{}) { c.Comments += s.CommentCount if s.Suppress && (s.SuppressUntil == 0 || s.SuppressUntil > now) { c.Suppressed++ } } } else if !errors.Is(err, os.ErrNotExist) { return c, err } // enforce.json (ban history) if b, err := os.ReadFile(filepath.Join(dir, "enforce.json")); err == nil { var sf struct { Bans map[string]json.RawMessage `json:"bans"` Allows map[string]json.RawMessage `json:"allows"` } if err := json.Unmarshal(b, &sf); err != nil { return c, fmt.Errorf("enforce.json: %w", err) } c.EnforceBans, c.EnforceAllow = len(sf.Bans), len(sf.Allows) } else if !errors.Is(err, os.ErrNotExist) { return c, err } return c, nil } func countLines(path string, gz bool) (int, error) { f, err := os.Open(path) if err != nil { return 0, err } defer f.Close() var r io.Reader = f if gz { zr, err := gzip.NewReader(f) if err != nil { return 0, err } defer zr.Close() r = zr } br := bufio.NewReaderSize(r, 256*1024) n := 0 for { line, err := br.ReadBytes('\n') if len(bytes.TrimSpace(line)) > 0 { n++ } if err == io.EOF { return n, nil } if err != nil { return n, err } } } // --------------------------------------------------------------------------- // tree type tree struct { entries []FileCopy warnings []string } // scanTree lists root (without hashes). Symlinks are kept as symlinks and // never followed; sockets and devices are skipped with a warning. func scanTree(root string, includeGeo, dest bool) (*tree, error) { t := &tree{} err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { if err != nil { return err } rel, _ := filepath.Rel(root, p) if rel == "." { return nil } rel = filepath.ToSlash(rel) top := strings.SplitN(rel, "/", 2)[0] switch { case rel == lockName: t.warnings = append(t.warnings, ".lock of the source is not copied") return nil case rel == ManifestName && dest: t.entries = append(t.entries, FileCopy{Path: rel, Kind: "file"}) return nil case rel == ManifestName: return fmt.Errorf("the source already holds %s: it is an import destination, not a 1.x data directory", ManifestName) case top == "geo" && !includeGeo: if rel == "geo" { t.warnings = append(t.warnings, "geo/ skipped (the hub downloads its own databases; use --include-geo to copy it)") } if d.IsDir() { return fs.SkipDir } return nil } fi, err := d.Info() if err != nil { return err } e := FileCopy{Path: rel, Mode: uint32(fi.Mode().Perm()), MTime: fi.ModTime().UnixNano(), Size: fi.Size()} switch m := fi.Mode(); { case m.IsDir(): e.Kind, e.Size = "dir", 0 case m.IsRegular(): e.Kind = "file" case m&fs.ModeSymlink != 0: tg, err := os.Readlink(p) if err != nil { return err } sum := sha256.Sum256([]byte(tg)) e.Kind, e.Target, e.SHA256, e.Size = "symlink", tg, hex.EncodeToString(sum[:]), 0 default: t.warnings = append(t.warnings, fmt.Sprintf("%s: special file skipped", rel)) return nil } t.entries = append(t.entries, e) return nil }) sort.Slice(t.entries, func(i, j int) bool { return t.entries[i].Path < t.entries[j].Path }) return t, err } func hashFile(path string) (string, int64, error) { f, err := os.Open(path) if err != nil { return "", 0, err } defer f.Close() h := sha256.New() n, err := io.Copy(h, f) return hex.EncodeToString(h.Sum(nil)), n, err } // hashTree fills the sha256 of every regular file of t. func hashTree(root string, t *tree) error { for i := range t.entries { e := &t.entries[i] if e.Kind != "file" { continue } sum, n, err := hashFile(filepath.Join(root, filepath.FromSlash(e.Path))) if err != nil { return err } e.SHA256, e.Size = sum, n } return nil } // sameContent compares what the files hold (path, kind, size, hash, target). func sameContent(a, b []FileCopy) []string { bm := make(map[string]FileCopy, len(b)) for _, e := range b { bm[e.Path] = e } var diff []string seen := map[string]bool{} for _, x := range a { seen[x.Path] = true y, ok := bm[x.Path] switch { case !ok: diff = append(diff, "missing: "+x.Path) case x.Kind != y.Kind: diff = append(diff, "kind differs: "+x.Path) case x.SHA256 != y.SHA256 || x.Size != y.Size || x.Target != y.Target: diff = append(diff, "content differs: "+x.Path) } } for _, y := range b { if !seen[y.Path] { diff = append(diff, "extra: "+y.Path) } } sort.Strings(diff) return diff } // sameMeta compares mode and mtime (files and dirs; symlinks have no own mtime we keep). func sameMeta(a, b []FileCopy) []string { bm := make(map[string]FileCopy, len(b)) for _, e := range b { bm[e.Path] = e } var diff []string for _, x := range a { if x.Kind == "symlink" { continue } if y, ok := bm[x.Path]; ok && (x.Mode != y.Mode || x.MTime != y.MTime) { diff = append(diff, "mode or mtime differs: "+x.Path) } } return diff } // --------------------------------------------------------------------------- // import func checkArgs(from, dataDir, host string) (src, dst string, err error) { if !wire.ValidName(host) { return "", "", fmt.Errorf("invalid host name %q (lowercase letters, digits and dashes, up to 32)", host) } if src, err = filepath.Abs(from); err != nil { return } fi, serr := os.Stat(src) if serr != nil { return "", "", serr } if !fi.IsDir() { return "", "", fmt.Errorf("--from %s is not a directory", from) } dd, err := filepath.Abs(dataDir) if err != nil { return } dst = importDest(dd, host) if within(src, dd) || within(dd, src) { return "", "", fmt.Errorf("--from %s and the data dir %s must not contain one another", src, dd) } return src, dst, nil } func within(a, b string) bool { r, err := filepath.Rel(b, a) return err == nil && (r == "." || (r != ".." && !strings.HasPrefix(r, ".."+string(filepath.Separator)))) } // Import copies the whole 1.x data directory `from` into the node directory of // `host` under dataDir and verifies the copy. See the package comment. func Import(from, dataDir, host string, opt ImportOptions) (ImportReport, error) { rep := ImportReport{DryRun: opt.DryRun} src, dst, err := checkArgs(from, dataDir, host) if err != nil { return rep, err } dataDir, _ = filepath.Abs(dataDir) rep.Dest = dst lock := filepath.Join(dataDir, lockName) if _, err := os.Lstat(lock); err == nil { return rep, fmt.Errorf("%s exists: the hub (or another import) is running on this data dir; stop it first (if it is stale, remove the file)", lock) } // read the source twice, around the copy, to catch a writer t, err := scanTree(src, opt.IncludeGeo, false) if err != nil { return rep, err } rep.Warnings = append(rep.Warnings, t.warnings...) if err := hashTree(src, t); err != nil { return rep, err } rep.Files = t.entries srcCounts, err := CountDir(src) if err != nil { return rep, fmt.Errorf("source does not load: %w", err) } rep.Counts = srcCounts // destination state if _, err := os.Lstat(dst); err == nil { prev, merr := readManifest(dst) if merr == nil && len(sameContent(t.entries, prev.Files)) == 0 { rep.Skipped = true if cur, err := scanTree(dst, true, true); err == nil { _ = hashTree(dst, cur) if d := sameContent(prev.Files, dropManifest(cur.entries)); len(d) > 0 { rep.Warnings = append(rep.Warnings, fmt.Sprintf("destination changed since the import (%d files; the hub already ran?); nothing was touched", len(d))) } } return rep, nil } if !opt.Force { return rep, fmt.Errorf("%s already exists with different content (or no manifest); nothing was changed. Compare with --verify, or use --force to move it to %s.bak- (never deleted)", dst, dst) } } else if !errors.Is(err, os.ErrNotExist) { return rep, err } if opt.DryRun { return rep, nil } // from here on we write: take the data-dir lock so the hub cannot start in the middle if err := os.MkdirAll(dataDir, 0o700); err != nil { return rep, err } lf, err := os.OpenFile(lock, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return rep, fmt.Errorf("cannot take %s: %w", lock, err) } fmt.Fprintf(lf, "import pid=%d\n", os.Getpid()) lf.Close() defer os.Remove(lock) parent := filepath.Dir(dst) if err := os.MkdirAll(parent, 0o700); err != nil { return rep, err } stamp := time.Now().UTC().Format("20060102T150405") tmp := filepath.Join(parent, fmt.Sprintf(".import-%s-%d.tmp", host, os.Getpid())) if err := os.RemoveAll(tmp); err != nil { // our own leftover of this very pid return rep, err } ok := false defer func() { if !ok { os.RemoveAll(tmp) } }() if err := copyTree(src, tmp, t.entries); err != nil { return rep, err } // verify the copy: hashes of what was written, counts through the real loaders, and the source unchanged got, err := scanTree(tmp, true, true) if err != nil { return rep, err } if err := hashTree(tmp, got); err != nil { return rep, err } if d := sameContent(t.entries, got.entries); len(d) > 0 { return rep, fmt.Errorf("copy verification failed (%d differences, first: %s); nothing was installed", len(d), d[0]) } if d := sameMeta(t.entries, got.entries); len(d) > 0 { return rep, fmt.Errorf("copy verification failed (%s); nothing was installed", d[0]) } dstCounts, err := CountDir(tmp) if err != nil { return rep, fmt.Errorf("copy does not load: %w", err) } if dstCounts != srcCounts { return rep, fmt.Errorf("counts differ after the copy: source %+v, copy %+v; nothing was installed", srcCounts, dstCounts) } after, err := scanTree(src, opt.IncludeGeo, false) if err != nil { return rep, err } if err := hashTree(src, after); err != nil { return rep, err } if d := sameContent(t.entries, after.entries); len(d) > 0 { return rep, fmt.Errorf("the source changed while it was being copied (%s): stop the 1.x instance and run again; nothing was installed", d[0]) } m := manifest{Version: 1, Host: host, From: src, ImportedAt: time.Now().UTC().Format(time.RFC3339), Files: t.entries, Counts: srcCounts} mb, _ := json.MarshalIndent(m, "", " ") if err := writeFileSync(filepath.Join(tmp, ManifestName), mb, 0o600); err != nil { return rep, err } syncDir(tmp) if opt.Force { if _, err := os.Lstat(dst); err == nil { bak := dst + ".bak-" + stamp for i := 2; ; i++ { // never overwrite an earlier backup if _, err := os.Lstat(bak); errors.Is(err, os.ErrNotExist) { break } bak = fmt.Sprintf("%s.bak-%s-%d", dst, stamp, i) } if err := os.Rename(dst, bak); err != nil { return rep, err } rep.Backup = bak } } if err := os.Rename(tmp, dst); err != nil { return rep, err } ok = true syncDir(parent) return rep, nil } func dropManifest(in []FileCopy) []FileCopy { out := make([]FileCopy, 0, len(in)) for _, e := range in { if e.Path != ManifestName { out = append(out, e) } } return out } func readManifest(dir string) (manifest, error) { var m manifest b, err := os.ReadFile(filepath.Join(dir, ManifestName)) if err != nil { return m, err } return m, json.Unmarshal(b, &m) } // copyTree copies entries (already listed under src) to dst, preserving mode // and mtime. Directories get their times last, children first. func copyTree(src, dst string, entries []FileCopy) error { if err := os.MkdirAll(dst, 0o700); err != nil { return err } var dirs []FileCopy for _, e := range entries { from, to := filepath.Join(src, filepath.FromSlash(e.Path)), filepath.Join(dst, filepath.FromSlash(e.Path)) switch e.Kind { case "dir": if err := os.MkdirAll(to, 0o700); err != nil { return err } dirs = append(dirs, e) case "symlink": if err := os.Symlink(e.Target, to); err != nil { return err } case "file": if err := copyFile(from, to, e); err != nil { return fmt.Errorf("%s: %w", e.Path, err) } } } for i := len(dirs) - 1; i >= 0; i-- { e := dirs[i] to := filepath.Join(dst, filepath.FromSlash(e.Path)) if err := os.Chmod(to, fs.FileMode(e.Mode)); err != nil { return err } syncDir(to) if err := os.Chtimes(to, time.Unix(0, e.MTime), time.Unix(0, e.MTime)); err != nil { return err } } return nil } func copyFile(from, to string, e FileCopy) error { in, err := os.Open(from) if err != nil { return err } defer in.Close() out, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return err } _, err = io.Copy(out, in) if err == nil { err = out.Sync() } if cerr := out.Close(); err == nil { err = cerr } if err != nil { return err } if err := os.Chmod(to, fs.FileMode(e.Mode)); err != nil { return err } return os.Chtimes(to, time.Unix(0, e.MTime), time.Unix(0, e.MTime)) } func writeFileSync(path string, b []byte, mode fs.FileMode) error { f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode) if err != nil { return err } _, err = f.Write(b) if err == nil { err = f.Sync() } if cerr := f.Close(); err == nil { err = cerr } return err } func syncDir(p string) { if f, err := os.Open(p); err == nil { _ = f.Sync() f.Close() } } // --------------------------------------------------------------------------- // verify // VerifyImport compares the source with the imported node directory (it // writes nothing): sha256, size, mode and mtime of every file, then the counts. // Run it before the hub starts on the destination; once the hub runs, its // files change by design. func VerifyImport(from, dataDir, host string) (ImportReport, error) { rep := ImportReport{DryRun: true} src, dst, err := checkArgs(from, dataDir, host) if err != nil { return rep, err } rep.Dest = dst m, err := readManifest(dst) if err != nil { return rep, fmt.Errorf("%s has no readable %s (not imported yet?): %w", dst, ManifestName, err) } // geo/ was in the copy iff the manifest lists it withGeo := false for _, e := range m.Files { if e.Path == "geo" || strings.HasPrefix(e.Path, "geo/") { withGeo = true break } } s, err := scanTree(src, withGeo, false) if err != nil { return rep, err } rep.Warnings = append(rep.Warnings, s.warnings...) if err := hashTree(src, s); err != nil { return rep, err } d, err := scanTree(dst, true, true) if err != nil { return rep, err } if err := hashTree(dst, d); err != nil { return rep, err } rep.Files = s.entries var bad []string bad = append(bad, sameContent(s.entries, dropManifest(d.entries))...) bad = append(bad, sameMeta(s.entries, d.entries)...) sc, err := CountDir(src) if err != nil { return rep, err } rep.Counts = sc dc, err := CountDir(dst) if err != nil { return rep, err } if sc != dc { bad = append(bad, fmt.Sprintf("counts differ: source %+v, destination %+v", sc, dc)) } if len(bad) > 0 { n := len(bad) if n > 10 { bad = append(bad[:10], fmt.Sprintf("... and %d more", n-10)) } return rep, fmt.Errorf("verification FAILED (%d problems):\n %s", n, strings.Join(bad, "\n ")) } return rep, nil } // --------------------------------------------------------------------------- // command line // ImportCLI runs `urutau import ...` (args after the word "import") and // returns the exit code. // // urutau import --from DIR --host NAME [--data-dir D] [--dry-run] [--force] [--include-geo] // urutau import --verify --from DIR --host NAME [--data-dir D] // urutau import --count DIR func ImportCLI(args []string, out, errw io.Writer) int { fs := flag.NewFlagSet("import", flag.ContinueOnError) fs.SetOutput(errw) from := fs.String("from", "", "1.x data directory to import (stopped instance)") host := fs.String("host", "", "name of the probe that receives it") dataDir := fs.String("data-dir", env("URUTAU_DATA_DIR", "/data"), "hub data directory (URUTAU_DATA_DIR)") dry := fs.Bool("dry-run", false, "compare and report, write nothing") force := fs.Bool("force", false, "move a divergent destination to .bak- (never deleted)") geo := fs.Bool("include-geo", false, "also copy geo/") verify := fs.Bool("verify", false, "only compare --from with the imported copy") count := fs.String("count", "", "print the counts of this data directory and exit") if err := fs.Parse(args); err != nil { return 2 } if *count != "" { c, err := CountDir(*count) if err != nil { fmt.Fprintln(errw, "error:", err) return 1 } fmt.Fprint(out, FormatCounts(c)) return 0 } if *from == "" || *host == "" { fmt.Fprintln(errw, "usage: urutau import --from DIR --host NAME [--data-dir D] [--dry-run] [--force] [--include-geo] | --verify ... | --count DIR") return 2 } if *verify { rep, err := VerifyImport(*from, *dataDir, *host) for _, w := range rep.Warnings { fmt.Fprintln(errw, "warning:", w) } if err != nil { fmt.Fprintln(errw, "error:", err) return 1 } fmt.Fprintf(out, "verified: %d files identical (sha256, mode, mtime) in %s\n%s", len(rep.Files), rep.Dest, FormatCounts(rep.Counts)) return 0 } rep, err := Import(*from, *dataDir, *host, ImportOptions{DryRun: *dry, Force: *force, IncludeGeo: *geo}) for _, w := range rep.Warnings { fmt.Fprintln(errw, "warning:", w) } if err != nil { fmt.Fprintln(errw, "error:", err) return 1 } switch { case rep.Skipped: fmt.Fprintf(out, "already imported into %s, nothing done\n", rep.Dest) case rep.DryRun: fmt.Fprintf(out, "dry run: %d entries would be copied to %s\n", len(rep.Files), rep.Dest) default: fmt.Fprintf(out, "imported %d entries into %s\n", len(rep.Files), rep.Dest) if rep.Backup != "" { fmt.Fprintf(out, "previous destination kept at %s\n", rep.Backup) } } fmt.Fprint(out, FormatCounts(rep.Counts)) return 0 }