Soft limit per share (F-QUO-8)
Where no hard limit is possible (a host folder mounted into the VM/LXC,
an LXC's own disk), a share can get a soft limit:
- Sharestead measures the folder (as for personal folders); a full share
is read-only over SMB for everyone through a second trailing include
(/etc/samba/sharestead/share-limits.conf) that repeats it with
read only = yes. Verified first on CT 151: a share-section include
with %S does NOT work (Samba doesn't substitute it there), a trailing
global include does, also against an explicit write list.
- Connections to a share whose state changes are closed (smbcontrol all
close-share) so it applies at once; dfree reports the space left in
the limit inside the share.
- Existing setups get the second include when the first share limit is
set; KeepLimitsLast keeps both last.
- PUT /api/v1/shares/{name}/limit; limits of deleted shares are dropped;
"Share X is full" on Problems.
- UI: "Size limit" card on the share page: a hard limit set outside is
shown (with a soft one too, if set); otherwise a soft limit with bar,
"full — read-only over SMB" and what isn't stopped; greyed with the
reason for shares not on SMB; personal folders point to their own
limits. Share list and dashboard show limit and "full".
- Problems page checks fresh when opened (it showed the last background
check, up to a minute old); saving a limit refreshes problems.
- The label's accessible name is just "Soft limit" (FieldLabel; it read
"Soft limit soft What is …?").
Verified on VM 152 with smbclient: Media (ext4, 126 MB, limit 100 MB)
refuses uploads, downloads work, clients see 1 KB free; HostData
(virtiofs) and Family (XFS) below their limits accept uploads. e2e on
CT 151 (desktop + phone), axe on both instances. Tests: domain, service,
API.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b1571cb976
commit
5937a0d26f
25 files changed
+575
-35
No files matched your search
@@ -147,6 +147,7 @@ func run(listen, dataDir, adminGroup string, log *slog.Logger) error {
|
||||
Homes: editor.Homes,
|
||||
SettingsFile: filepath.Join(dataDir, "limits.json"),
|
||||
OverrideDir: filepath.Dir(share.LimitsInclude),
|
||||
ShareFile: share.ShareLimitsInclude,
|
||||
DFreeDir: "/run/sharestead/dfree",
|
||||
Interval: 10 * time.Minute,
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ Items marked ❓ depend on an open question in [README](README.md#open-questions
|
||||
| F-QUO-4 | The personal folder's remaining space is reported to clients (Explorer/Finder show it as free space) | S | MVP |
|
||||
| F-QUO-5 | **Hard limits per share / personal folder, shown for every filesystem:** the share page shows the space the system reports for the folder, which includes hard limits (ZFS dataset `refquota`, XFS and ext4 project quota: all verified on CT 151, see design §4.4); per storage folder, whether hard limits can be set here, and if not, what is missing (F-MON-11) | S | MVP |
|
||||
| F-QUO-6 | **Manage hard limits** where Sharestead runs on the same system as the filesystem (VM, bare metal): adapters for ZFS, XFS and ext4 project quota (btrfs qgroups later); detected per storage folder, greyed out with the reason otherwise (F-MON-11) | S | v1 |
|
||||
| F-QUO-8 | **Soft limit per share** where hard limits aren't possible (e.g. a host folder mounted into the VM/LXC): Sharestead measures the folder every ~10 min; over the limit the share is read-only over SMB for everyone, PCs show the space left in the limit. Labelled "soft: only uploads via Sharestead are stopped; writes on the host or via NFS aren't". When the folder grows past the limit another way, the UI shows it plainly (red bar, e.g. 250 / 200 GB). Owner's decision 2026-11-29 | M | MVP |
|
||||
| F-QUO-8 | **Soft limit per share** where hard limits aren't possible (e.g. a host folder mounted into the VM/LXC): Sharestead measures the folder every ~10 min; over the limit the share is read-only over SMB for everyone, PCs show the space left in the limit. Labelled "soft: only uploads via Sharestead are stopped; writes on the host or via NFS aren't". When the folder grows past the limit another way, the UI shows it plainly (red bar, e.g. 250 / 200 GB). Owner's decision 2026-11-29. Built: enforced via a trailing include (`share-limits.conf`) that repeats full shares with `read only = yes`, verified on CT 151 and VM 152 | M | MVP |
|
||||
| F-QUO-7 | The UI states clearly which quota type is active and what it means | M | MVP |
|
||||
|
||||
### Discovery & services
|
||||
|
||||
@@ -23,6 +23,7 @@ and the command to enable them**.
|
||||
| **Read-only per user over NFS** | POSIX ACLs on that storage folder | NFS gives access per device; the share page says which rules NFS doesn't enforce |
|
||||
| **NFS** | `nfs-kernel-server`; a **privileged** container or a VM (the kernel NFS server can't run in an unprivileged container) | NFS is shown as not available, with the reason |
|
||||
| **Hard storage limits** (writes stop at the limit) | set in the filesystem: a ZFS dataset with `refquota`, an XFS/ext4 project quota per folder. In a container only the host can set them. Sharestead shows them as the folder's size | personal folders get a soft limit: measured every ~10 min, read-only over SMB until space is freed; it can grow past the limit in between, NFS isn't limited |
|
||||
| **Soft limit per share** | nothing extra: Sharestead measures the folder and stops uploads over SMB when it is full | — (available everywhere; writes on the server itself or over NFS aren't stopped; it counts space on disk after compression) |
|
||||
| **Windows network discovery** | `wsdd2`; ports 3702/udp, 5357/tcp | the NAS doesn't appear in *Network* on Windows; connecting by address still works |
|
||||
| **Mac discovery** | `avahi-daemon`; port 5353/udp | the NAS doesn't appear in Finder's sidebar; *Connect to Server* still works |
|
||||
| **TVs and media players (DLNA)** | `minidlna`; ports 1900/udp, 8200/tcp | no DLNA |
|
||||
|
||||
@@ -39,6 +39,25 @@ func (s *Service) Problems(ctx context.Context) []health.Problem {
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, sh := range r.Shares {
|
||||
if sh.Limit > 0 {
|
||||
limited++
|
||||
}
|
||||
if !sh.ReadOnly {
|
||||
continue
|
||||
}
|
||||
out = append(out, health.Problem{
|
||||
ID: "limit-share-" + sh.Name, Severity: health.Warning,
|
||||
Title: "Share " + sh.Name + " is full",
|
||||
Affected: []string{"The share is read-only over SMB for everyone; other shares work"},
|
||||
Cause: fmt.Sprintf("The folder %s holds %s; the share's limit is %s.", sh.Path, quota.Size(sh.Used), quota.Size(sh.Limit)),
|
||||
Steps: []string{
|
||||
"Delete or move files in the share. Write access returns by itself after the next measurement.",
|
||||
"Or raise the share's limit on its page.",
|
||||
},
|
||||
Facts: []string{fmt.Sprintf("%.0f %% of the limit used", sh.Percent), "soft limit: writes on the server itself or over NFS aren't stopped", "measured " + ago(r.ScannedAt)},
|
||||
})
|
||||
}
|
||||
if limited == 0 {
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"path/filepath"
|
||||
@@ -58,10 +59,11 @@ type Config interface {
|
||||
LimitsConfigured() (enabled, last bool, err error)
|
||||
}
|
||||
|
||||
// Sessions closes a user's open connections to shares so new settings apply;
|
||||
// Sessions closes open connections to shares so new settings apply;
|
||||
// clients reconnect by themselves.
|
||||
type Sessions interface {
|
||||
Reconnect(ctx context.Context, user string, shares []string) error
|
||||
CloseShare(ctx context.Context, share string) error
|
||||
}
|
||||
|
||||
// Settings are the stored limits.
|
||||
@@ -73,6 +75,9 @@ type Settings struct {
|
||||
// only affects users created afterwards.
|
||||
HomeDefault int64 `json:"home_default"`
|
||||
HomeUsers map[string]int64 `json:"home_users"`
|
||||
// Shares holds soft limits per share (share name → bytes), for folders
|
||||
// where no hard limit is possible.
|
||||
Shares map[string]int64 `json:"shares"`
|
||||
}
|
||||
|
||||
// HomeLimit returns the limit of a user's personal folder and where it
|
||||
@@ -105,11 +110,15 @@ type UserUsage struct {
|
||||
Home *HomeUsage `json:"home,omitempty"`
|
||||
}
|
||||
|
||||
// ShareUsage is the size of one share's folder.
|
||||
// ShareUsage is the size of one share's folder and its soft limit.
|
||||
type ShareUsage struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
Used int64 `json:"used"`
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
Used int64 `json:"used"`
|
||||
Limit int64 `json:"limit"` // soft limit; 0: none
|
||||
Percent float64 `json:"percent"`
|
||||
State quota.State `json:"state"`
|
||||
ReadOnly bool `json:"read_only"` // full: read-only over SMB now
|
||||
}
|
||||
|
||||
// Report is the current usage.
|
||||
@@ -139,6 +148,7 @@ type Service struct {
|
||||
|
||||
SettingsFile string // /var/lib/sharestead/limits.json
|
||||
OverrideDir string // /etc/samba/sharestead/limits
|
||||
ShareFile string // /etc/samba/sharestead/share-limits.conf (share.ShareLimitsInclude)
|
||||
DFreeDir string // /run/sharestead/dfree
|
||||
Interval time.Duration // between scans (minimum)
|
||||
|
||||
@@ -165,7 +175,7 @@ func (s *Service) log() *slog.Logger {
|
||||
|
||||
// Settings returns the stored limits.
|
||||
func (s *Service) Settings() (Settings, error) {
|
||||
st := Settings{WarnPercent: quota.DefaultWarnPercent, HomeUsers: map[string]int64{}}
|
||||
st := Settings{WarnPercent: quota.DefaultWarnPercent, HomeUsers: map[string]int64{}, Shares: map[string]int64{}}
|
||||
b, err := s.Files.ReadFile(s.SettingsFile)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return st, nil
|
||||
@@ -179,6 +189,9 @@ func (s *Service) Settings() (Settings, error) {
|
||||
if st.HomeUsers == nil {
|
||||
st.HomeUsers = map[string]int64{}
|
||||
}
|
||||
if st.Shares == nil {
|
||||
st.Shares = map[string]int64{}
|
||||
}
|
||||
if st.WarnPercent < 1 || st.WarnPercent > 100 {
|
||||
st.WarnPercent = quota.DefaultWarnPercent
|
||||
}
|
||||
@@ -210,6 +223,71 @@ func (s *Service) Forget(ctx context.Context, user string) error {
|
||||
return s.Enforce(ctx)
|
||||
}
|
||||
|
||||
// ErrUnknownShare is returned for a limit on a share that doesn't exist.
|
||||
var ErrUnknownShare = errors.New("unknown share")
|
||||
|
||||
// SetShareLimit sets a share's soft limit in bytes; 0 removes it. Only for
|
||||
// shares with a folder that are reachable over SMB (the limit is enforced
|
||||
// there). The first limit sets up Samba (recorded in the change history).
|
||||
func (s *Service) SetShareLimit(ctx context.Context, actor, name string, limit int64) error {
|
||||
if err := quota.ValidLimit(limit); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrInvalid, err)
|
||||
}
|
||||
items, err := s.Shares()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var it *shares.Item
|
||||
for i := range items {
|
||||
if strings.EqualFold(items[i].Name, name) {
|
||||
it = &items[i]
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case it == nil:
|
||||
return fmt.Errorf("%w: %s", ErrUnknownShare, name)
|
||||
case it.Homes:
|
||||
return fmt.Errorf("%w: personal folders have their own limit per user", ErrInvalid)
|
||||
case it.Path == "" || it.SMB == nil:
|
||||
return fmt.Errorf("%w: a share limit is enforced over SMB, and this share isn't shared over SMB", ErrInvalid)
|
||||
}
|
||||
s.mu.Lock()
|
||||
st, err := s.Settings()
|
||||
if err == nil {
|
||||
if limit == 0 {
|
||||
delete(st.Shares, it.Name)
|
||||
} else {
|
||||
st.Shares[it.Name] = limit
|
||||
}
|
||||
err = s.save(st)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if limit > 0 {
|
||||
if _, err := s.Config.EnableLimits(ctx, actor); err != nil {
|
||||
return fmt.Errorf("the limit is saved, but Samba couldn't be set up for it: %w", err)
|
||||
}
|
||||
}
|
||||
return s.Enforce(ctx)
|
||||
}
|
||||
|
||||
// ForgetShare removes a deleted share's limit.
|
||||
func (s *Service) ForgetShare(ctx context.Context, name string) error {
|
||||
s.mu.Lock()
|
||||
st, err := s.Settings()
|
||||
if _, ok := st.Shares[name]; err == nil && ok {
|
||||
delete(st.Shares, name)
|
||||
err = s.save(st)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Enforce(ctx)
|
||||
}
|
||||
|
||||
// homeBase returns the folder holding one personal folder per user, or "".
|
||||
func (s *Service) homeBase() string {
|
||||
if s.Homes == nil {
|
||||
@@ -351,7 +429,10 @@ func (s *Service) Report(ctx context.Context) (Report, error) {
|
||||
if it.Path == "" || it.Homes {
|
||||
continue
|
||||
}
|
||||
r.Shares = append(r.Shares, ShareUsage{Name: it.Name, Path: it.Path, Used: last.ByRoot[filepath.Clean(it.Path)]})
|
||||
su := ShareUsage{Name: it.Name, Path: it.Path, Used: last.ByRoot[filepath.Clean(it.Path)], Limit: st.Shares[it.Name]}
|
||||
su.State, su.Percent = quota.Evaluate(su.Used, su.Limit, st.WarnPercent)
|
||||
su.ReadOnly = su.State == quota.Over && it.SMB != nil
|
||||
r.Shares = append(r.Shares, su)
|
||||
}
|
||||
}
|
||||
sort.Slice(r.Users, func(i, j int) bool { return r.Users[i].Name < r.Users[j].Name })
|
||||
@@ -517,6 +598,7 @@ func (s *Service) Enforce(ctx context.Context) error {
|
||||
s.log().Info("personal folder over its limit: read-only for the user", "user", u.Name)
|
||||
s.reconnect(ctx, u.Name, connected(readOnly, u.Name))
|
||||
}
|
||||
errs = append(errs, s.enforceShares(ctx, last, st, wantDFree))
|
||||
names, err := s.Files.Names(s.OverrideDir)
|
||||
errs = append(errs, err)
|
||||
for _, n := range names {
|
||||
@@ -541,6 +623,93 @@ func (s *Service) Enforce(ctx context.Context) error {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// enforceShares writes the file that makes full shares read-only over SMB
|
||||
// and their free-space files; shares whose state changed are reconnected.
|
||||
func (s *Service) enforceShares(ctx context.Context, last *Usage, st Settings, wantDFree map[string]bool) error {
|
||||
if s.ShareFile == "" {
|
||||
return nil
|
||||
}
|
||||
items, err := s.Shares()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var full []string
|
||||
var errs []error
|
||||
for _, it := range items {
|
||||
limit := st.Shares[it.Name]
|
||||
if limit <= 0 || it.Path == "" || it.Homes || it.SMB == nil {
|
||||
continue
|
||||
}
|
||||
p := filepath.Clean(it.Path)
|
||||
used := last.ByRoot[p]
|
||||
total, free := quota.DFree(used, limit)
|
||||
name := "share-" + strconv.FormatUint(fnv64(p), 16)
|
||||
wantDFree[name] = true
|
||||
errs = append(errs, s.writeIfChanged(filepath.Join(s.DFreeDir, name), fmt.Appendf(nil, "%d %d %s\n", total, free, p)))
|
||||
if state, _ := quota.Evaluate(used, limit, st.WarnPercent); state == quota.Over {
|
||||
full = append(full, it.Name)
|
||||
}
|
||||
}
|
||||
sort.Strings(full)
|
||||
content, err := quota.ShareOverride(full)
|
||||
if err != nil {
|
||||
return errors.Join(append(errs, err)...)
|
||||
}
|
||||
old, _ := s.Files.ReadFile(s.ShareFile)
|
||||
if string(old) == string(content) {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
if err := s.Files.WriteFile(s.ShareFile, content); err != nil {
|
||||
return errors.Join(append(errs, err)...)
|
||||
}
|
||||
before := sectionsIn(string(old))
|
||||
now := map[string]bool{}
|
||||
for _, n := range full {
|
||||
now[n] = true
|
||||
}
|
||||
for n := range now {
|
||||
if !before[n] {
|
||||
s.log().Info("share over its limit: read-only over SMB", "share", n)
|
||||
s.closeShare(ctx, n)
|
||||
}
|
||||
}
|
||||
for n := range before {
|
||||
if !now[n] {
|
||||
s.log().Info("share below its limit again: write access restored", "share", n)
|
||||
s.closeShare(ctx, n)
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// sectionsIn returns the share sections of an override file.
|
||||
func sectionsIn(content string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
if n, ok := strings.CutPrefix(strings.TrimSpace(line), "["); ok {
|
||||
if n, ok := strings.CutSuffix(n, "]"); ok && !strings.EqualFold(n, "global") {
|
||||
out[n] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func fnv64(s string) uint64 {
|
||||
h := fnv.New64a()
|
||||
_, _ = h.Write([]byte(s))
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
func (s *Service) closeShare(ctx context.Context, share string) {
|
||||
if s.Sessions == nil {
|
||||
return
|
||||
}
|
||||
if err := s.Sessions.CloseShare(ctx, share); err != nil {
|
||||
s.log().Warn("closing connections so the share limit applies", "share", share, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// connected returns the share names a user's connections may use for
|
||||
// sections: a personal folder is connected as "homes" or as the user's name.
|
||||
func connected(sections []string, user string) []string {
|
||||
|
||||
@@ -57,6 +57,11 @@ func (f *fakeConfig) LimitsConfigured() (bool, bool, error) { return f.enabled >
|
||||
|
||||
type fakeSessions struct{ calls []string }
|
||||
|
||||
func (f *fakeSessions) CloseShare(_ context.Context, share string) error {
|
||||
f.calls = append(f.calls, "*:"+share)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeSessions) Reconnect(_ context.Context, user string, sh []string) error {
|
||||
f.calls = append(f.calls, user+":"+strings.Join(sh, ","))
|
||||
return nil
|
||||
@@ -81,7 +86,7 @@ func setup() (*Service, memFiles, *fakeScanner, *fakeConfig, *fakeSessions) {
|
||||
{Share: share.Share{Name: "homes", Homes: true, SMB: &share.SMB{}}},
|
||||
}, nil
|
||||
},
|
||||
SettingsFile: "/data/limits.json", OverrideDir: "/etc/limits", DFreeDir: "/run/dfree", Interval: time.Minute,
|
||||
SettingsFile: "/data/limits.json", OverrideDir: "/etc/limits", ShareFile: "/etc/share-limits.conf", DFreeDir: "/run/dfree", Interval: time.Minute,
|
||||
}
|
||||
return s, files, sc, cfg, sess
|
||||
}
|
||||
@@ -340,3 +345,71 @@ func TestNewDefaultPinsOnlyUsersWithAFolder(t *testing.T) {
|
||||
t.Fatalf("sam: %v %d", err, mustSettings(t, s).HomeUsers["sam"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareLimit(t *testing.T) {
|
||||
s, files, _, cfg, sess := setup()
|
||||
ctx := context.Background()
|
||||
s.scan(ctx) // Family holds 6 GiB, Media 3 GiB
|
||||
if err := s.SetShareLimit(ctx, "admin", "family", 5*gib); err != nil { // name case-insensitive
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.enabled == 0 {
|
||||
t.Fatal("a share limit must set up Samba")
|
||||
}
|
||||
want, _ := quota.ShareOverride([]string{"Family"})
|
||||
if files["/etc/share-limits.conf"] != string(want) {
|
||||
t.Fatalf("share file %q", files["/etc/share-limits.conf"])
|
||||
}
|
||||
if len(sess.calls) != 1 || sess.calls[0] != "*:Family" {
|
||||
t.Fatalf("connections closed: %v", sess.calls)
|
||||
}
|
||||
var dfree string
|
||||
for _, n := range files.mustNames(t, "/run/dfree") {
|
||||
if strings.HasPrefix(n, "share-") {
|
||||
dfree = files["/run/dfree/"+n]
|
||||
}
|
||||
}
|
||||
if dfree != "5242880 1 /srv/family\n" {
|
||||
t.Fatalf("share dfree %q", dfree)
|
||||
}
|
||||
r, _ := s.Report(ctx)
|
||||
if f := r.Shares[0]; f.Name != "Family" || f.Limit != 5*gib || f.State != quota.Over || !f.ReadOnly {
|
||||
t.Fatalf("report %+v", f)
|
||||
}
|
||||
if p := s.Problems(ctx); len(p) != 1 || p[0].ID != "limit-share-Family" || !strings.Contains(strings.Join(p[0].Facts, " "), "soft limit") {
|
||||
t.Fatalf("problems %+v", p)
|
||||
}
|
||||
// Unchanged: nothing rewritten, nobody disconnected.
|
||||
if err := s.Enforce(ctx); err != nil || len(sess.calls) != 1 {
|
||||
t.Fatalf("err=%v %v", err, sess.calls)
|
||||
}
|
||||
// Raised: write access back, connections closed again so it applies.
|
||||
if err := s.SetShareLimit(ctx, "admin", "Family", 10*gib); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(files["/etc/share-limits.conf"], "[Family]") || len(sess.calls) != 2 {
|
||||
t.Fatalf("raised: %q %v", files["/etc/share-limits.conf"], sess.calls)
|
||||
}
|
||||
// Removed and forgotten.
|
||||
if err := s.SetShareLimit(ctx, "admin", "Family", 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st := mustSettings(t, s); len(st.Shares) != 0 {
|
||||
t.Fatalf("kept: %v", st.Shares)
|
||||
}
|
||||
for _, n := range files.mustNames(t, "/run/dfree") {
|
||||
if strings.HasPrefix(n, "share-") {
|
||||
t.Fatalf("share dfree left: %s", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareLimitIsOnlyForSMBShares(t *testing.T) {
|
||||
s, _, _, _, _ := setup()
|
||||
ctx := context.Background()
|
||||
for name, want := range map[string]error{"nobody": ErrUnknownShare, "nfs-only": ErrInvalid, "homes": ErrInvalid} {
|
||||
if err := s.SetShareLimit(ctx, "admin", name, gib); !errors.Is(err, want) {
|
||||
t.Errorf("%s: got %v, want %v", name, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,13 @@ func (s *Service) Clients(ctx context.Context) ([]Client, error) {
|
||||
// Reconnect closes the user's open connections to the given shares, so
|
||||
// changed settings (such as a storage limit) apply. SMB clients reconnect by
|
||||
// themselves; other users aren't affected (each connection is its own smbd
|
||||
// CloseShare closes every connection to a share, so a changed setting
|
||||
// (e.g. read-only because it is full) applies; clients reconnect by themselves.
|
||||
func (s *Service) CloseShare(ctx context.Context, share string) error {
|
||||
_, err := s.Run.Run(ctx, nil, "smbcontrol", "all", "close-share", share)
|
||||
return err
|
||||
}
|
||||
|
||||
// process).
|
||||
func (s *Service) Reconnect(ctx context.Context, user string, shares []string) error {
|
||||
raw, err := s.Run.Run(ctx, nil, "smbstatus", "--json")
|
||||
|
||||
@@ -71,6 +71,21 @@ func Override(user string, shares []string) ([]byte, error) {
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// ShareOverride is the file that makes full shares read-only for everyone
|
||||
// (repeated sections, read by the trailing include; see share.ShareLimitsInclude).
|
||||
func ShareOverride(shares []string) ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
b.WriteString("# Written by Sharestead: these shares are over their storage limit, so they are read-only over SMB.\n")
|
||||
for _, s := range shares {
|
||||
if err := smbconf.ValidateSectionName(s); err != nil {
|
||||
return nil, fmt.Errorf("share %q: %w", s, err)
|
||||
}
|
||||
fmt.Fprintf(&b, "[%s]\n\tread only = yes\n\twrite list =\n", s)
|
||||
}
|
||||
b.WriteString("[global]\n")
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
// DFree returns what clients see for a user with a limit, in KiB: the limit
|
||||
// as total size and the remaining space. The dfree script lowers the free
|
||||
// space to what the disk really has. At least 1 KiB is reported: Samba
|
||||
|
||||
@@ -75,3 +75,29 @@ func TestDFree(t *testing.T) {
|
||||
t.Errorf("over limit free = %d", free)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShareOverrideIsReadBackAsReadOnlyForEveryone(t *testing.T) {
|
||||
b, err := ShareOverride([]string{"Family", "Photos 2024"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
main := "[Family]\n\tread only = no\n\twrite list = alex\n[Photos 2024]\n\tread only = no\n[Media]\n\tread only = no\n[global]\n"
|
||||
f := smbconf.Parse(append([]byte(main), b...))
|
||||
for _, s := range []string{"Family", "Photos 2024"} {
|
||||
if v, _ := f.Get(s, "read only"); v != "yes" {
|
||||
t.Errorf("%s: read only = %q", s, v)
|
||||
}
|
||||
if v, _ := f.Get(s, "write list"); v != "" {
|
||||
t.Errorf("%s: write list = %q", s, v)
|
||||
}
|
||||
}
|
||||
if v, _ := f.Get("Media", "read only"); v != "no" {
|
||||
t.Error("a share below its limit must not change")
|
||||
}
|
||||
if _, err := ShareOverride([]string{"x]\n[evil"}); err == nil {
|
||||
t.Error("bad share name accepted")
|
||||
}
|
||||
if b, _ := ShareOverride(nil); string(b) != "# Written by Sharestead: these shares are over their storage limit, so they are read-only over SMB.\n[global]\n" {
|
||||
t.Errorf("no full shares: %q", b)
|
||||
}
|
||||
}
|
||||
@@ -6,30 +6,43 @@ import (
|
||||
"sharestead/internal/format/smbconf"
|
||||
)
|
||||
|
||||
// Storage limits (soft quotas) work through two global Samba settings:
|
||||
// Storage limits (soft) work through global Samba settings:
|
||||
//
|
||||
// - an include of a per-user file that makes shares read-only for a user
|
||||
// over the limit. Samba merges repeated sections and the last value wins,
|
||||
// so the include must come after every share definition;
|
||||
// - a dfree command that reports the user's remaining space to clients.
|
||||
// - includes that repeat share sections with "read only = yes": a per-user
|
||||
// file (a full personal folder) and one file for full shares. Samba
|
||||
// merges repeated sections and the last value wins, so the includes must
|
||||
// come after every share definition;
|
||||
// - a dfree command that reports the remaining space to clients.
|
||||
const (
|
||||
LimitsInclude = "/etc/samba/sharestead/limits/%U.conf"
|
||||
DFreeCommand = "/usr/lib/sharestead/dfree"
|
||||
LimitsInclude = "/etc/samba/sharestead/limits/%U.conf"
|
||||
ShareLimitsInclude = "/etc/samba/sharestead/share-limits.conf"
|
||||
DFreeCommand = "/usr/lib/sharestead/dfree"
|
||||
)
|
||||
|
||||
// LimitsEnabled reports whether smb.conf includes the per-user limit files.
|
||||
func LimitsEnabled(f *smbconf.File) bool {
|
||||
var limitIncludes = []string{LimitsInclude, ShareLimitsInclude}
|
||||
|
||||
func hasGlobalInclude(f *smbconf.File, value string) bool {
|
||||
for _, p := range f.Params(smbconf.GlobalSection) {
|
||||
if smbconf.NormalizeKey(p.Key) == "include" && p.Value == LimitsInclude {
|
||||
if smbconf.NormalizeKey(p.Key) == "include" && p.Value == value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// LimitsLast reports whether the limits include comes after every share.
|
||||
// LimitsEnabled reports whether smb.conf includes both limit files.
|
||||
func LimitsEnabled(f *smbconf.File) bool {
|
||||
return hasGlobalInclude(f, LimitsInclude) && hasGlobalInclude(f, ShareLimitsInclude)
|
||||
}
|
||||
|
||||
// LimitsLast reports whether the limit includes come after every share.
|
||||
func LimitsLast(f *smbconf.File) bool {
|
||||
return f.After(smbconf.GlobalSection, "include", LimitsInclude)
|
||||
for _, v := range limitIncludes {
|
||||
if hasGlobalInclude(f, v) && !f.After(smbconf.GlobalSection, "include", v) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// EnableLimits adds the settings storage limits need. The include is moved
|
||||
@@ -52,15 +65,28 @@ func EnableLimits(f *smbconf.File) (bool, error) {
|
||||
return changed || moved, err
|
||||
}
|
||||
|
||||
// KeepLimitsLast moves the limits include behind every share. With add set,
|
||||
// a missing include is added. It reports whether the file changed.
|
||||
// KeepLimitsLast moves the limit includes behind every share. With add set,
|
||||
// missing includes are added; without, only includes already there move.
|
||||
// It reports whether the file changed.
|
||||
func KeepLimitsLast(f *smbconf.File, add bool) (bool, error) {
|
||||
if !add && !LimitsEnabled(f) || LimitsLast(f) {
|
||||
var want []smbconf.Param
|
||||
for _, v := range limitIncludes {
|
||||
if add || hasGlobalInclude(f, v) {
|
||||
want = append(want, smbconf.Param{Key: "include", Value: v})
|
||||
}
|
||||
}
|
||||
complete := true
|
||||
for _, p := range want {
|
||||
complete = complete && hasGlobalInclude(f, p.Value)
|
||||
}
|
||||
if len(want) == 0 || (complete && LimitsLast(f)) {
|
||||
return false, nil
|
||||
}
|
||||
f.DeleteValue(smbconf.GlobalSection, "include", LimitsInclude)
|
||||
if err := f.AppendBlock(smbconf.GlobalSection, smbconf.Param{Key: "include", Value: LimitsInclude}); err != nil {
|
||||
return false, fmt.Errorf("adding the storage limit include: %w", err)
|
||||
for _, p := range want {
|
||||
f.DeleteValue(smbconf.GlobalSection, "include", p.Value)
|
||||
}
|
||||
if err := f.AppendBlock(smbconf.GlobalSection, want...); err != nil {
|
||||
return false, fmt.Errorf("adding the storage limit includes: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -13,7 +13,7 @@ func TestEnableLimitsAddsDFreeAndTrailingInclude(t *testing.T) {
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("changed=%v err=%v", changed, err)
|
||||
}
|
||||
want := "[global]\n\tworkgroup = HOME\n\tdfree command = " + DFreeCommand + "\n\n[Family]\n\tpath = /srv/family\n\n[global]\n\tinclude = " + LimitsInclude + "\n"
|
||||
want := "[global]\n\tworkgroup = HOME\n\tdfree command = " + DFreeCommand + "\n\n[Family]\n\tpath = /srv/family\n\n[global]\n\tinclude = " + LimitsInclude + "\n\tinclude = " + ShareLimitsInclude + "\n"
|
||||
if got := string(f.Bytes()); got != want {
|
||||
t.Fatalf("got\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func TestKeepLimitsLastMovesIncludeBehindNewShare(t *testing.T) {
|
||||
if err != nil || !moved || !LimitsLast(f) {
|
||||
t.Fatalf("moved=%v err=%v\n%s", moved, err, f.Bytes())
|
||||
}
|
||||
if n := strings.Count(string(f.Bytes()), LimitsInclude); n != 1 {
|
||||
if n := strings.Count(string(f.Bytes()), LimitsInclude) + strings.Count(string(f.Bytes()), ShareLimitsInclude); n != 2 {
|
||||
t.Fatalf("include appears %d times:\n%s", n, f.Bytes())
|
||||
}
|
||||
plain := smbconf.Parse([]byte("[a]\n\tpath = /a\n"))
|
||||
@@ -55,3 +55,29 @@ func TestKeepLimitsLastMovesIncludeBehindNewShare(t *testing.T) {
|
||||
t.Fatal("without limits nothing must be added")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldSetupGetsTheShareLimitsInclude(t *testing.T) {
|
||||
// Installs from before share limits have only the per-user include.
|
||||
old := "[a]\n\tpath = /a\n\n[global]\n\tdfree command = " + DFreeCommand + "\n\tinclude = " + LimitsInclude + "\n"
|
||||
f := smbconf.Parse([]byte(old))
|
||||
if LimitsEnabled(f) {
|
||||
t.Fatal("only one of two includes: not enabled")
|
||||
}
|
||||
if !LimitsLast(f) {
|
||||
t.Fatal("the include that is there is last")
|
||||
}
|
||||
// A new share without add: only the include that is there moves.
|
||||
g := smbconf.Parse([]byte(old))
|
||||
_ = g.AddSection("b")
|
||||
if moved, err := KeepLimitsLast(g, false); err != nil || !moved || strings.Contains(string(g.Bytes()), ShareLimitsInclude) {
|
||||
t.Fatalf("moved=%v err=%v\n%s", moved, err, g.Bytes())
|
||||
}
|
||||
// The first share limit: EnableLimits adds the second include, both last.
|
||||
changed, err := EnableLimits(f)
|
||||
if err != nil || !changed || !LimitsEnabled(f) || !LimitsLast(f) {
|
||||
t.Fatalf("changed=%v err=%v\n%s", changed, err, f.Bytes())
|
||||
}
|
||||
if n := strings.Count(string(f.Bytes()), LimitsInclude); n != 1 {
|
||||
t.Fatalf("per-user include %d times:\n%s", n, f.Bytes())
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,7 @@ var apiDocs = map[string]opDoc{
|
||||
"POST /api/v1/problems/fix": {Tag: "Problems", Summary: "Apply a one-click fix", Request: fixProblemRequest{}},
|
||||
"GET /api/v1/folders/capabilities": {Tag: "Folders", Summary: "Storage folders and what they support", Description: "Per storage folder (mounts below /srv, /mnt, /media, /data, and those folders): filesystem and whether POSIX ACLs work, found by trying it on a temporary folder. Without ACLs Sharestead works with access per share; subfolder permissions need ACLs. The result is kept for 10 minutes.", Response: capabilities.Report{}, Query: []queryParam{{Name: "fresh", Description: "1: check again now instead of the kept result", Schema: map[string]any{"type": "string", "enum": []string{"1"}}}}},
|
||||
"GET /api/v1/diagnostics": {Tag: "Problems", Summary: "Diagnostic bundle (ZIP)", Description: "For troubleshooting and bug reports: system and package versions, config files, testparm, service states, the last 300 log lines, current problems and the storage check. Passwords, password hashes, passkeys, the TLS key, sessions and API keys are not included; setting values named like password/secret/token are replaced. Still contains user, share and host names and IP addresses.", Response: []byte{}, MediaType: "application/zip"},
|
||||
"PUT /api/v1/shares/{name}/limit": {Tag: "Storage", Summary: "Set a share's soft limit", Description: "0 removes it. For shares reachable over SMB, where no hard limit is possible. Sharestead measures the folder every few minutes; over the limit the share is read-only over SMB for everyone, and clients see the space left in the limit. Writes on the server itself or over NFS aren't stopped.", Request: setShareLimitRequest{}},
|
||||
"GET /api/v1/updates": {Tag: "Updates", Summary: "Pending system updates", Description: "From a simulated upgrade; nothing is installed.", Response: updates.Status{}, Query: []queryParam{{Name: "fresh", Description: "1: check again now instead of the cached result", Schema: map[string]any{"type": "string", "enum": []string{"1"}}}}},
|
||||
"GET /api/v1/me/passkeys": {Tag: "Self-service", Summary: "My passkeys", Response: passkeyList{}},
|
||||
"POST /api/v1/me/passkeys/begin": {Tag: "Self-service", Summary: "Start adding a passkey", Description: "Returns WebAuthn options for navigator.credentials.create(). Needs a recent password and a host name (not an IP address).", Response: passkeyCreation{}, Confirm: true},
|
||||
|
||||
@@ -5,11 +5,13 @@ import (
|
||||
"net/http"
|
||||
|
||||
"sharestead/internal/app/quotas"
|
||||
"sharestead/internal/domain/quota"
|
||||
)
|
||||
|
||||
func (a *api) registerQuotas() {
|
||||
a.handle("GET", "/api/v1/storage", ScopeAdmin, a.storageReport)
|
||||
a.handle("POST", "/api/v1/storage/scan", ScopeAdmin, a.storageScan)
|
||||
a.handle("PUT", "/api/v1/shares/{name}/limit", ScopeAdmin, a.setShareLimit)
|
||||
}
|
||||
|
||||
func (a *api) storageReport(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -26,12 +28,35 @@ func (a *api) storageScan(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
|
||||
// setShareLimitRequest is the body of setShareLimit.
|
||||
type setShareLimitRequest struct {
|
||||
Limit int64 `json:"limit"` // bytes; 0 removes the limit
|
||||
}
|
||||
|
||||
func (a *api) setShareLimit(w http.ResponseWriter, r *http.Request) {
|
||||
var in setShareLimitRequest
|
||||
if !decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
err := a.quotas.SetShareLimit(r.Context(), sessionFrom(r).User, name, in.Limit)
|
||||
a.audit(r, "set share limit", name, err)
|
||||
summary := "Storage limit for share " + name + " removed"
|
||||
if in.Limit > 0 {
|
||||
summary = "Storage limit for share " + name + " set to " + quota.Size(in.Limit) + " (soft)"
|
||||
}
|
||||
a.record(r, summary, err)
|
||||
limitResponse(w, err)
|
||||
}
|
||||
|
||||
func limitResponse(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case err == nil:
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
case errors.Is(err, quotas.ErrInvalid):
|
||||
problem(w, http.StatusBadRequest, "invalid_input", "Please check your input", err.Error(), nil)
|
||||
case errors.Is(err, quotas.ErrUnknownShare):
|
||||
problem(w, http.StatusNotFound, "not_found", "Share not found", err.Error()+" — it may have been removed in the meantime; reload the page.", nil)
|
||||
case errors.Is(err, quotas.ErrUnknownUser):
|
||||
problem(w, http.StatusNotFound, "not_found", "Not found", err.Error()+" — it may have been removed in the meantime; reload the page.", nil)
|
||||
default:
|
||||
|
||||
@@ -153,6 +153,11 @@ func (a *api) deleteShare(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
res, err := a.editor.DeleteShare(r.Context(), sessionFrom(r).User, name, in.Base, dryRun(r))
|
||||
if err == nil && !dryRun(r) && a.quotas != nil {
|
||||
if ferr := a.quotas.ForgetShare(r.Context(), name); ferr != nil {
|
||||
a.log.Warn("removing the deleted share's limit", "share", name, "error", ferr)
|
||||
}
|
||||
}
|
||||
a.edit(w, r, "delete share", name, res, err)
|
||||
}
|
||||
|
||||
|
||||
+10
-2
@@ -1,8 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Samba "dfree command" for Sharestead storage limits. Samba runs it as the
|
||||
# connected user, in the share's folder, and reads "total free" in KiB.
|
||||
# In the user's personal folder with a folder limit, that limit is shown.
|
||||
# Free space is never more than the disk really has. If this script fails, Samba reports the disk's
|
||||
# In the user's personal folder with a folder limit, that limit is shown;
|
||||
# in a share with a limit, the share's limit. Free space is never more than
|
||||
# the disk really has. If this script fails, Samba reports the disk's
|
||||
# own values.
|
||||
#
|
||||
# The disk is read through /proc/self/cwd: Samba runs this without the
|
||||
@@ -19,6 +20,13 @@ limit=""
|
||||
if [ -r "$dir.home" ] && read -r htotal hfree hpath < "$dir.home"; then
|
||||
case "$cwd/" in "$hpath"/*) limit="$htotal $hfree" ;; esac
|
||||
fi
|
||||
# share-*: "total free path" of a share with a limit
|
||||
if [ -z "$limit" ]; then
|
||||
for f in /run/sharestead/dfree/share-*; do
|
||||
[ -r "$f" ] && read -r stotal sfree spath < "$f" || continue
|
||||
case "$cwd/" in "$spath"/*) limit="$stotal $sfree"; break ;; esac
|
||||
done
|
||||
fi
|
||||
if [ -n "$limit" ]; then
|
||||
set -- $limit
|
||||
total=$1
|
||||
|
||||
@@ -19,11 +19,14 @@ mkdir -p /srv/sst-test/homes
|
||||
install -d -o kim -m 0700 /srv/sst-test/homes/kim
|
||||
head -c 2000000 /dev/urandom > /srv/sst-test/homes/kim/kim-data.bin
|
||||
chown kim /srv/sst-test/homes/kim/kim-data.bin
|
||||
# The Family share holds 2 MB, for the share limit test.
|
||||
head -c 2000000 /dev/urandom > /srv/sst-test/family/family-data.bin
|
||||
chown alex /srv/sst-test/family/family-data.bin
|
||||
# ZFS reports a new file's size only once it is written out (a few seconds);
|
||||
# wait for it, so Sharestead's first measurement sees the 2 MB.
|
||||
sync
|
||||
for _ in $(seq 1 30); do
|
||||
[ "$(stat -c %b /srv/sst-test/homes/kim/kim-data.bin)" -ge 3900 ] && break
|
||||
[ "$(stat -c %b /srv/sst-test/homes/kim/kim-data.bin)" -ge 3900 ] && [ "$(stat -c %b /srv/sst-test/family/family-data.bin)" -ge 3900 ] && break
|
||||
sleep 1
|
||||
done
|
||||
id e2e-admin >/dev/null 2>&1 || useradd -M -s /usr/sbin/nologin -G sharestead-admins e2e-admin
|
||||
|
||||
@@ -688,6 +688,36 @@ test('problems: diagnostic bundle downloads as a ZIP without the password', asyn
|
||||
expect(body.includes(Buffer.from(pass))).toBe(false); // entries are deflated, so this is a weak check; unit tests cover the redaction
|
||||
});
|
||||
|
||||
test('share limit (soft): a full share is read-only over SMB, shown on page, list and Problems; removed again', async ({ page, isMobile }, info) => {
|
||||
const errors = watchConsole(page, true);
|
||||
await login(page);
|
||||
await page.goto('/#/shares/Family');
|
||||
const card = page.locator('section.card', { has: page.getByRole('heading', { name: 'Size limit' }) });
|
||||
await expect(card).toBeVisible();
|
||||
test.skip(await card.getByText('hard limit').count() > 0, 'Family has a hard limit here');
|
||||
if (await card.getByRole('button', { name: 'Remove limit' }).count()) { // left over from an earlier run
|
||||
await card.getByRole('button', { name: 'Remove limit' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('Limit removed.');
|
||||
}
|
||||
await card.getByLabel('Soft limit', { exact: true }).fill('1'); // the share holds 2 MB (e2e-setup)
|
||||
await card.getByLabel('Unit').selectOption('MB');
|
||||
await card.getByRole('button', { name: 'Save limit' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('Limit set to 1 MB (soft).');
|
||||
await expect(card).toContainText('full — read-only over SMB', { timeout: 15_000 });
|
||||
await expect(card).toContainText('Writes on the server itself or over NFS aren’t stopped');
|
||||
await page.screenshot({ path: `e2e-results/screens/${info.project.name}-share-limit-full.png`, fullPage: true, caret: 'initial', animations: 'disabled' });
|
||||
await openNav(page, 'Problems', isMobile);
|
||||
await expect(page.getByText('Share Family is full')).toBeVisible();
|
||||
await openNav(page, 'Shares', isMobile);
|
||||
await expect(page.getByRole('row').filter({ has: page.getByRole('link', { name: 'Family', exact: true }) })).toContainText('full');
|
||||
await page.goto('/#/shares/Family');
|
||||
await card.getByRole('button', { name: 'Remove limit' }).click();
|
||||
await expect(card.getByRole('status')).toContainText('Limit removed.');
|
||||
await openNav(page, 'Problems', isMobile);
|
||||
await expect(page.getByText('Share Family is full')).toHaveCount(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('share page says what each protocol checks and what not', async ({ page }) => {
|
||||
await login(page);
|
||||
await page.goto('/#/shares/Media');
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<script lang="ts">
|
||||
// A share's size limit (F-QUO-8): a hard limit set outside is shown; where
|
||||
// none is set, a soft limit can be set here; not possible: greyed + reason.
|
||||
import { onMount } from 'svelte';
|
||||
import { api } from '../lib/api';
|
||||
import type { Problem, Share, StorageFolder } from '../lib/types';
|
||||
import { toProblem } from '../lib/errors';
|
||||
import { bytes } from '../lib/format';
|
||||
import { storage, ago } from '../lib/storage.svelte';
|
||||
import { health } from '../lib/health.svelte';
|
||||
import { ownLimit } from '../lib/storage-groups';
|
||||
import { href } from '../lib/router.svelte';
|
||||
import Banner from './Banner.svelte';
|
||||
import HelpIcon from './HelpIcon.svelte';
|
||||
import FieldLabel from './FieldLabel.svelte';
|
||||
import Notice from './Notice.svelte';
|
||||
import SizeInput from './SizeInput.svelte';
|
||||
import UsageBar from './UsageBar.svelte';
|
||||
|
||||
let { share }: { share: Share } = $props();
|
||||
let folders = $state<StorageFolder[]>([]);
|
||||
onMount(() => { api.folderCapabilities().then((r) => { folders = r.folders; }).catch(() => {}); });
|
||||
|
||||
const usage = $derived(storage.report?.shares.find((x) => x.name === share.name));
|
||||
const hard = $derived(ownLimit(share, folders));
|
||||
const why = $derived(share.homes ? 'homes' : !share.smb || !share.path ? 'nosmb' : '');
|
||||
let limitBytes = $state(0);
|
||||
let valid = $state(true);
|
||||
let busy = $state(false);
|
||||
let problem = $state<Problem | null>(null);
|
||||
let ok = $state('');
|
||||
$effect(() => { limitBytes = usage?.limit ?? 0; });
|
||||
|
||||
async function save(limit: number) {
|
||||
busy = true; problem = null; ok = '';
|
||||
try {
|
||||
await api.setShareLimit(share.name, limit);
|
||||
await Promise.all([storage.refresh(), health.refresh()]);
|
||||
ok = limit ? `Limit set to ${bytes(limit)} (soft).` : 'Limit removed.';
|
||||
} catch (err) { problem = toProblem(err); } finally { busy = false; }
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="card" aria-labelledby="limit-title">
|
||||
<div class="row between lab"><h2 id="limit-title">Size limit</h2>{#if !hard && why === ''}<span class="pill">soft</span>{/if}</div>
|
||||
{#if why === 'homes'}
|
||||
<p class="muted small">Personal folders have a limit per user: on each user’s page, default under <a href={href('system')}>System → Personal folders</a>.</p>
|
||||
{:else if hard}
|
||||
<div class="row between"><b>{usage ? bytes(usage.used) + ' of ' : ''}{bytes(hard)}</b><span class="pill acc">hard limit</span></div>
|
||||
{#if usage}<UsageBar used={usage.used} total={hard} label="Share size of its hard limit" warn={storage.report?.warn_percent ?? 90} bad={100} />{/if}
|
||||
<p class="facts">Set outside Sharestead<HelpIcon term="hardLimit" />: the filesystem enforces it for everything that writes here, at once.</p>
|
||||
{#if usage?.limit}
|
||||
<div class="row between soft-too">
|
||||
<span class="small">Also a soft limit: <b>{bytes(usage.limit)}</b>{#if usage.state === 'over'} <span class="pill bad">full — read-only over SMB</span>{/if}</span>
|
||||
<button class="btn sm" onclick={() => save(0)} disabled={busy}>Remove soft limit</button>
|
||||
</div>
|
||||
<Notice {ok} {problem} />
|
||||
{/if}
|
||||
{:else}
|
||||
<fieldset class="lim" disabled={why !== ''}>
|
||||
<legend class="sr-only">Soft limit</legend>
|
||||
{#if usage?.limit}
|
||||
<div class="row between">
|
||||
<b class:over={usage.state === 'over'}>{bytes(usage.used)} of {bytes(usage.limit)}</b>
|
||||
{#if usage.state === 'over'}<span class="pill bad">full — read-only over SMB</span>{:else if usage.state === 'warning'}<span class="pill warn">almost full</span>{:else}<span class="pill ok">within the limit</span>{/if}
|
||||
</div>
|
||||
<UsageBar used={usage.used} total={usage.limit} label="Share size of its limit" warn={storage.report?.warn_percent ?? 90} bad={100} />
|
||||
{#if usage.state === 'over'}<Banner kind="warn" compact>Nobody can save new files in this share over SMB until it is below the limit. Writes on the server itself or over NFS aren’t stopped{usage.used > usage.limit ? ', which is how it got past the limit' : ''}.</Banner>{/if}
|
||||
{/if}
|
||||
<FieldLabel for="share-limit" term="shareLimit">Soft limit</FieldLabel>
|
||||
<div class="row wrap">
|
||||
<SizeInput id="share-limit" label="Soft limit" bind:bytes={limitBytes} bind:valid />
|
||||
<button class="btn primary" onclick={() => save(limitBytes)} disabled={busy || !valid || limitBytes === (usage?.limit ?? 0)}>Save limit</button>
|
||||
{#if usage?.limit}<button class="btn" onclick={() => save(0)} disabled={busy}>Remove limit</button>{/if}
|
||||
</div>
|
||||
</fieldset>
|
||||
{#if why === 'nosmb'}
|
||||
<p class="facts">Not available: a soft limit is enforced over SMB, and this share isn’t shared over SMB.</p>
|
||||
{:else}
|
||||
<p class="facts">Measured every few minutes{storage.report?.scanned_at ? ` (last: ${ago(storage.report.scanned_at)})` : ''}. Only uploads over SMB are stopped; writes on the server itself or over NFS aren’t.</p>
|
||||
{/if}
|
||||
<Notice {ok} {problem} />
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<style>
|
||||
.lim { border: 0; padding: 0; margin: 0; }
|
||||
.lim:disabled { opacity: .55; }
|
||||
.over { color: var(--bad); }
|
||||
.lab { margin-bottom: 4px; }
|
||||
.soft-too { margin-top: 10px; gap: 8px; flex-wrap: wrap; }
|
||||
</style>
|
||||
@@ -130,6 +130,7 @@ export const api = {
|
||||
createGroup: (name: string, members: string[]) => request<void>('POST', '/api/v1/groups', { name, members }),
|
||||
setMembers: (name: string, members: string[]) => request<void>('PUT', '/api/v1/groups/' + encodeURIComponent(name) + '/members', { members }),
|
||||
updates: (fresh = false) => request<UpdateStatus>('GET', '/api/v1/updates' + (fresh ? '?fresh=1' : '')),
|
||||
setShareLimit: (name: string, limit: number) => request<void>('PUT', '/api/v1/shares/' + encodeURIComponent(name) + '/limit', { limit }),
|
||||
folderCapabilities: (fresh = false) => request<FolderCapabilities>('GET', '/api/v1/folders/capabilities' + (fresh ? '?fresh=1' : '')),
|
||||
homes: () => request<{ homes: HomesStatus; default_limit: number }>('GET', '/api/v1/homes'),
|
||||
setHomes: (h: { enabled: boolean; folder: string; create_folders: boolean }, dry: boolean, base?: Record<string, string>) =>
|
||||
|
||||
@@ -8,6 +8,8 @@ export const glossary: Record<string, Entry> = {
|
||||
nfs: { title: 'NFS', body: 'The usual way for Linux PCs and servers to use network folders. It trusts the device, not a password: the user ID sent by the PC decides who owns files, so your Linux user should have the same UID as on the NAS.', tech: 'NFSv3 / NFSv4, sec=sys' },
|
||||
custom: { title: 'Custom settings', body: 'This share uses settings the simple view can’t show exactly (for example %U macros or limits by IP address). Sharestead keeps them as they are and shows the reason instead of guessing.', tech: 'smb.conf' },
|
||||
homes: { title: 'Personal folders', body: 'Every user gets their own private folder, reachable as \\\\nas\\<user name>. Nobody else can open it.', tech: '[homes]' },
|
||||
shareLimit: { title: 'Share limit (soft)', body: 'How big the share may get, measured by Sharestead every few minutes. When it is full, the share is read-only over SMB for everyone until it is smaller again; PCs show the space left as free space. Soft: it counts the space used on disk (after compression), between two measurements it can grow past the limit, and writes on the server itself or over NFS aren’t stopped.', tech: 'folder size on disk · read only = yes via include · dfree' },
|
||||
hardLimit: { title: 'Hard limit', body: 'A limit the filesystem itself enforces, set outside Sharestead (e.g. a ZFS dataset quota or an XFS/ext4 project quota). It applies to everything that writes there, at once. Sharestead shows it as the folder’s size.', tech: 'shown from statfs' },
|
||||
homeLimit: { title: 'Personal folder limit (soft)', body: 'How big this user’s personal folder may get. Sharestead measures the folder every few minutes. Over the limit, the user can still open files there but can’t save new ones over SMB until it is smaller again. Soft: between two measurements the folder can grow past the limit, and NFS isn’t limited. PCs and Macs show the space left in the limit as free space.', tech: 'folder size of <personal folders>/<user> · read only = yes · dfree' },
|
||||
smb: { title: 'SMB', body: 'The way Windows, macOS, Linux file managers and most TV apps open network folders. Each person logs in with their user name and password.', tech: 'Samba · TCP 445' },
|
||||
minProtocol: { title: 'Minimum SMB version', body: 'The oldest SMB version devices may use. SMB2 works with nearly everything since Windows 7. SMB1 has known security holes; only turn it on for very old devices.', tech: 'server min protocol' },
|
||||
|
||||
@@ -50,7 +50,7 @@ export interface HealthProblem { id: string; severity: 'critical' | 'warning'; t
|
||||
|
||||
export type LimitState = 'none' | 'ok' | 'warning' | 'over';
|
||||
export interface UserUsage { name: string; uid: number; read_only: boolean; home?: HomeUsage }
|
||||
export interface ShareUsage { name: string; path: string; used: number }
|
||||
export interface ShareUsage { name: string; path: string; used: number; limit: number; percent: number; state: LimitState; read_only: boolean }
|
||||
export interface StorageReport { scanned_at?: string; took_ms: number; scanning: boolean; error?: string; unreadable: number; next_scan?: string; warn_percent: number; users: UserUsage[]; shares: ShareUsage[] }
|
||||
|
||||
export interface PendingPackage { name: string; from?: string; to: string; security: boolean; relevant: boolean }
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
const withUsage = $derived(shares.filter((s) => s.usage));
|
||||
const report = $derived(storage.report);
|
||||
const sizeOf = (name: string) => report?.shares.find((x) => x.name === name)?.used;
|
||||
const softOf = (name: string) => report?.shares.find((x) => x.name === name);
|
||||
const largest = $derived(Math.max(1, ...(report?.shares.map((x) => x.used) ?? [1])));
|
||||
// The largest shares; all of them are on the Shares page.
|
||||
const TOP = 8;
|
||||
@@ -85,7 +86,7 @@
|
||||
<tr>
|
||||
<td class="name"><a href={href('shares', s.name)}>{s.name}</a></td>
|
||||
<td class="barcell">{#if size !== undefined}<UsageBar used={size} total={largest} label={'Size of ' + s.name + ' compared to the largest share'} warn={101} bad={101} />{/if}</td>
|
||||
<td class="small nowrap">{size === undefined ? 'not measured yet' : bytes(size)}{#if limit}<div class="muted">limit {bytes(limit)}</div>{/if}</td>
|
||||
<td class="small nowrap" class:over={softOf(s.name)?.state === 'over'}>{size === undefined ? 'not measured yet' : bytes(size)}{#if limit}<div class="muted">limit {bytes(limit)} (hard)</div>{:else if softOf(s.name)?.limit}<div class="muted">limit {bytes(softOf(s.name)!.limit)} (soft)</div>{/if}</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import Notice from '../components/Notice.svelte';
|
||||
import { segments } from '../lib/text';
|
||||
import { ago } from '../lib/storage.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
let busy = $state(false);
|
||||
let ok = $state('');
|
||||
@@ -14,6 +15,8 @@
|
||||
let checked = $state(new Date());
|
||||
|
||||
async function check() { busy = true; await health.refresh(); checked = new Date(); busy = false; }
|
||||
// Opening the page shows the current state, not the last background check.
|
||||
onMount(check);
|
||||
async function fix(p: HealthProblem) {
|
||||
if (!p.fix) return;
|
||||
busy = true; ok = ''; problem = null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import ProtocolChecks from '../components/ProtocolChecks.svelte';
|
||||
import ShareLimitCard from '../components/ShareLimitCard.svelte';
|
||||
import { protocolChecks } from '../lib/protocols';
|
||||
import { services as svcState } from '../lib/services-state.svelte';
|
||||
import { onMount as onMountSvc } from 'svelte';
|
||||
@@ -248,6 +249,8 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="stack">
|
||||
<ShareLimitCard {share} />
|
||||
{#if share.homes && share.smb}
|
||||
<div class="card">
|
||||
<h2>Connect</h2>
|
||||
@@ -260,6 +263,7 @@
|
||||
<ConnectHelp name={share.name} smb={!!share.smb} nfsPath={share.nfs ? share.path : ''} />
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if !share.homes}
|
||||
<div class="card danger-zone mt">
|
||||
@@ -279,6 +283,7 @@
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.stack { display: grid; gap: 16px; align-content: start; }
|
||||
.add { margin-top: 10px; } .add select { max-width: 320px; }
|
||||
.opts { margin-top: 8px; } .optbox { margin-top: 8px; padding-top: 4px; border-top: 1px solid var(--line); }
|
||||
.end { justify-content: flex-end; margin-top: 12px; }
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import { services as svcState } from '../lib/services-state.svelte';
|
||||
import { onMount as onMountSvc } from 'svelte';
|
||||
const sizeOf = (name: string) => storage.report?.shares.find((x) => x.name === name)?.used;
|
||||
const usageOf = (name: string) => storage.report?.shares.find((x) => x.name === name);
|
||||
|
||||
let { shares }: { shares: Share[] } = $props();
|
||||
const nfsOn = $derived(svcState.on('nfs'));
|
||||
@@ -53,7 +54,7 @@
|
||||
{#if s.smb && !s.smb.browsable}<span class="pill">hidden</span>{/if}
|
||||
</td>
|
||||
<td class="small nowrap" data-label="Size">
|
||||
{#if s.problem}<span class="pill bad">⛔ problem</span>{:else if sizeOf(s.name) !== undefined}{bytes(sizeOf(s.name) ?? 0)}{:else if s.homes}<span class="muted">—</span>{:else}<span class="muted">not measured yet</span>{/if}
|
||||
{#if s.problem}<span class="pill bad">⛔ problem</span>{:else if usageOf(s.name)}{bytes(usageOf(s.name)!.used)}{#if usageOf(s.name)!.limit} / {bytes(usageOf(s.name)!.limit)}{/if}{#if usageOf(s.name)!.state === 'over'} <span class="pill bad">full</span>{:else if usageOf(s.name)!.state === 'warning'} <span class="pill warn">{Math.round(usageOf(s.name)!.percent)} %</span>{/if}{:else if s.homes}<span class="muted">—</span>{:else}<span class="muted">not measured yet</span>{/if}
|
||||
</td>
|
||||
</tr>
|
||||
{:else}
|
||||
|
||||
Reference in new issue
Block a user