fork/gdu

git clone https://git.julia.blue/fork/gdu

yurenchen000Feat: Show symlink target #260 (#612)1eaa266

subvolume
5.1 KiB223 linesraw
1// Package webui implements a web-based frontend for Gdu. It serves an embedded
2// React single-page application and a small, bounded JSON API over the
3// in-memory analysis tree, streaming scan progress via Server-Sent Events.
4package webui
5
6import (
7	"encoding/json"
8	"io"
9	"sync"
10	"time"
11
12	log "github.com/sirupsen/logrus"
13
14	"github.com/dundee/gdu/v5/internal/common"
15	"github.com/dundee/gdu/v5/pkg/analyze"
16	"github.com/dundee/gdu/v5/pkg/device"
17	"github.com/dundee/gdu/v5/pkg/fs"
18	"github.com/dundee/gdu/v5/report"
19)
20
21// progressPollInterval is how often the scan progress is sampled and broadcast.
22const progressPollInterval = 100 * time.Millisecond
23
24// UI is the web frontend. It embeds the shared *common.UI so that all the
25// generic Set* configuration methods are provided for free; only the
26// frontend-specific methods are implemented in this package.
27type UI struct {
28	*common.UI
29
30	output      io.Writer
31	listenAddr  string
32	openBrowser bool
33	browserCmd  string
34
35	getter  device.DevicesInfoGetter
36	devices device.Devices
37
38	mu           sync.RWMutex
39	topDir       fs.Item
40	topDirPath   string
41	linkedItems  fs.HardLinkedItems
42	collapsePath bool
43	scanning     bool
44	scanErr      error
45	progress     common.CurrentProgress
46
47	hub *hub
48}
49
50// CreateUI creates a new web UI.
51func CreateUI(
52	output io.Writer,
53	listenAddr string,
54	openBrowser bool,
55	browserCmd string,
56	useColors bool,
57	showApparentSize bool,
58	showRelativeSize bool,
59	useSIPrefix bool,
60) *UI {
61	ui := &UI{
62		UI: &common.UI{
63			UseColors:        useColors,
64			ShowApparentSize: showApparentSize,
65			ShowRelativeSize: showRelativeSize,
66			UseSIPrefix:      useSIPrefix,
67			Analyzer:         analyze.CreateAnalyzer(),
68		},
69		output:      output,
70		listenAddr:  listenAddr,
71		openBrowser: openBrowser,
72		browserCmd:  browserCmd,
73		linkedItems: make(fs.HardLinkedItems),
74		hub:         newHub(),
75	}
76	if listenAddr == "" {
77		ui.listenAddr = "localhost:0"
78	}
79	if !useSIPrefix {
80		ui.SetBlockSizeFromEnvironment()
81	}
82	return ui
83}
84
85// SetCollapsePath sets whether single-child directory chains are collapsed.
86func (ui *UI) SetCollapsePath(value bool) {
87	ui.collapsePath = value
88}
89
90// SetShowSymlinkTarget is a no-op for the web UI (rendering is browser-side).
91func (ui *UI) SetShowSymlinkTarget(value bool) {
92}
93
94// ListDevices loads mounted devices so they can be served to the browser.
95func (ui *UI) ListDevices(getter device.DevicesInfoGetter) error {
96	ui.getter = getter
97	devices, err := getter.GetDevicesInfo()
98	if err != nil {
99		return err
100	}
101	ui.mu.Lock()
102	ui.devices = devices
103	ui.mu.Unlock()
104	return nil
105}
106
107// AnalyzePath analyzes disk usage in the given path in the background while the
108// HTTP server serves progress and partial results.
109func (ui *UI) AnalyzePath(path string, parentDir fs.Item) error {
110	ui.mu.Lock()
111	ui.scanning = true
112	ui.scanErr = nil
113	ui.topDirPath = path
114	ui.mu.Unlock()
115
116	ui.Analyzer.ResetProgress()
117
118	scanDone := make(chan struct{})
119	go ui.pollProgress(scanDone)
120
121	go func() {
122		dir := ui.Analyzer.AnalyzeDir(path, ui.CreateIgnoreFunc(), ui.CreateFileTypeFilter())
123
124		if parentDir != nil {
125			dir.SetParent(parentDir)
126			parentDir.RemoveFileByName(dir.GetName())
127			parentDir.AddFile(dir)
128		}
129
130		if ui.IsFilteringFiles() {
131			dir.UpdateStatsWithFileFiltering(ui.linkedItems)
132		} else {
133			dir.UpdateStats(ui.linkedItems)
134		}
135
136		ui.mu.Lock()
137		if parentDir == nil {
138			ui.topDir = dir
139			ui.topDirPath = dir.GetPath()
140		}
141		ui.scanning = false
142		ui.mu.Unlock()
143
144		close(scanDone)
145		ui.hub.publish(ui.statusJSON())
146	}()
147
148	return nil
149}
150
151// ReadAnalysis reads an analysis report from a JSON reader and serves it.
152func (ui *UI) ReadAnalysis(input io.Reader) error {
153	ui.mu.Lock()
154	ui.scanning = true
155	ui.mu.Unlock()
156
157	dir, err := report.ReadAnalysis(input)
158	if err != nil {
159		ui.mu.Lock()
160		ui.scanning = false
161		ui.scanErr = err
162		ui.mu.Unlock()
163		return err
164	}
165	dir.UpdateStats(ui.linkedItems)
166
167	ui.mu.Lock()
168	ui.topDir = dir
169	ui.topDirPath = dir.GetPath()
170	ui.scanning = false
171	ui.mu.Unlock()
172	return nil
173}
174
175// ReadFromStorage reads a previously stored analysis and serves it.
176func (ui *UI) ReadFromStorage(storagePath, path string) error {
177	storage := analyze.NewStorage(storagePath, path)
178	closeFn := storage.Open()
179	defer closeFn()
180
181	dir, err := storage.GetDirForPath(path)
182	if err != nil {
183		return err
184	}
185	dir.UpdateStats(ui.linkedItems)
186
187	ui.mu.Lock()
188	ui.topDir = dir
189	ui.topDirPath = dir.GetPath()
190	ui.scanning = false
191	ui.mu.Unlock()
192	return nil
193}
194
195// pollProgress samples the analyzer progress and broadcasts it until the scan
196// goroutine signals completion by closing scanDone.
197func (ui *UI) pollProgress(scanDone <-chan struct{}) {
198	ticker := time.NewTicker(progressPollInterval)
199	defer ticker.Stop()
200
201	for {
202		select {
203		case <-scanDone:
204			return
205		case <-ticker.C:
206			p := ui.Analyzer.GetProgress()
207			ui.mu.Lock()
208			ui.progress = p
209			ui.mu.Unlock()
210			ui.hub.publish(ui.statusJSON())
211		}
212	}
213}
214
215// statusJSON renders the current scan status as a JSON string for SSE.
216func (ui *UI) statusJSON() string {
217	data, err := json.Marshal(ui.buildStatus())
218	if err != nil {
219		log.Printf("webui: marshaling status: %s", err)
220		return `{"state":"error"}`
221	}
222	return string(data)
223}