@@ -5,30 +5,55 @@ import (
55 "errors"
66 "flag"
77 "fmt"
8+ "log"
89 "math"
910 "os"
1011 "sort"
1112 "time"
1213
14+ "go.uber.org/zap"
15+
1316 "github.com/e2b-dev/infra/packages/orchestrator/cmd/clean-nfs-cache/pkg"
17+ "github.com/e2b-dev/infra/packages/shared/pkg/env"
18+ "github.com/e2b-dev/infra/packages/shared/pkg/logger"
1419)
1520
21+ const serviceName = "clean-nfs-cache"
22+
1623func main () {
17- if err := cleanNFSCache (context .Background ()); err != nil {
18- fmt .Println (err )
24+ ctx := context .Background ()
25+ if err := cleanNFSCache (ctx ); err != nil {
26+ zap .L ().Error ("clean NFS cache failed" , zap .Error (err ))
1927 os .Exit (1 )
2028 }
2129}
2230
2331func cleanNFSCache (ctx context.Context ) error {
32+ globalLogger := zap .Must (logger .NewLogger (ctx , logger.LoggerConfig {
33+ ServiceName : serviceName ,
34+ IsInternal : true ,
35+ IsDebug : env .IsDebug (),
36+ Cores : nil ,
37+ EnableConsole : true ,
38+ }))
39+ defer func (l * zap.Logger ) {
40+ err := l .Sync ()
41+ if err != nil {
42+ log .Printf ("error while shutting down logger: %v" , err )
43+ }
44+ }(globalLogger )
45+ zap .ReplaceGlobals (globalLogger )
46+
2447 path , opts , err := parseArgs ()
2548 if err != nil {
2649 return fmt .Errorf ("invalid arguments: %w" , err )
2750 }
2851
2952 // get free space information for path
30- fmt .Printf ("dry run: %t\n " , opts .dryRun )
31- fmt .Printf ("target disk usage percentage: %f%%\n " , opts .targetDiskUsagePercent )
53+ zap .L ().Info ("starting" ,
54+ zap .Bool ("dry_run" , opts .dryRun ),
55+ zap .Float64 ("target_percent" , opts .targetDiskUsagePercent ),
56+ zap .String ("path" , path ))
3257
3358 var diskInfo pkg.DiskInfo
3459 timeit (fmt .Sprintf ("getting disk info for %q" , path ), func () {
@@ -40,7 +65,9 @@ func cleanNFSCache(ctx context.Context) error {
4065 targetDiskUsage := int64 (float64 (opts .targetDiskUsagePercent ) / 100 * float64 (diskInfo .Total ))
4166 areWeDone := func () bool {
4267 currentUsedPercentage := (float64 (diskInfo .Used ) / float64 (diskInfo .Total )) * 100
43- fmt .Printf ("current usage: %d%% (%s)\n " , int (currentUsedPercentage ), formatBytes (diskInfo .Used ))
68+ zap .L ().Info ("current usage" ,
69+ zap .Float64 ("percent" , currentUsedPercentage ),
70+ zap .String ("size" , formatBytes (diskInfo .Used )))
4471 return diskInfo .Used < targetDiskUsage
4572 }
4673
@@ -55,7 +82,7 @@ func cleanNFSCache(ctx context.Context) error {
5582 var files []pkg.File
5683 timeit (fmt .Sprintf ("gathering metadata on %d files" , opts .filesPerLoop ), func () {
5784 files , err = getFiles (cache , opts .filesPerLoop )
58- fmt . Printf ( "got %d files" , len (files ))
85+ zap . L (). Info ( "got files" , zap . Int ( "count" , len (files ) ))
5986 })
6087 if err != nil {
6188 return fmt .Errorf ("could not get File metadata: %w" , err )
@@ -67,8 +94,11 @@ func cleanNFSCache(ctx context.Context) error {
6794 })
6895
6996 var results results
70- timeit (fmt .Sprintf ("deleting bottom %d%% files\n " , opts .filesToDeletePerLoop ), func () {
97+ timeit (fmt .Sprintf ("deleting bottom %d files" , opts .filesToDeletePerLoop ), func () {
7198 results , err = deleteOldestFiles (cache , files , opts , & diskInfo , areWeDone , opts .filesToDeletePerLoop )
99+ zap .L ().Info ("deleted files" ,
100+ zap .Int64 ("count" , results .deletedFiles ),
101+ zap .Int64 ("bytes" , results .deletedBytes ))
72102 })
73103 allResults = allResults .union (results )
74104 if err != nil {
@@ -81,26 +111,24 @@ func cleanNFSCache(ctx context.Context) error {
81111
82112func printSummary (r results , opts opts ) {
83113 if r .deletedFiles == 0 {
84- fmt . Fprintln ( os . Stderr , "no files deleted" )
114+ zap . L (). Info ( "no files deleted" )
85115 return
86116 }
87117
88- var notice string
89- if opts .dryRun {
90- notice = "would be "
91- }
92- fmt .Println ("======= summary =======" )
93- if opts .dryRun {
94- fmt .Println ("(note: dry-run mode enabled, no files were actually deleted)" )
95- }
96- fmt .Printf (" %d files (%d bytes) %sdeleted\n " , r .deletedFiles , r .deletedBytes , notice )
97- fmt .Println ("access time:" )
98- fmt .Printf ("- most recently used: %s\n " , minDuration (r .lastAccessed ).Round (time .Second ))
99- fmt .Printf ("- least recently used: %s\n " , maxDuration (r .lastAccessed ).Round (time .Second ))
100- fmt .Printf ("- standard deviation: %s\n " , standardDeviation (r .lastAccessed ).Round (time .Second ))
118+ zap .L ().Info ("summary" ,
119+ zap .Bool ("dry_run" , opts .dryRun ),
120+ zap .Int64 ("files" , r .deletedFiles ),
121+ zap .Int64 ("bytes" , r .deletedBytes ),
122+ zap .Duration ("most_recently_used" , minDuration (r .lastAccessed ).Round (time .Second )),
123+ zap .Duration ("least_recently_used" , maxDuration (r .lastAccessed ).Round (time .Second )),
124+ zap .Duration ("std_deviation" , standardDeviation (r .lastAccessed ).Round (time .Second )))
101125}
102126
103127func standardDeviation (accessed []time.Duration ) time.Duration {
128+ if len (accessed ) == 0 {
129+ return 0
130+ }
131+
104132 var sum time.Duration
105133 for i := range accessed {
106134 sum += accessed [i ]
@@ -169,18 +197,21 @@ func deleteOldestFiles(cache *pkg.ListingCache, files []pkg.File, opts opts, dis
169197 var results results
170198 for index , file := range files {
171199 if opts .dryRun {
172- fmt .Printf ("DRY RUN: would delete %q (%d bytes, last access: %s)\n " ,
173- file .Path , file .Size ,
174- time .Since (file .ATime ).Round (time .Minute ))
200+ zap .L ().Debug ("would delete" ,
201+ zap .String ("path" , file .Path ),
202+ zap .Int64 ("bytes" , file .Size ),
203+ zap .Duration ("last_access" , time .Since (file .ATime ).Round (time .Minute )))
175204 } else {
176- // remove File
177- fmt .Printf ("deleting #%d: %q (%d bytes) ... " , index + 1 , file .Path , file .Size )
205+ zap .L ().Debug ("deleting" ,
206+ zap .Int ("index" , index + 1 ),
207+ zap .String ("path" , file .Path ),
208+ zap .Int64 ("bytes" , file .Size ))
178209 if err := os .Remove (file .Path ); err != nil {
179- // if we fail to delete the File, try the next one
180- fmt .Printf ("failed to delete %q: %v\n " , file .Path , err )
210+ zap .L ().Error ("failed to delete" ,
211+ zap .String ("path" , file .Path ),
212+ zap .Error (err ))
181213 continue
182214 }
183- fmt .Print ("\n " )
184215 }
185216
186217 cache .Decache (file .Path )
@@ -211,11 +242,9 @@ func sortFilesByATime(files []pkg.File) {
211242func reportGetFilesProgress (usedFiles , dupeHits int ) {
212243 total := usedFiles + dupeHits
213244 if total > 0 && total % 100 == 0 {
214- msg := fmt .Sprintf ("%d files" , usedFiles )
215- if dupeHits > 0 {
216- msg += fmt .Sprintf (", %d dupe hits" , dupeHits )
217- }
218- fmt .Printf ("\r %s ... " , msg )
245+ zap .L ().Debug ("gathering files progress" ,
246+ zap .Int ("files" , usedFiles ),
247+ zap .Int ("dupe_hits" , dupeHits ))
219248 }
220249}
221250
@@ -230,7 +259,7 @@ func getFiles(cache *pkg.ListingCache, maxFiles int) ([]pkg.File, error) {
230259
231260 path , err := cache .GetRandomFile ()
232261 if err != nil {
233- return items , err
262+ return nil , err
234263 }
235264
236265 if _ , ok := usedFiles [path ]; ok {
@@ -251,6 +280,7 @@ func getFiles(cache *pkg.ListingCache, maxFiles int) ([]pkg.File, error) {
251280 usedFiles [path ] = struct {}{}
252281 }
253282
283+ reportGetFilesProgress (len (usedFiles ), dupeHits )
254284 return items , nil
255285}
256286
@@ -289,13 +319,11 @@ func parseArgs() (string, opts, error) {
289319}
290320
291321func timeit (message string , fn func ()) {
292- fmt .Print (message + " ... \n " )
293-
294322 start := time .Now ()
295323 fn ()
296324 done := time .Since (start ).Round (time .Millisecond )
297325
298- fmt . Print ( message + fmt . Sprintf ( ": done in [%s] \n " , done ))
326+ zap . L (). Debug ( message , zap . Duration ( "duration " , done ))
299327}
300328
301329func formatBytes (b int64 ) string {
0 commit comments