Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions cmd/internal/cliext/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,29 +40,41 @@ func WithConfigFlag(cmd *cli.Command) *cli.Command {
})

cmd.Before = WrapBeforeFuncs(cmd.Before, func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
var (
cfg *config.Config
err error
)
if cfgPath := cmd.String("config"); cfgPath != "" {
cfg, err = config.LoadPath(cfgPath)
} else {
cfg, err = config.Load()
}
cfg, err := LoadConfig(cmd)
if err != nil {
return nil, err
}
// Replace the in-memory config option with --cache-dir if the user
// explicitly requested it.
if cmd.IsSet("cache-dir") {
cfg.CacheDir = cmd.String("cache-dir")
}
return WithCtxConfig(ctx, cfg), nil
})

return cmd
}

// LoadConfig reads the configuration selected by the flags from
// [WithConfigFlag]. Most users want [CtxConfig], which is the configuration
// as it was when the command started. This is for commands that can outlive
// a change to the configuration files.
func LoadConfig(cmd *cli.Command) (*config.Config, error) {
var (
cfg *config.Config
err error
)
if cfgPath := cmd.String("config"); cfgPath != "" {
cfg, err = config.LoadPath(cfgPath)
} else {
cfg, err = config.Load()
}
if err != nil {
return nil, err
}
// Replace the in-memory config option with --cache-dir if the user
// explicitly requested it.
if cmd.IsSet("cache-dir") {
cfg.CacheDir = cmd.String("cache-dir")
}
return cfg, nil
}

// CtxConfig returns the parsed --config flag value for [cli.Command]s
// configured using [WithConfigFlag].
func CtxConfig(ctx context.Context) *config.Config {
Expand Down
232 changes: 127 additions & 105 deletions cmd/quarry-sysupdate/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ import (
"context"
"fmt"
"log/slog"
"maps"
"slices"

"github.com/urfave/cli/v3"

"go.amutable.dev/quarry/cmd/internal/cliext"
"go.amutable.dev/quarry/internal/hostnamed"
"go.amutable.dev/quarry/internal/third_party/assert"
"go.amutable.dev/quarry/internal/tufclient"
Expand All @@ -20,115 +22,126 @@ import (
// Same cap as systemd-sysupdate-update.service (--loop=16).
const maxUpdateIterations = 16

var updateCommand = withExtensionDirFlag(withQuarryUserFlag(withQuarryProxyFlag(&cli.Command{
Name: "update",
Usage: "extended 'systemd-sysupdate update' wrapper",
Action: func(ctx context.Context, _ *cli.Command) (Err error) {
exts := xsysupdate.ExtensionSet{
&xsysupdate.TransferFileExtension{
OverrideSourcePathURL: ctxQuarryProxyURL(ctx),
},
}
ctx, err := exts.DoInit(ctx)
if err != nil {
return fmt.Errorf("init extensions: %w", err)
}
slog.Info("Initialised extensions.",
"extensions", exts.String())
// Legacy-prefixed targets are only applied after all other targets so
// we can allow them to be overridden by the non-legacy prefix.
// TODO: Drop this.
var (
applied = map[string]struct{}{} // uses the stripped name
legacyTargets []*tufclient.TargetInfo
)
applyTarget := func(target *tufclient.TargetInfo) error {
slog.Info("Extension target found.",
"target", target.Path, "repository", target.Repo.Name)
name, legacy, ok := xsysupdate.CutExtensionTargetPrefix(target.Path)
assert.Assertf(ok, "extension target path %q must have extension prefix", target.Path)
if _, ok := applied[name]; ok {
slog.Info("Skipping legacy extension target superseded by new prefix.",
"target", target.Path, "repository", target.Repo.Name)
assert.Assertf(!legacy, "extension target path %q must not be applied after legacy paths", target.Path)
return nil
}
if err := exts.DoApplyTarget(ctx, target); err != nil {
return fmt.Errorf("apply extension target %s: %w", target.Path, err)
}
applied[name] = struct{}{}
slog.Info("Extension target applied.",
// updatePass applies the extension targets of all configured repositories and
// then runs sysupdate for every enabled component.
func updatePass(ctx context.Context) error {
exts := xsysupdate.ExtensionSet{
&xsysupdate.TransferFileExtension{
OverrideSourcePathURL: ctxQuarryProxyURL(ctx),
},
}
ctx, err := exts.DoInit(ctx)
if err != nil {
return fmt.Errorf("init extensions: %w", err)
}
slog.Info("Initialised extensions.",
"extensions", exts.String())
// Legacy-prefixed targets are only applied after all other targets so
// we can allow them to be overridden by the non-legacy prefix.
// TODO: Drop this.
var (
applied = map[string]struct{}{} // uses the stripped name
legacyTargets []*tufclient.TargetInfo
)
applyTarget := func(target *tufclient.TargetInfo) error {
slog.Info("Extension target found.",
"target", target.Path, "repository", target.Repo.Name)
name, legacy, ok := xsysupdate.CutExtensionTargetPrefix(target.Path)
assert.Assertf(ok, "extension target path %q must have extension prefix", target.Path)
if _, ok := applied[name]; ok {
slog.Info("Skipping legacy extension target superseded by new prefix.",
"target", target.Path, "repository", target.Repo.Name)
assert.Assertf(!legacy, "extension target path %q must not be applied after legacy paths", target.Path)
return nil
}
for target, err := range unprivIterTargetFiles(ctx) {
if err != nil {
return fmt.Errorf("error while scanning repos: %w", err)
}
if _, legacy, ok := xsysupdate.CutExtensionTargetPrefix(target.Path); !ok {
// Not an extension target file.
continue
} else if legacy {
// Defer application of legacy-prefixed extensions until we've
// done everything else so we can skip them if there was a
// non-legacy version of the same file.
legacyTargets = append(legacyTargets, target)
continue
}
// Otherwise, apply the extension target file.
if err := applyTarget(target); err != nil {
return err
}
if err := exts.DoApplyTarget(ctx, target); err != nil {
return fmt.Errorf("apply extension target %s: %w", target.Path, err)
}
for _, target := range legacyTargets {
if err := applyTarget(target); err != nil {
return err
}
applied[name] = struct{}{}
slog.Info("Extension target applied.",
"target", target.Path, "repository", target.Repo.Name)
return nil
}
for target, err := range unprivIterTargetFiles(ctx) {
if err != nil {
return fmt.Errorf("error while scanning repos: %w", err)
}
if err := exts.DoBeforeUpdate(ctx); err != nil {
return fmt.Errorf("before update extensions: %w", err)
if _, legacy, ok := xsysupdate.CutExtensionTargetPrefix(target.Path); !ok {
// Not an extension target file.
continue
} else if legacy {
// Defer application of legacy-prefixed extensions until we've
// done everything else so we can skip them if there was a
// non-legacy version of the same file.
legacyTargets = append(legacyTargets, target)
continue
}
slog.Info("Completed pre-sysupdate extensions.")
// Otherwise, apply the extension target file.
if err := applyTarget(target); err != nil {
return err
}
}
for _, target := range legacyTargets {
if err := applyTarget(target); err != nil {
return err
}
}
if err := exts.DoBeforeUpdate(ctx); err != nil {
return fmt.Errorf("before update extensions: %w", err)
}
slog.Info("Completed pre-sysupdate extensions.")

// TODO: Should we do runas.User("root") or use run0 here?
// TODO: Should we do runas.User("root") or use run0 here?

// FIXME FIXME FIXME
//
// If these updates error out we are kind of in a messy position.
// Because we need to call sysupdate multiple times to update each
// component, it is possible that one component installation fails. We
// would ideally never want to allow execution with mixed repo states,
// but fixing this requires having logic for cleanup so we can abort
// the extension application, clean up the successfully installed
// components, and force-downgrade to the old versions.
// FIXME FIXME FIXME
//
// If these updates error out we are kind of in a messy position.
// Because we need to call sysupdate multiple times to update each
// component, it is possible that one component installation fails. We
// would ideally never want to allow execution with mixed repo states,
// but fixing this requires having logic for cleanup so we can abort
// the extension application, clean up the successfully installed
// components, and force-downgrade to the old versions.

// Pick up tags the user set by hand, not only ones a confext ships.
if err := enableSuggested(ctx); err != nil {
return err
}
if err := sysupdateAll(ctx); err != nil {
return err
}

// A refreshed confext may ship machine-tags.d(5) files, and features gated on
// those tags were evaluated against the old tags. Loop until the tags
// settle.
if err := exts.Close(); err != nil {
return fmt.Errorf("post-update extension cleanup: %w", err)
}

return nil
}

var updateCommand = withExtensionDirFlag(withQuarryUserFlag(withQuarryProxyFlag(&cli.Command{
Name: "update",
Usage: "extended 'systemd-sysupdate update' wrapper",
Action: func(ctx context.Context, cmd *cli.Command) (Err error) {
// A refreshed confext may ship machine-tags.d(5) files, and features
// gated on those tags were evaluated against the old tags. It may also
// ship quarry-client drop-ins that might define additional
// repositories. Loop until both settle.
//
// TODO: The real signal to stop looping is whether the set of
// installable features stopped changing (rather than the tags), but
// there isn't a really nice way for us to detect that so we use tags
// as a proxy. In future, sysupdate will handle the loop for us (and
// thus be responsible for this detection) so this can all be removed
// then.
// installable features stopped changing (rather than the combination
// of tags and repositories available), but there isn't a really nice
// way for us to detect that so we use tags as a proxy. In future,
// sysupdate will handle the loop for us (and thus be responsible for
// this detection) so this can all (possibly?) be removed then.
tags, err := hostnamed.CurrentTags(ctx, "")
if err != nil {
return fmt.Errorf("fetch machine tags before update: %w", err)
}

// Pick up tags the user set by hand, not only ones a confext ships.
if err := enableSuggested(ctx); err != nil {
return err
}
if err := sysupdateAll(ctx); err != nil {
return err
}

if err := exts.Close(); err != nil {
return fmt.Errorf("post-update extension cleanup: %w", err)
}

for iteration := 1; ; iteration++ {
if err := updatePass(ctx); err != nil {
return err
}

// Do online-reload of sysexts and confexts.
slog.Info("Trigger online-reload of new components.")
if err := sysupdateRefresh(ctx); err != nil {
Expand All @@ -139,23 +152,32 @@ var updateCommand = withExtensionDirFlag(withQuarryUserFlag(withQuarryProxyFlag(
if err != nil {
return fmt.Errorf("fetch machine tags after refresh: %w", err)
}
if slices.Equal(tags, newTags) {
// The refresh may have changed our on-disk configuration, so
// reload it.
newCfg, err := cliext.LoadConfig(cmd)
if err != nil {
return fmt.Errorf("reload configuration after refresh: %w", err)
}
// TODO: Right now we look at the set of repositories to see if we
// should continue looping but arguably we should be tracking if
// the configuration changed at all -- repository names are not
// authoritative information and tracking them this way is less
// than ideal.
repos := slices.Sorted(maps.Keys(cliext.CtxConfig(ctx).Repos))
newRepos := slices.Sorted(maps.Keys(newCfg.Repos))
if slices.Equal(tags, newTags) && slices.Equal(repos, newRepos) {
return nil
}
if iteration >= maxUpdateIterations {
slog.Warn("Maximum number of update iterations reached, not looking for further updates.",
"max", maxUpdateIterations, "before", tags, "after", newTags)
"max", maxUpdateIterations, "before", tags, "after", newTags,
"reposBefore", repos, "reposAfter", newRepos)
return nil
}
slog.Info("Machine tags changed by refresh, running another update pass.",
"iteration", iteration, "before", tags, "after", newTags)
tags = newTags
if err := enableSuggested(ctx); err != nil {
return err
}
if err := sysupdateAll(ctx); err != nil {
return err
}
slog.Info("Machine tags or repositories changed by refresh, running another update pass.",
"iteration", iteration, "before", tags, "after", newTags,
"reposBefore", repos, "reposAfter", newRepos)
tags, ctx = newTags, cliext.WithCtxConfig(ctx, newCfg)
}
},
})))
22 changes: 22 additions & 0 deletions internal/linux/openat_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,25 @@ func Openat(dirFile *os.File, path string, flags int, mode ...uint32) (*os.File,
return os.NewFile(uintptr(fd), fileName), err
})
}

// Mkdirat is a slightly more ergonomic wrapper around [unix.Mkdirat].
func Mkdirat(dirFile *os.File, path string, mode uint32) error {
return fdutils.WithFileFd(dirFile, func(dirFd uintptr) error {
err := unix.Mkdirat(int(dirFd), path, mode) //nolint:forbidigo // caller guarantees that the path is safe to create
if err != nil {
err = &os.PathError{Op: "mkdirat", Path: dirFile.Name() + "/" + path, Err: err}
}
return err
})
}

// Unlinkat is a slightly more ergonomic wrapper around [unix.Unlinkat].
func Unlinkat(dirFile *os.File, path string, flags int) error {
return fdutils.WithFileFd(dirFile, func(dirFd uintptr) error {
err := unix.Unlinkat(int(dirFd), path, flags) //nolint:forbidigo // caller guarantees that the path is safe to remove
if err != nil {
err = &os.PathError{Op: "unlinkat", Path: dirFile.Name() + "/" + path, Err: err}
}
return err
})
}
Loading