Nine packages each had their own write-temp-then-rename helper with slightly different behaviour (some synced, some did not; some created the parent directory, some did not; modes and temp-file patterns varied). They are replaced by one fsutil.WriteFileAtomic that always syncs before rename, creates the parent directory, and takes the file mode as a parameter.
77 lines
2.4 KiB
Go
77 lines
2.4 KiB
Go
package releaseupdate
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/samcharles93/archie-core/internal/fsutil"
|
|
)
|
|
|
|
// Report is an update's post-restart outcome, written by the watchdog and
|
|
// relayed by the next archied boot.
|
|
type Report struct {
|
|
Channel string `json:"channel"`
|
|
ChatID int64 `json:"chat_id"`
|
|
ThreadID int `json:"thread_id"`
|
|
Previous map[string]string `json:"previous"`
|
|
Installed map[string]string `json:"installed"`
|
|
HealthCheck string `json:"health_check"` // "passed" or "failed"
|
|
RolledBack bool `json:"rolled_back"`
|
|
// RestoredDatabase reports that rollback found a migration and restored
|
|
// the pre-update snapshot, losing every write made since it.
|
|
RestoredDatabase bool `json:"restored_database"`
|
|
}
|
|
|
|
func (r Report) validate() error {
|
|
if r.RolledBack && r.HealthCheck != "failed" {
|
|
return errors.New("update report: rolled_back requires health_check to be \"failed\"")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// WritePendingReport persists r to path atomically, the same way
|
|
// saveDeferrals does.
|
|
func WritePendingReport(path string, r Report) error {
|
|
if err := r.validate(); err != nil {
|
|
return err
|
|
}
|
|
data, err := json.Marshal(r)
|
|
if err != nil {
|
|
return fmt.Errorf("encode update report: %w", err)
|
|
}
|
|
if err := fsutil.WriteFileAtomic(path, data, 0o600); err != nil {
|
|
return fmt.Errorf("write update report: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ReadPendingReport reads a Report previously written by WritePendingReport.
|
|
// found is false, with a nil error, when no update is in flight -- the
|
|
// common case on every normal startup.
|
|
func ReadPendingReport(path string) (Report, bool, error) {
|
|
data, err := os.ReadFile(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return Report{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return Report{}, false, fmt.Errorf("read update report: %w", err)
|
|
}
|
|
var report Report
|
|
if err := json.Unmarshal(data, &report); err != nil {
|
|
return Report{}, false, fmt.Errorf("decode update report: %w", err)
|
|
}
|
|
return report, true, nil
|
|
}
|
|
|
|
// ClearPendingReport removes a report once it has been relayed. A report
|
|
// that is already gone (cleared by a previous boot attempt) is not an
|
|
// error.
|
|
func ClearPendingReport(path string) error {
|
|
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return fmt.Errorf("clear update report: %w", err)
|
|
}
|
|
return nil
|
|
}
|