A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): add instance directory, lock and ownership
Hampus55008a9d346d
diff --git a/fluxer_rexctl/internal/instance/instance.go b/fluxer_rexctl/internal/instance/instance.gonew file mode 100644index 000000000..3c20f602a--- /dev/null+++ b/fluxer_rexctl/internal/instance/instance.go@@ -0,0 +1,357 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package instance++import (+ "errors"+ "fmt"+ "io/fs"+ "net"+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "slices"+ "strings"+ "time"++ "github.com/compose-spec/compose-go/v2/template"++ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack"+)++var (+ ErrNotFound = errors.New("instance: not found")+ ErrLegacy = errors.New("instance: made by the old installer")+ ErrExists = errors.New("instance: already exists")+ ErrBadProject = errors.New("instance: project names use lowercase letters, digits, dashes and underscores")+ ErrNoReleaseSet = errors.New("instance: the files for this release are missing")+)++const (+ EnvFileName = ".env"+ CustomCompose = settings.CustomFile+ StateDirName = ".rexctl"+ StateFileName = "state.json"+ LockFileName = "lock"+ ReleasesDir = "releases"+ StackDir = "stack"+ BackupsDir = "backups"+ CertsDir = "certs"+ CaddyDropInDir = "caddy.d"+ KeepReleases = 3+)++var legacyComposeNames = []string{"compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml"}++var projectName = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`)++type Instance struct {+ Dir string+ State *State+}++func DefaultDir() (string, error) {+ if runtime.GOOS != "windows" && os.Geteuid() == 0 {+ return "/opt/fluxer", nil+ }+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, "fluxer"), nil+}++func Locate() (string, error) {+ if wd, err := os.Getwd(); err == nil && present(wd) {+ return wd, nil+ }+ dir, err := DefaultDir()+ if err != nil || present(dir) || runtime.GOOS == "windows" || os.Geteuid() != 0 {+ return dir, err+ }+ if home, err := os.UserHomeDir(); err == nil && present(filepath.Join(home, "fluxer")) {+ return filepath.Join(home, "fluxer"), nil+ }+ return dir, nil+}++func present(dir string) bool {+ return exists(filepath.Join(dir, StateDirName, StateFileName)) || isLegacy(dir)+}++func Find(dir string) (*Instance, error) {+ dir, err := filepath.Abs(dir)+ if err != nil {+ return nil, err+ }+ i := &Instance{Dir: dir}+ state, err := LoadState(i.StatePath())+ if errors.Is(err, fs.ErrNotExist) {+ if isLegacy(dir) {+ return nil, ErrLegacy+ }+ return nil, ErrNotFound+ }+ if err != nil {+ return nil, err+ }+ i.State = state+ return i, nil+}++func isLegacy(dir string) bool {+ if exists(filepath.Join(dir, StateDirName, StateFileName)) || !exists(filepath.Join(dir, EnvFileName)) {+ return false+ }+ for _, name := range legacyComposeNames {+ if exists(filepath.Join(dir, name)) {+ return true+ }+ }+ env, _ := envfile.Load(filepath.Join(dir, EnvFileName))+ return env != nil && env.Value("COMPOSE_FILE") != ""+}++func exists(path string) bool {+ _, err := os.Stat(path)+ return err == nil+}++func Create(dir, project string) (*Instance, error) {+ if !projectName.MatchString(project) {+ return nil, ErrBadProject+ }+ dir, err := filepath.Abs(dir)+ if err != nil {+ return nil, err+ }+ i := &Instance{Dir: dir}+ if exists(i.StatePath()) {+ return nil, ErrExists+ }+ if isLegacy(dir) {+ return nil, ErrLegacy+ }+ if exists(i.Path(EnvFileName)) {+ return nil, ErrExists+ }+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return nil, err+ }+ for _, d := range []string{StateDirName, BackupsDir} {+ if err := os.MkdirAll(i.Path(d), 0o700); err != nil {+ return nil, err+ }+ if err := envfile.RestrictToOwner(i.Path(d)); err != nil {+ return nil, err+ }+ }+ for _, d := range []string{CertsDir, CaddyDropInDir} {+ if err := os.MkdirAll(i.Path(d), 0o755); err != nil {+ return nil, err+ }+ }+ now := time.Now().UTC().Truncate(time.Second)+ i.State = &State{Schema: StateSchema, Project: project, InstalledAt: now, UpdatedAt: now}+ i.State.normalize()+ return i, nil+}++func (i *Instance) Path(elem ...string) string {+ return filepath.Join(append([]string{i.Dir}, elem...)...)+}++func (i *Instance) StateDir() string { return i.Path(StateDirName) }++func (i *Instance) StatePath() string { return i.Path(StateDirName, StateFileName) }++func (i *Instance) ReleaseDir(version string) string {+ return i.Path(StateDirName, ReleasesDir, version)+}++func (i *Instance) SetDir(version string) string {+ return filepath.Join(i.ReleaseDir(version), StackDir)+}++func (i *Instance) BackupDir() string { return i.Path(BackupsDir) }++func (i *Instance) Project() string {+ if i.State != nil {+ return i.State.Project+ }+ return ""+}++func (i *Instance) Set() (*stack.Set, error) {+ release := i.State.Release+ set, err := stack.LoadSet(i.SetDir(release))+ if err == nil {+ return set, nil+ }+ if !errors.Is(err, fs.ErrNotExist) {+ return nil, err+ }+ if embedded := stack.Embedded(); release == "" || release == embedded.Release {+ return embedded, nil+ }+ return nil, fmt.Errorf("%w: %s", ErrNoReleaseSet, release)+}++func (i *Instance) Custom() ([]byte, error) {+ data, err := os.ReadFile(i.Path(CustomCompose))+ if errors.Is(err, fs.ErrNotExist) {+ return nil, nil+ }+ return data, err+}++func (i *Instance) Environment() (map[string]string, error) {+ set, err := i.Set()+ if err != nil {+ return nil, err+ }+ return effectiveFor(set, i.State)+}++func effectiveFor(set *stack.Set, s *State) (map[string]string, error) {+ var admin map[string]string+ if s.AdminImport != nil {+ admin = s.AdminImport.Values+ }+ return settings.Effective(set, s.Settings, s.Secrets, admin)+}++func (i *Instance) Setting(name string) string {+ if i.State == nil {+ return ""+ }+ set, err := i.Set()+ if err != nil {+ return i.State.Settings[name]+ }+ env, err := effectiveFor(set, i.State)+ if err != nil {+ return i.State.Settings[name]+ }+ if v, ok := env[name]; ok {+ return v+ }+ custom, _ := i.Custom()+ return composeDefault(set, custom, env, name)+}++func composeDefault(set *stack.Set, custom []byte, env map[string]string, name string) string {+ defs := composeDefaults(setFiles(set, custom))[name]+ if len(defs) == 0 {+ return ""+ }+ v, ok := interpolate(defs[0], env)+ if !ok {+ return ""+ }+ return v+}++func interpolate(s string, env map[string]string) (string, bool) {+ out, err := template.Substitute(s, func(k string) (string, bool) {+ v, ok := env[k]+ return v, ok+ })+ return out, err == nil+}++func setFiles(set *stack.Set, custom []byte) [][]byte {+ var out [][]byte+ if names, err := stack.ComposeFileNames(set.Files); err == nil {+ for _, name := range names {+ if data, err := fs.ReadFile(set.Files, name); err == nil {+ out = append(out, data)+ }+ }+ }+ if len(custom) > 0 {+ out = append(out, custom)+ }+ return out+}++func (i *Instance) Domain() string {+ return i.Setting("FLUXER_DOMAIN")+}++func (i *Instance) Origin() string {+ if o := strings.TrimSpace(i.Setting("FLUXER_PUBLIC_ORIGIN")); o != "" && !strings.Contains(o, "${") {+ return strings.TrimRight(o, "/")+ }+ domain := i.Domain()+ if domain == "" {+ return ""+ }+ scheme := i.Setting("FLUXER_PUBLIC_SCHEME")+ if scheme == "" {+ scheme = "https"+ }+ port := i.Setting("FLUXER_PUBLIC_PORT")+ if port == "" || (scheme == "https" && port == "443") || (scheme == "http" && port == "80") {+ return scheme + "://" + domain+ }+ return scheme + "://" + net.JoinHostPort(domain, port)+}++func (i *Instance) Overlays() []stack.Overlay {+ if i.State == nil {+ return nil+ }+ return stack.OverlaysFor(i.State.Settings)+}++func (i *Instance) ComposeFiles() []string {+ files := stack.ComposeFiles(i.Dir, i.Overlays())+ if exists(i.Path(CustomCompose)) {+ files = append(files, i.Path(CustomCompose))+ }+ return files+}++func (i *Instance) MissingFiles() []string {+ files := stack.ComposeFiles(i.Dir, i.Overlays())+ for name := range stack.MountedFiles {+ files = append(files, i.Path(name))+ }+ var out []string+ for _, f := range files {+ if exists(f) {+ continue+ }+ if rel, err := filepath.Rel(i.Dir, f); err == nil {+ f = rel+ }+ out = append(out, f)+ }+ slices.Sort(out)+ return out+}++func (i *Instance) Save() error {+ if i.State == nil {+ return fmt.Errorf("instance: nothing to save in %s", i.Dir)+ }+ i.State.UpdatedAt = time.Now().UTC().Truncate(time.Second)+ if err := i.State.Save(i.StatePath()); err != nil {+ return err+ }+ if fromV1 {+ return removeIfExists(i.Path(EnvFileName))+ }+ return nil+}++func removeIfExists(path string) error {+ if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {+ return err+ }+ return nil+}diff --git a/fluxer_rexctl/internal/instance/lock.go b/fluxer_rexctl/internal/instance/lock.gonew file mode 100644index 000000000..06e68ff07--- /dev/null+++ b/fluxer_rexctl/internal/instance/lock.go@@ -0,0 +1,54 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package instance++import (+ "context"+ "errors"+ "os"+)++var ErrLocked = errors.New("instance: another rexctl command is changing this instance")++type Lock struct {+ path string+ file *os.File+}++func (i *Instance) Lock(ctx context.Context) (*Lock, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ if err := os.MkdirAll(i.StateDir(), 0o700); err != nil {+ return nil, err+ }+ path := i.Path(StateDirName, LockFileName)+ f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600)+ if err != nil {+ return nil, err+ }+ if err := tryLock(f); err != nil {+ f.Close()+ return nil, err+ }+ return &Lock{path: path, file: f}, nil+}++func (i *Instance) Busy() bool {+ l, err := i.Lock(context.Background())+ if err != nil {+ return errors.Is(err, ErrLocked)+ }+ l.Release()+ return false+}++func (l *Lock) Release() error {+ if l == nil || l.file == nil {+ return nil+ }+ f := l.file+ l.file = nil+ unlock(f)+ return f.Close()+}diff --git a/fluxer_rexctl/internal/instance/lock_unix.go b/fluxer_rexctl/internal/instance/lock_unix.gonew file mode 100644index 000000000..0d8f18b99--- /dev/null+++ b/fluxer_rexctl/internal/instance/lock_unix.go@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++//go:build !windows++package instance++import (+ "errors"+ "os"+ "syscall"+)++func tryLock(f *os.File) error {+ for {+ err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)+ if errors.Is(err, syscall.EINTR) {+ continue+ }+ if errors.Is(err, syscall.EWOULDBLOCK) {+ return ErrLocked+ }+ return err+ }+}++func unlock(f *os.File) {+ _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)+}diff --git a/fluxer_rexctl/internal/instance/lock_windows.go b/fluxer_rexctl/internal/instance/lock_windows.gonew file mode 100644index 000000000..0b055c649--- /dev/null+++ b/fluxer_rexctl/internal/instance/lock_windows.go@@ -0,0 +1,26 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++//go:build windows++package instance++import (+ "errors"+ "os"++ "golang.org/x/sys/windows"+)++func tryLock(f *os.File) error {+ var ol windows.Overlapped+ err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &ol)+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {+ return ErrLocked+ }+ return err+}++func unlock(f *os.File) {+ var ol windows.Overlapped+ _ = windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, &ol)+}diff --git a/fluxer_rexctl/internal/instance/owner_unix.go b/fluxer_rexctl/internal/instance/owner_unix.gonew file mode 100644index 000000000..5ed942960--- /dev/null+++ b/fluxer_rexctl/internal/instance/owner_unix.go@@ -0,0 +1,22 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++//go:build !windows++package instance++import (+ "os"+ "syscall"+)++func (i *Instance) OwnerUID() (int, bool) {+ info, err := os.Stat(i.Dir)+ if err != nil {+ return 0, false+ }+ st, ok := info.Sys().(*syscall.Stat_t)+ if !ok {+ return 0, false+ }+ return int(st.Uid), true+}diff --git a/fluxer_rexctl/internal/instance/owner_windows.go b/fluxer_rexctl/internal/instance/owner_windows.gonew file mode 100644index 000000000..9568c367e--- /dev/null+++ b/fluxer_rexctl/internal/instance/owner_windows.go@@ -0,0 +1,7 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++//go:build windows++package instance++func (i *Instance) OwnerUID() (int, bool) { return 0, false }