diff --git a/README.md b/README.md index 31f1ada..d33264b 100644 --- a/README.md +++ b/README.md @@ -115,15 +115,21 @@ or the [Telegram group](https://t.me/+6UwIu9F4gZQxNjM0). CentOS Stream), Docker mirrors their repository indexes, and PyPI mirrors must list `ansible-core`. - **Distros in blackout mode.** Interzone reads the server's distro and - release and checks that the chosen mirrors carry them before deploying. - The OS package step handles each family the playbook supports: + **Blackout mode picks its mirrors.** Choosing blackout on the Server step + points every source at the defaults above. A deploy then reads the + server's distro, release and architecture and checks the mirrors against + them: PyPI before Ansible is installed, the container registry against + every image the enabled services use, the OS and Docker package mirrors + against the server's release. Wherever the chosen mirror falls short, + interzone switches to the first known mirror that has everything, says so + in the log and saves it on the Server step. The defaults point at infamous.g0th.ir, an [interzone-mirror](https://itsjustadream.g0th.ir/vvvomit/interzone-mirror) that carries what interzone and the playbook install on Debian, Ubuntu - (x86 and ARM), Raspberry Pi OS and Arch. On RHEL-family and Fedora servers, - choose one of the public mirrors below instead. + (x86 and ARM), Raspberry Pi OS and Arch. On RHEL-family and Fedora servers + the deploy switches to one of the public mirrors below. The OS package + step handles each family the playbook supports: | Server | OS packages | Docker | In-country mirror? | |---|---|---|---| diff --git a/internal/config/config.go b/internal/config/config.go index b4c5678..8015ef5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -19,6 +19,7 @@ import ( const ( DefaultPlaybookGit = "https://itsjustadream.g0th.ir/spantaleev/matrix-docker-ansible-deploy" DefaultRegistryPrefix = "mechatok.g0th.ir/" + DefaultRolesGitBase = "https://itsjustadream.g0th.ir/" UpstreamGitHub = "https://github.com/" ) @@ -117,7 +118,7 @@ func Default() *Config { Target: Target{Mode: "local", User: "root", Port: "22"}, Sources: Sources{ PlaybookGit: DefaultPlaybookGit, - RolesGitBase: "https://itsjustadream.g0th.ir/", + RolesGitBase: DefaultRolesGitBase, UseRegistry: true, RegistryPrefix: DefaultRegistryPrefix, }, diff --git a/internal/config/mirrors.go b/internal/config/mirrors.go index 5b9359b..ccf0e2a 100644 --- a/internal/config/mirrors.go +++ b/internal/config/mirrors.go @@ -86,6 +86,11 @@ var KnownMirrors = []Mirror{ {MirrorPyPI, "Chabokan", "https://mirror2.chabokan.net/pypi/simple", nil}, } +// KnownRegistries are container registries that carry every registry's +// images under one prefix (/), best first. Blackout +// deploys fall back to them when the chosen registry lacks an image. +var KnownRegistries = []string{DefaultRegistryPrefix} + // Mirrors returns the known mirrors of one kind, best first. func Mirrors(kind MirrorKind) []Mirror { var out []Mirror diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index 1bf93c5..fa60ea1 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -133,17 +133,18 @@ func Plan(a Action) []Step { type Event struct { Plan []Step // the steps of this run; sent first Step Step - Started bool // a step began - Skipped bool // a step was not needed - Warn bool // a step finished with problems that don't stop the run - Line string // a line of command output - Note bool // Line is interzone's own message, not command output - Task string // current Ansible task, when Line starts one - Failed bool // Line reports a failed task - Moved bool // migration: the data is on the new server, which is now the target - Err error // the whole run failed - Done bool // the whole run finished - Result *Result // set with Done + Started bool // a step began + Skipped bool // a step was not needed + Warn bool // a step finished with problems that don't stop the run + Line string // a line of command output + Note bool // Line is interzone's own message, not command output + Task string // current Ansible task, when Line starts one + Failed bool // Line reports a failed task + Moved bool // migration: the data is on the new server, which is now the target + Sources *config.Sources // blackout: the run picked other mirrors; the caller saves them + Err error // the whole run failed + Done bool // the whole run finished + Result *Result // set with Done } // Result is what a finished run produced besides log output. @@ -236,7 +237,9 @@ type Runner struct { // Start launches the run in the background. Events arrive on the returned // channel, which is closed when the run ends. func Start(ctx context.Context, cfg *config.Config, opts Options) <-chan Event { - if opts.Action == ActionMigrate { + // A migration and blackout mirror picks change the run's config; the + // caller applies those changes through events. + if opts.Action == ActionMigrate || cfg.Sources.Blackout { cp := *cfg cfg = &cp } @@ -305,6 +308,9 @@ func (r *Runner) ansible(ctx context.Context) error { return nil } r.begin(StepAnsible) + if !hasWheels(wheelsDir()) { + r.pickPyPI(ctx) + } if err := r.exec(ctx, StepAnsible, "", "python3", "-m", "venv", venvDir()); err != nil { return err } @@ -382,7 +388,15 @@ func (r *Runner) inventory(ctx context.Context) error { if err := os.MkdirAll(hostDir, 0o700); err != nil { return err } + return r.writeInventory(StepInventory) +} +// writeInventory renders vars.yml and hosts from the config; mirror picks +// call it again when they change what vars.yml says. +func (r *Runner) writeInventory(step Step) error { + c := r.cfg + inv := filepath.Join(c.PlaybookDir, "inventory") + hostDir := filepath.Join(inv, "host_vars", c.HostName()) var cert, key string switch c.SSL.Mode { case "selfsigned": @@ -391,7 +405,7 @@ func (r *Runner) inventory(ctx context.Context) error { if err != nil { return fmt.Errorf("self-signed certificate: %w", err) } - r.note(StepInventory, "self-signed certificate: "+cert) + r.note(step, "self-signed certificate: "+cert) case "custom": cert, key = c.SSL.CertPath, c.SSL.KeyPath } @@ -401,7 +415,7 @@ func (r *Runner) inventory(ctx context.Context) error { fixed := *c fixed.Values, fixed.Overrides = maps.Clone(c.Values), maps.Clone(c.Overrides) for _, n := range fixed.RenameOld(c.PlaybookDir) { - r.note(StepInventory, "renamed "+n) + r.note(step, "renamed "+n) } vars := fixed.VarsYAML(config.MigrationVersion(c.PlaybookDir), cert, key) files := map[string]string{ @@ -412,7 +426,7 @@ func (r *Runner) inventory(ctx context.Context) error { if err := os.WriteFile(path, []byte(body), 0o600); err != nil { return err } - r.note(StepInventory, "wrote "+path) + r.note(step, "wrote "+path) } return nil } @@ -430,12 +444,20 @@ func (r *Runner) roles(ctx context.Context) error { } func (r *Runner) mirrors(ctx context.Context) error { + if r.cfg.Sources.Blackout { + r.begin(StepMirrors) + if err := r.pickPackages(ctx); err != nil { + return err + } + } src := r.cfg.Sources if src.APTMirror == "" && src.DockerPackageURL == "" { r.skip(StepMirrors, "no OS or Docker package mirror configured") return nil } - r.begin(StepMirrors) + if !src.Blackout { + r.begin(StepMirrors) + } inv := filepath.Join(r.cfg.PlaybookDir, "inventory") _ = os.Remove(filepath.Join(inv, "interzone-apt-mirror.yml")) // the play before v0.3 vars, err := json.MarshalIndent(mirrorVars(src), "", " ") diff --git a/internal/deploy/images.go b/internal/deploy/images.go index b2f2824..979b829 100644 --- a/internal/deploy/images.go +++ b/internal/deploy/images.go @@ -348,6 +348,14 @@ func shortNetErr(err error) string { // failure: the server may already have them. func (r *Runner) images(ctx context.Context) error { r.begin(StepImages) + if src := &r.cfg.Sources; src.Blackout && (!src.UseRegistry || src.RegistryPrefix == "") { + // Upstream registries are out of reach in a blackout. + src.UseRegistry, src.RegistryPrefix = true, config.DefaultRegistryPrefix + r.picked(StepImages, "Container images", "", src.RegistryPrefix) + if err := r.writeInventory(StepImages); err != nil { + return err + } + } r.note(StepImages, "asking the playbook which images the enabled services use…") imgs, arch, err := ListImages(ctx, r.cfg, false) if err != nil { @@ -362,7 +370,13 @@ func (r *Runner) images(ctx context.Context) error { return nil } r.note(StepImages, fmt.Sprintf("%d images for %s; checking the registries…", len(imgs), arch)) - for _, st := range CheckImages(ctx, imgs, arch) { + statuses := func() []ImageStatus { + if r.cfg.Sources.Blackout { + return r.pickRegistry(ctx, imgs, arch) + } + return CheckImages(ctx, imgs, arch) + }() + for _, st := range statuses { if st.OK { r.result.Images = append(r.result.Images, st.Ref) r.emit(Event{Step: StepImages, Line: "ok: " + st.Ref}) diff --git a/internal/deploy/pick.go b/internal/deploy/pick.go new file mode 100644 index 0000000..48d5f9a --- /dev/null +++ b/internal/deploy/pick.go @@ -0,0 +1,165 @@ +package deploy + +import ( + "context" + "fmt" + "slices" + "strings" + + "interzone/internal/config" +) + +// In blackout mode a run picks its mirrors itself: the one set on the +// Server step if it carries what this server needs, otherwise the first +// known mirror that does. A pick that changes anything is saved back +// through a Sources event. + +// candidates is current followed by the known URLs, without repeats. +func candidates(current string, known []string) []string { + out := []string{} + for _, u := range append([]string{current}, known...) { + if u != "" && !slices.Contains(out, u) { + out = append(out, u) + } + } + return out +} + +func (r *Runner) picked(step Step, what, from, to string) { + if from == to { + return + } + if from == "" { + r.note(step, what+": using "+to) + } else { + r.note(step, fmt.Sprintf("%s: %s doesn't carry everything this server needs; using %s", what, from, to)) + } + src := r.cfg.Sources + r.emit(Event{Step: step, Sources: &src}) +} + +func orNone(s string) string { + if s == "" { + return "no mirror" + } + return s +} + +// pickPyPI picks the PyPI index Ansible is installed from. +func (r *Runner) pickPyPI(ctx context.Context) { + if !r.cfg.Sources.Blackout { + return + } + cur := r.cfg.Sources.PyPIIndex + var known []string + for _, m := range config.Mirrors(config.MirrorPyPI) { + known = append(known, m.URL) + } + for _, u := range candidates(cur, known) { + if _, err := ProbeMirror(ctx, config.MirrorPyPI, u); err == nil { + r.cfg.Sources.PyPIIndex = u + r.env = Env(r.cfg) + r.picked(StepAnsible, "PyPI", cur, u) + return + } + } + r.note(StepAnsible, "! no known PyPI mirror lists ansible-core; trying "+orNone(cur)) +} + +// pickPackages picks the OS and Docker package mirrors for the server's +// distro and release. +func (r *Runner) pickPackages(ctx context.Context) error { + facts, err := probe(ctx, r.cfg) + if err != nil { + r.note(StepMirrors, "! couldn't look at the server to pick mirrors: "+err.Error()) + return nil + } + osNeeds, docker, why := serverNeeds(facts) + if docker != nil && facts["docker"] != "" { + docker = nil // installed already + } + src := &r.cfg.Sources + if why == "" && len(osNeeds) > 0 { + r.pickFor(ctx, config.MirrorOS, &src.APTMirror, osNeeds, facts["arch"]) + } + if docker != nil { + was := src.DockerPackageURL + r.pickFor(ctx, config.MirrorDocker, &src.DockerPackageURL, []need{*docker}, facts["arch"]) + if src.DockerPackageURL != was { + return r.writeInventory(StepMirrors) // vars.yml has docker_repo_url + } + } + return nil +} + +// pickFor sets *url to the first candidate mirror of kind carrying every +// release in needs. +func (r *Runner) pickFor(ctx context.Context, kind config.MirrorKind, url *string, needs []need, arch string) { + what := map[config.MirrorKind]string{config.MirrorOS: "OS packages", config.MirrorDocker: "Docker packages"}[kind] + var known []string + for _, m := range config.Mirrors(kind) { + if slices.ContainsFunc(needs, func(n need) bool { return !slices.Contains(m.Covers, n.distro) }) { + continue + } + known = append(known, m.URL) + } + var names []string + for _, n := range needs { + names = append(names, name(n.distro, n.version)) + } + for _, u := range candidates(*url, known) { + ok := !slices.ContainsFunc(needs, func(n need) bool { + _, err := ProbeDistro(ctx, kind, u, n.distro, n.version, arch) + return err != nil + }) + if ok { + cur := *url + *url = u + r.picked(StepMirrors, what, cur, u) + r.note(StepMirrors, what+": "+u+" carries "+strings.Join(names, ", ")) + return + } + } + r.note(StepMirrors, "! "+what+": no known mirror carries "+strings.Join(names, ", ")+"; keeping "+orNone(*url)) +} + +// pickRegistry checks the images against the registry set on the Server +// step and then the known ones, and keeps the first that has all of them, +// or else the one missing the fewest. imgs are named as vars.yml has them, +// under the current registry prefix. +func (r *Runner) pickRegistry(ctx context.Context, imgs []Image, arch string) []ImageStatus { + src := &r.cfg.Sources + cur := strings.TrimPrefix(strings.TrimPrefix(src.RegistryPrefix, "https://"), "http://") + cur = strings.TrimRight(cur, "/") + "/" + var best []ImageStatus + bestMissing, bestAt := len(imgs)+1, "" + for _, reg := range candidates(cur, config.KnownRegistries) { + moved := make([]Image, len(imgs)) + for i, im := range imgs { + moved[i] = im + moved[i].Ref = reg + strings.TrimPrefix(im.Ref, cur) + } + st := CheckImages(ctx, moved, arch) + missing := 0 + for _, s := range st { + if !s.OK { + missing++ + } + } + r.note(StepImages, fmt.Sprintf("%s has %d of %d images", reg, len(imgs)-missing, len(imgs))) + if missing < bestMissing { + best, bestMissing, bestAt = st, missing, reg + } + if missing == 0 { + break + } + } + if bestAt != cur { + src.RegistryPrefix = bestAt + r.picked(StepImages, "Container images", cur, bestAt) + if err := r.writeInventory(StepImages); err != nil { + r.note(StepImages, "! "+err.Error()) + } + } + return best +} diff --git a/internal/deploy/pick_test.go b/internal/deploy/pick_test.go new file mode 100644 index 0000000..eba3531 --- /dev/null +++ b/internal/deploy/pick_test.go @@ -0,0 +1,62 @@ +package deploy + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + "time" + + "interzone/internal/config" +) + +func TestPickFor(t *testing.T) { + fresh := "Date: " + time.Now().UTC().Format(time.RFC1123) + "\n" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/good/ubuntu/dists/noble-security/Release" { + http.NotFound(w, r) + return + } + w.Write([]byte(fresh)) + })) + defer srv.Close() + defer func(k []config.Mirror) { config.KnownMirrors = k }(config.KnownMirrors) + config.KnownMirrors = []config.Mirror{ + {Kind: config.MirrorOS, URL: srv.URL + "/debian-only", Covers: []string{config.Debian}}, + {Kind: config.MirrorOS, URL: srv.URL + "/empty", Covers: []string{config.Ubuntu}}, + {Kind: config.MirrorOS, URL: srv.URL + "/good", Covers: []string{config.Ubuntu}}, + } + needs := []need{{config.Ubuntu, "noble"}} + + for _, tc := range []struct{ set, want string }{ + {srv.URL + "/broken", srv.URL + "/good"}, // the set one lacks it: the first known one that has it + {srv.URL + "/good", srv.URL + "/good"}, + {"", srv.URL + "/good"}, + } { + c := config.Default() + c.Sources.Blackout, c.Sources.APTMirror = true, tc.set + r := &Runner{cfg: c, events: make(chan Event, 64)} + r.pickFor(context.Background(), config.MirrorOS, &c.Sources.APTMirror, needs, "x86_64") + if c.Sources.APTMirror != tc.want { + t.Errorf("set %q: picked %q, want %q", tc.set, c.Sources.APTMirror, tc.want) + } + saved := false + for len(r.events) > 0 { + if (<-r.events).Sources != nil { + saved = true + } + } + if saved != (tc.set != tc.want) { + t.Errorf("set %q: Sources event sent = %v", tc.set, saved) + } + } + + // nothing carries it: the set one stays + c := config.Default() + c.Sources.APTMirror = srv.URL + "/broken" + r := &Runner{cfg: c, events: make(chan Event, 64)} + r.pickFor(context.Background(), config.MirrorOS, &c.Sources.APTMirror, []need{{config.Ubuntu, "jammy"}}, "x86_64") + if c.Sources.APTMirror != srv.URL+"/broken" { + t.Errorf("with no mirror carrying it, picked %q", c.Sources.APTMirror) + } +} diff --git a/internal/ui/blackout_test.go b/internal/ui/blackout_test.go new file mode 100644 index 0000000..befd125 --- /dev/null +++ b/internal/ui/blackout_test.go @@ -0,0 +1,39 @@ +package ui + +import ( + "testing" + + tea "github.com/charmbracelet/bubbletea" + + "interzone/internal/config" +) + +// Choosing blackout points every download back at the in-country mirrors. +func TestBlackoutSources(t *testing.T) { + a := demoApp(t, 120, 36) + a.jump(a.index("Server")) + s := a.cur().(*serverScreen) + f := s.form + f.get("net").choice = 0 + f.get("useRegistry").on = false + f.get("registry").input.SetValue("elsewhere.example/") + f.get("git").input.SetValue("https://github.com/spantaleev/matrix-docker-ansible-deploy") + for i, fl := range f.fields { + if fl.key == "net" { + f.focusOn(i) + } + } + press(a, tea.KeyMsg{Type: tea.KeyRight}) + if f.value("net") != "blackout" { + t.Fatalf("net = %q", f.value("net")) + } + for k, want := range map[string]string{ + "useRegistry": "true", "registry": config.DefaultRegistryPrefix, "git": config.DefaultPlaybookGit, + "roles": config.DefaultRolesGitBase, "apt": config.SelfHostedMirror, + "dockerpkg": config.SelfHostedMirror + "/docker", "pypi": config.SelfHostedMirror + "/pypi/simple", + } { + if got := f.value(k); got != want { + t.Errorf("%s = %q, want %q", k, got, want) + } + } +} diff --git a/internal/ui/screens_deploy.go b/internal/ui/screens_deploy.go index 52a3d4a..a7096b2 100644 --- a/internal/ui/screens_deploy.go +++ b/internal/ui/screens_deploy.go @@ -669,6 +669,10 @@ func (s *deployScreen) handle(ev deploy.Event) { s.backAt = time.Now().Add(autoBackDelay) } return + case ev.Sources != nil: + s.cfg.Sources = *ev.Sources + _ = s.cfg.Save() + return case ev.Moved: // The data now lives on the new server: from here on it is the // server, even if a later step fails. diff --git a/internal/ui/screens_setup.go b/internal/ui/screens_setup.go index f232084..b974066 100644 --- a/internal/ui/screens_setup.go +++ b/internal/ui/screens_setup.go @@ -213,7 +213,7 @@ func (s *serverScreen) enter(c *config.Config) tea.Cmd { choiceField("net", "Network situation", []string{"online", "blackout"}, []string{"Normal internet", "Blackout: in-country mirrors only"}, netMode, - "Blackout mode adds mirrors for Docker Engine, OS packages and PyPI."), + "Blackout points every download at in-country mirrors. Before deploying, interzone checks them against the server and the images it needs and switches to another known mirror where one falls short."), textField("git", "Playbook git repository", src.PlaybookGit, config.DefaultPlaybookGit, "Where matrix-docker-ansible-deploy is cloned from."), textField("roles", "Git mirror for Ansible roles", src.RolesGitBase, "https://github.com/", @@ -259,6 +259,21 @@ func (s *serverScreen) enter(c *config.Config) tea.Cmd { return nil } +// blackoutSources points every download at the in-country mirrors when +// blackout mode is chosen; the deploy then swaps in another known mirror +// wherever one lacks something the server needs. +func (s *serverScreen) blackoutSources() { + f := s.form + for k, v := range map[string]string{ + "git": config.DefaultPlaybookGit, "roles": config.DefaultRolesGitBase, "registry": config.DefaultRegistryPrefix, + "dockerpkg": config.DefaultMirror(config.MirrorDocker), "apt": config.DefaultMirror(config.MirrorOS), + "pypi": config.DefaultMirror(config.MirrorPyPI), + } { + f.get(k).input.SetValue(v) + } + f.get("useRegistry").on = true +} + // explainSSL makes the certificate choice's help describe the picked one. func (s *serverScreen) explainSSL() { mode := s.form.value("ssl") @@ -351,7 +366,11 @@ func (s *serverScreen) update(msg tea.Msg) tea.Cmd { return tea.Batch(s.spin.Tick, func() tea.Msg { return checksMsg(deploy.Preflight(cfg)) }) } } + was := s.form.value("net") cmd := s.form.Update(msg) + if was != "blackout" && s.form.value("net") == "blackout" { + s.blackoutSources() + } s.cfg.Sources.Blackout = s.form.value("net") == "blackout" // keeps the header badge live s.explainSSL() return cmd