package main import ( "errors" "fmt" "os" "path/filepath" "regexp" "strings" ) // appliedStore keeps every composition the agent applied, one file per module (the node's own as `node.json`), in the // directory `applied` beside the node's state (agent.Env.Applied, issue 774). It is the machine's own record of what runs: // read at the agent's start before anything is watched, so the node never composes its own as if a module it runs ran // nothing because the bucket no longer keeps that composition or the kept declaration is retired. Files are 0600 in a // 0700 directory: a composition carries values sealed to this machine. type appliedStore struct{ dir string } func appliedStoreFor(statePath string) appliedStore { return appliedStore{dir: filepath.Join(filepath.Dir(statePath), "applied")} } // appliedName is a module name the store takes as a file name: a catalogue module's or the node's own, never a path. var appliedName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`) func (s appliedStore) path(module string) (string, error) { if !appliedName.MatchString(module) || strings.Contains(module, "..") { return "", fmt.Errorf("%q is not a module name the applied store takes", module) } return filepath.Join(s.dir, module+".json"), nil } // holds says whether the store keeps the module's composition. func (s appliedStore) holds(module string) bool { path, err := s.path(module) if err != nil { return false } _, err = os.Stat(path) return err == nil } func (s appliedStore) Load() (map[string][]byte, error) { entries, err := os.ReadDir(s.dir) if errors.Is(err, os.ErrNotExist) { return nil, nil } if err != nil { return nil, err } out := map[string][]byte{} var errs []error for _, e := range entries { module, ok := strings.CutSuffix(e.Name(), ".json") if !ok || e.IsDir() || !appliedName.MatchString(module) { continue } raw, err := os.ReadFile(filepath.Join(s.dir, e.Name())) if err != nil { errs = append(errs, err) continue } out[module] = raw } return out, errors.Join(errs...) } func (s appliedStore) Keep(module string, raw []byte) error { path, err := s.path(module) if err != nil { return err } if was, err := os.ReadFile(path); err == nil && string(was) == string(raw) { return nil } if err := os.MkdirAll(s.dir, 0o700); err != nil { return err } tmp, err := os.CreateTemp(s.dir, "."+module+".*") if err != nil { return err } defer os.Remove(tmp.Name()) if _, err := tmp.Write(raw); err != nil { tmp.Close() return err } if err := tmp.Sync(); err != nil { tmp.Close() return err } if err := tmp.Close(); err != nil { return err } return os.Rename(tmp.Name(), path) } func (s appliedStore) Drop(module string) error { path, err := s.path(module) if err != nil { return err } if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { return err } return nil }