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
8 changes: 4 additions & 4 deletions availableVersions.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"production": "1.6.21",
"test": "1.6.21",
"local": "1.6.21",
"all": "1.6.21"
"production": "1.6.22",
"test": "1.6.22",
"local": "1.6.22",
"all": "1.6.22"
}
28 changes: 28 additions & 0 deletions src/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (
"os"
"reagent/api"
"reagent/apps"
"reagent/appstorage"
"reagent/benchmark"
"reagent/common"
"reagent/config"
"reagent/container"
"reagent/crashrecovery"
Expand Down Expand Up @@ -460,6 +462,32 @@ func NewAgent(generalConfig *config.Config) (agent *Agent) {
safe.Go(func() { diskGuard.Run(context.Background()) })
}

// What each installed app takes on this device's disk (its volumes, its
// folders, its containers' writable layers), measured every 30 minutes
// and carried in the device stats for the app's storage view.
safe.Go(func() {
appstorage.Run(context.Background(), container, appstorage.Config{
AppsDirectory: cliArgs.AppsDirectory,
AppsComposeDir: cliArgs.AppsComposeDir,
AppsSharedDir: cliArgs.AppsSharedDir,
AgentDir: cliArgs.AgentDir,
Apps: func() ([]appstorage.App, error) {
payloads, err := appStore.GetRequestedStates()
if err != nil {
return nil, err
}
prod := make([]appstorage.App, 0, len(payloads))
for _, p := range payloads {
if p.Stage == common.PROD {
prod = append(prod, appstorage.App{AppKey: p.AppKey, AppName: p.AppName})
}
}
return prod, nil
},
Paused: diskguard.IsEmergency,
})
})

// Reconcile local app state against the Docker daemon. fatal=true keeps
// the historical behavior (die and let the supervisor restart us); the
// late-daemon path must not kill an otherwise healthy agent, so it logs
Expand Down
328 changes: 328 additions & 0 deletions src/appstorage/appstorage.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,328 @@
// Package appstorage measures how much of the device's disk each installed
// app takes, for the app's storage view in the platform. It runs as a slow
// background loop in the agent; the last measurement rides in the device
// stats of every heartbeat (StatsFields), which the backend keeps on the
// device row.
//
// Per app (the PROD install; a development run is not the installed app) it
// counts:
//
// - volumes: the Docker volumes its containers mount, and those labeled with
// its compose project (kept by `compose down`, so a stopped app still has
// them), each with its size;
// - folder: the app's own folders the agent creates — the /data folder of a
// single-container app (<AppsDirectory>/prod/<name>) and the folder of a
// compose app (<AppsComposeDir>/<name>), which holds the data of its
// relative bind mounts (./data:/data);
// - container: the writable layers of its containers, the data written
// outside any mount (an app that forgot to declare a volume fills it);
// - host_paths: the other host folders it binds (/mnt/usb:/data). They are
// listed, not counted: such a folder can be shared with other apps or the
// host, so its size is not the app's.
//
// The Docker part comes from the daemon's disk-usage report, which walks
// every volume and writable layer: on an SD card that takes minutes and keeps
// the daemon busy. So it runs every 30 minutes, with a deadline, and not
// while the device is in a disk emergency (when the daemon is often wedged).
// A failed pass keeps the previous measurement.
package appstorage

import (
"context"
"io/fs"
"os"
"path/filepath"
"reagent/common"
"reagent/container"
"slices"
"strings"
"sync/atomic"
"time"

"github.com/rs/zerolog/log"
)

const (
initialDelay = 3 * time.Minute // not while the agent starts the apps
interval = 30 * time.Minute
passTimeout = 10 * time.Minute

// The heartbeat carries this on every beat: keep it small.
maxVolumesPerApp = 20
maxHostPathsPerApp = 10

composeProjectLabel = "com.docker.compose.project"
)

// Docker is the subset of the container layer the measurement needs.
// *container.Docker satisfies it.
type Docker interface {
DiskUsage(ctx context.Context) ([]container.DiskUsageVolume, []container.DiskUsageContainer, error)
}

// App is one locally known app.
type App struct {
AppKey uint64
AppName string
}

type Config struct {
AppsDirectory string // holds <stage>/<name>, the /data folders
AppsComposeDir string // holds <name>, the PROD compose folders
AppsSharedDir string // the /shared folder of all apps: nobody's alone
AgentDir string
// Apps returns the locally known PROD apps, stopped ones included.
Apps func() ([]App, error)
// Paused reports whether a pass must be skipped now (disk emergency).
Paused func() bool
}

// Volume is one volume of an app with its size in bytes.
type Volume struct {
Name string
Bytes int64
}

// Usage is what one app takes on this device.
type Usage struct {
AppKey uint64
VolumesBytes int64
Volumes []Volume // largest first, at most maxVolumesPerApp
FolderBytes int64
ContainerBytes int64
HostPaths []string // at most maxHostPathsPerApp
}

type Report struct {
MeasuredAt time.Time
Apps []Usage
}

// dict is the report as the heartbeat carries it: plain maps, the time as
// RFC 3339, so every WAMP serializer encodes it the same way.
func (r *Report) dict() common.Dict {
apps := make([]common.Dict, 0, len(r.Apps))
for _, u := range r.Apps {
app := common.Dict{
"app_key": u.AppKey,
"volumes_bytes": u.VolumesBytes,
"folder_bytes": u.FolderBytes,
"container_bytes": u.ContainerBytes,
}
if len(u.Volumes) > 0 {
volumes := make([]common.Dict, 0, len(u.Volumes))
for _, v := range u.Volumes {
volumes = append(volumes, common.Dict{"name": v.Name, "bytes": v.Bytes})
}
app["volumes"] = volumes
}
if len(u.HostPaths) > 0 {
app["host_paths"] = u.HostPaths
}
apps = append(apps, app)
}
return common.Dict{"measured_at": r.MeasuredAt.Format(time.RFC3339), "apps": apps}
}

var last atomic.Pointer[Report]

// StatsFields is the last measurement for the heartbeat's stats:
// "app_storage" with measured_at and apps, one entry per locally known PROD
// app (app_key, volumes_bytes, volumes [name, bytes], folder_bytes,
// container_bytes, host_paths). Until the first pass has finished, apps is
// empty and measured_at missing: the platform then knows the agent measures,
// unlike one too old to, whose stats have no app_storage at all.
func StatsFields() common.Dict {
r := last.Load()
if r == nil {
return common.Dict{"app_storage": common.Dict{"apps": []common.Dict{}}}
}
return common.Dict{"app_storage": r.dict()}
}

// Run measures after initialDelay and then every interval, until ctx ends.
func Run(ctx context.Context, docker Docker, cfg Config) {
timer := time.NewTimer(initialDelay)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
}
if cfg.Paused == nil || !cfg.Paused() {
passCtx, cancel := context.WithTimeout(ctx, passTimeout)
report, err := Measure(passCtx, docker, cfg)
cancel()
if err != nil {
log.Warn().Err(err).Msg("appstorage: measuring the apps' disk usage failed; keeping the last measurement")
} else {
last.Store(report)
}
}
timer.Reset(interval)
}
}

// Measure takes one measurement of every locally known PROD app.
func Measure(ctx context.Context, docker Docker, cfg Config) (*Report, error) {
apps, err := cfg.Apps()
if err != nil {
return nil, err
}
volumes, containers, err := docker.DiskUsage(ctx)
if err != nil {
return nil, err
}

byProject := make(map[string]int, len(apps))
byContainer := make(map[string]int, len(apps))
usages := make([]Usage, len(apps))
folders := make([][]string, len(apps))
for i, app := range apps {
usages[i].AppKey = app.AppKey
byProject[common.NormalizeComposeProjectName(
common.BuildComposeContainerName(common.PROD, app.AppKey, app.AppName))] = i
byContainer[common.BuildContainerName(common.PROD, app.AppKey, app.AppName)] = i
folders[i] = appFolders(cfg, app.AppName)
}

ownerOf := func(labels map[string]string, names []string) (int, bool) {
if project := labels[composeProjectLabel]; project != "" {
i, ok := byProject[common.NormalizeComposeProjectName(project)]
return i, ok
}
for _, n := range names {
if i, ok := byContainer[strings.TrimPrefix(n, "/")]; ok {
return i, true
}
}
return 0, false
}

volumeOwner := make(map[string]int)
for _, c := range containers {
i, ok := ownerOf(c.Labels, c.Names)
if !ok {
continue
}
if c.SizeRw > 0 {
usages[i].ContainerBytes += c.SizeRw
}
for _, m := range c.Mounts {
switch m.Type {
case "volume":
if _, taken := volumeOwner[m.Name]; !taken && m.Name != "" {
volumeOwner[m.Name] = i
}
case "bind":
if isHostPath(cfg, folders[i], m.Source) && !slices.Contains(usages[i].HostPaths, m.Source) {
usages[i].HostPaths = append(usages[i].HostPaths, m.Source)
}
}
}
}

for _, v := range volumes {
i, ok := volumeOwner[v.Name]
if !ok {
i, ok = ownerOf(v.Labels, nil)
}
if !ok || v.Size < 0 {
continue
}
usages[i].VolumesBytes += v.Size
usages[i].Volumes = append(usages[i].Volumes, Volume{Name: v.Name, Bytes: v.Size})
}

for i := range usages {
for _, dir := range folders[i] {
size, err := dirSize(ctx, dir)
if err != nil {
return nil, err
}
usages[i].FolderBytes += size
}
// Largest first, so a cut list still shows what matters.
slices.SortFunc(usages[i].Volumes, func(a, b Volume) int {
switch {
case a.Bytes > b.Bytes:
return -1
case a.Bytes < b.Bytes:
return 1
}
return strings.Compare(a.Name, b.Name)
})
if len(usages[i].Volumes) > maxVolumesPerApp {
usages[i].Volumes = usages[i].Volumes[:maxVolumesPerApp]
}
slices.Sort(usages[i].HostPaths)
if len(usages[i].HostPaths) > maxHostPathsPerApp {
usages[i].HostPaths = usages[i].HostPaths[:maxHostPathsPerApp]
}
}

return &Report{MeasuredAt: time.Now().UTC().Truncate(time.Second), Apps: usages}, nil
}

// appFolders are the app's own folders, the ones the agent creates for it.
func appFolders(cfg Config, appName string) []string {
var dirs []string
if cfg.AppsDirectory != "" {
dirs = append(dirs, filepath.Join(cfg.AppsDirectory, strings.ToLower(string(common.PROD)), strings.ToLower(appName)))
}
if cfg.AppsComposeDir != "" {
dirs = append(dirs, filepath.Join(cfg.AppsComposeDir, appName))
}
return dirs
}

// systemPrefixes are host folders an app binds to reach the host (devices,
// sockets, the D-Bus, configuration), not to keep data there.
var systemPrefixes = []string{"/dev", "/sys", "/proc", "/run", "/var/run", "/etc", "/usr", "/lib", "/bin", "/sbin", "/boot", "/tmp"}

// isHostPath reports whether a bind source is a host folder outside the app's
// own folders and the agent's, i.e. one worth listing as "not counted".
func isHostPath(cfg Config, appFolders []string, source string) bool {
if source == "" || !filepath.IsAbs(source) {
return false
}
clean := filepath.Clean(source)
own := append([]string{cfg.AppsDirectory, cfg.AppsSharedDir, cfg.AgentDir}, appFolders...)
for _, root := range append(own, systemPrefixes...) {
if root != "" && within(clean, root) {
return false
}
}
info, err := os.Stat(clean)
return err == nil && info.IsDir()
}

func within(path, root string) bool {
root = filepath.Clean(root)
return path == root || strings.HasPrefix(path, root+string(filepath.Separator))
}

// dirSize sums the sizes of the regular files below dir. A missing dir is 0;
// files that vanish or cannot be read during the walk are skipped.
func dirSize(ctx context.Context, dir string) (int64, error) {
var total int64
err := filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error {
if ctxErr := ctx.Err(); ctxErr != nil {
return ctxErr
}
if err != nil {
return nil
}
if d.Type().IsRegular() {
if info, err := d.Info(); err == nil {
total += info.Size()
}
}
return nil
})
if err != nil && ctx.Err() != nil {
return 0, err
}
return total, nil
}
Loading
Loading