fork/gdu
git clone https://git.julia.blue/fork/gdu
34f3996
master
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 30output io.Writer 31listenAddr string 32openBrowser bool 33browserCmd string 34 35getter device.DevicesInfoGetter 36devices device.Devices 37 38mu sync.RWMutex 39topDir fs.Item 40topDirPath string 41linkedItems fs.HardLinkedItems 42collapsePath bool 43scanning bool 44scanErr error 45progress common.CurrentProgress 46 47hub * hub 48} 49 50// CreateUI creates a new web UI. 51func CreateUI ( 52output io.Writer , 53listenAddr string , 54openBrowser bool , 55browserCmd string , 56useColors bool , 57showApparentSize bool , 58showRelativeSize bool , 59useSIPrefix bool , 60)* UI { 61ui := & UI { 62UI :& common.UI { 63UseColors :useColors , 64ShowApparentSize :showApparentSize , 65ShowRelativeSize :showRelativeSize , 66UseSIPrefix :useSIPrefix , 67Analyzer :analyze .CreateAnalyzer (), 68 }, 69output :output , 70listenAddr :listenAddr , 71openBrowser :openBrowser , 72browserCmd :browserCmd , 73linkedItems :make (fs.HardLinkedItems ), 74hub :newHub (), 75 } 76if listenAddr == "" { 77ui .listenAddr = "localhost:0" 78 } 79if ! useSIPrefix { 80ui .SetBlockSizeFromEnvironment () 81 } 82return ui 83} 84 85// SetCollapsePath sets whether single-child directory chains are collapsed. 86func (ui * UI )SetCollapsePath (value bool ) { 87ui .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 { 96ui .getter = getter 97devices ,err := getter .GetDevicesInfo () 98if err != nil { 99return err 100 } 101ui .mu .Lock () 102ui .devices = devices 103ui .mu .Unlock () 104return 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 { 110ui .mu .Lock () 111ui .scanning = true 112ui .scanErr = nil 113ui .topDirPath = path 114ui .mu .Unlock () 115 116ui .Analyzer .ResetProgress () 117 118scanDone := make (chan struct {}) 119go ui .pollProgress (scanDone ) 120 121go func () { 122dir := ui .Analyzer .AnalyzeDir (path ,ui .CreateIgnoreFunc (),ui .CreateFileTypeFilter ()) 123 124if parentDir != nil { 125dir .SetParent (parentDir ) 126parentDir .RemoveFileByName (dir .GetName ()) 127parentDir .AddFile (dir ) 128 } 129 130if ui .IsFilteringFiles () { 131dir .UpdateStatsWithFileFiltering (ui .linkedItems ) 132 }else { 133dir .UpdateStats (ui .linkedItems ) 134 } 135 136ui .mu .Lock () 137if parentDir == nil { 138ui .topDir = dir 139ui .topDirPath = dir .GetPath () 140 } 141ui .scanning = false 142ui .mu .Unlock () 143 144close (scanDone ) 145ui .hub .publish (ui .statusJSON ()) 146 }() 147 148return nil 149} 150 151// AnalyzePaths scans several roots one after another and serves them under a 152// virtual top level dir. The roots are scanned sequentially because the 153// analyzer owns a single set of progress channels. 154func (ui * UI )AnalyzePaths (paths []string )error { 155if len (paths )== 1 { 156return ui .AnalyzePath (paths [0 ],nil ) 157 } 158 159ui .mu .Lock () 160ui .scanning = true 161ui .scanErr = nil 162ui .topDirPath = analyze .VirtualRootName 163ui .mu .Unlock () 164 165go func () { 166roots := make ([]fs.Item ,0 ,len (paths )) 167for _ ,path := range paths { 168ui .Analyzer .ResetProgress () 169 170scanDone := make (chan struct {}) 171go ui .pollProgress (scanDone ) 172 173roots = append ( 174roots , 175ui .Analyzer .AnalyzeDir (path ,ui .CreateIgnoreFunc (),ui .CreateFileTypeFilter ()), 176 ) 177close (scanDone ) 178 } 179 180dir := analyze .CreateVirtualRootDir (roots ... ) 181if ui .IsFilteringFiles () { 182dir .UpdateStatsWithFileFiltering (ui .linkedItems ) 183 }else { 184dir .UpdateStats (ui .linkedItems ) 185 } 186 187ui .mu .Lock () 188ui .topDir = dir 189ui .topDirPath = dir .GetPath () 190ui .scanning = false 191ui .mu .Unlock () 192 193ui .hub .publish (ui .statusJSON ()) 194 }() 195 196return nil 197} 198 199// ReadAnalysis reads an analysis report from a JSON reader and serves it. 200func (ui * UI )ReadAnalysis (input io.Reader )error { 201ui .mu .Lock () 202ui .scanning = true 203ui .mu .Unlock () 204 205dir ,err := report .ReadAnalysis (input ) 206if err != nil { 207ui .mu .Lock () 208ui .scanning = false 209ui .scanErr = err 210ui .mu .Unlock () 211return err 212 } 213dir .UpdateStats (ui .linkedItems ) 214 215ui .mu .Lock () 216ui .topDir = dir 217ui .topDirPath = dir .GetPath () 218ui .scanning = false 219ui .mu .Unlock () 220return nil 221} 222 223// ReadFromStorage reads a previously stored analysis and serves it. 224func (ui * UI )ReadFromStorage (storagePath ,path string )error { 225storage := analyze .NewStorage (storagePath ,path ) 226closeFn := storage .Open () 227defer closeFn () 228 229dir ,err := storage .GetDirForPath (path ) 230if err != nil { 231return err 232 } 233dir .UpdateStats (ui .linkedItems ) 234 235ui .mu .Lock () 236ui .topDir = dir 237ui .topDirPath = dir .GetPath () 238ui .scanning = false 239ui .mu .Unlock () 240return nil 241} 242 243// pollProgress samples the analyzer progress and broadcasts it until the scan 244// goroutine signals completion by closing scanDone. 245func (ui * UI )pollProgress (scanDone <- chan struct {}) { 246ticker := time .NewTicker (progressPollInterval ) 247defer ticker .Stop () 248 249for { 250select { 251case <- scanDone : 252return 253case <- ticker .C : 254p := ui .Analyzer .GetProgress () 255ui .mu .Lock () 256ui .progress = p 257ui .mu .Unlock () 258ui .hub .publish (ui .statusJSON ()) 259 } 260 } 261} 262 263// statusJSON renders the current scan status as a JSON string for SSE. 264func (ui * UI )statusJSON ()string { 265data ,err := json .Marshal (ui .buildStatus ()) 266if err != nil { 267log .Printf ("webui: marshaling status: %s" ,err ) 268return `{"state":"error"}` 269 } 270return string (data ) 271}