github.com/NebulousLabs/Sia@v1.3.7/modules/gateway/persist.go (about) 1 package gateway 2 3 import ( 4 "path/filepath" 5 "time" 6 7 "github.com/NebulousLabs/Sia/modules" 8 "github.com/NebulousLabs/Sia/persist" 9 ) 10 11 const ( 12 // logFile is the name of the log file. 13 logFile = modules.GatewayDir + ".log" 14 15 // nodesFile is the name of the file that contains all seen nodes. 16 nodesFile = "nodes.json" 17 ) 18 19 // persistMetadata contains the header and version strings that identify the 20 // gateway persist file. 21 var persistMetadata = persist.Metadata{ 22 Header: "Sia Node List", 23 Version: "1.3.0", 24 } 25 26 // persistData returns the data in the Gateway that will be saved to disk. 27 func (g *Gateway) persistData() (nodes []*node) { 28 for _, node := range g.nodes { 29 nodes = append(nodes, node) 30 } 31 return 32 } 33 34 // load loads the Gateway's persistent data from disk. 35 func (g *Gateway) load() error { 36 var nodes []*node 37 err := persist.LoadJSON(persistMetadata, &nodes, filepath.Join(g.persistDir, nodesFile)) 38 if err != nil { 39 // COMPATv1.3.0 40 return g.loadv033persist() 41 } 42 for i := range nodes { 43 g.nodes[nodes[i].NetAddress] = nodes[i] 44 } 45 return nil 46 } 47 48 // saveSync stores the Gateway's persistent data on disk, and then syncs to 49 // disk to minimize the possibility of data loss. 50 func (g *Gateway) saveSync() error { 51 return persist.SaveJSON(persistMetadata, g.persistData(), filepath.Join(g.persistDir, nodesFile)) 52 } 53 54 // threadedSaveLoop periodically saves the gateway. 55 func (g *Gateway) threadedSaveLoop() { 56 for { 57 select { 58 case <-g.threads.StopChan(): 59 return 60 case <-time.After(saveFrequency): 61 } 62 63 func() { 64 err := g.threads.Add() 65 if err != nil { 66 return 67 } 68 defer g.threads.Done() 69 70 g.mu.Lock() 71 err = g.saveSync() 72 g.mu.Unlock() 73 if err != nil { 74 g.log.Println("ERROR: Unable to save gateway persist:", err) 75 } 76 }() 77 } 78 } 79 80 // loadv033persist loads the v0.3.3 Gateway's persistent data from disk. 81 func (g *Gateway) loadv033persist() error { 82 var nodes []modules.NetAddress 83 err := persist.LoadJSON(persist.Metadata{ 84 Header: "Sia Node List", 85 Version: "0.3.3", 86 }, &nodes, filepath.Join(g.persistDir, nodesFile)) 87 if err != nil { 88 return err 89 } 90 for _, addr := range nodes { 91 err := g.addNode(addr) 92 if err != nil { 93 g.log.Printf("WARN: error loading node '%v' from persist: %v", addr, err) 94 } 95 } 96 return nil 97 }