Chat API update. Breaks everything.
[brdnet.git] / dhtPersist.pas
blobff990c1b148ec3a1a2d41519cdf0c3b5f000eee5
1 unit dhtPersist;
3 Initialize DHT local node ID from file.
4 Restore DHT routing table from file.
5 Save DHT routing table on exit and periodically.
8 INTERFACE
10 IMPLEMENTATION
11 uses NetAddr,ServerLoop,DHT,SysUtils,Store1;
13 const ndfn='nodes.dat';
14 const idfn='idhash.txt';
16 procedure Save;
17 var nd: FILE of tPeerPub;
18 var node:tPeerPub;
19 var nnp:pointer=nil;
20 var nni:byte=0;
21 begin
22 assign(nd,'_'+ndfn);
23 ReWrite(nd);
24 try
25 repeat
26 dht.GetNextNode(nnp,nni,node);
27 if node.addr.isNil then break;
28 //writeln('dhtPersist: save ',string(node.addr));
29 write(nd,node);
30 until false;
31 finally
32 close(nd);
33 end;
34 rename(nd,ndfn);
35 end;
37 procedure Load;
38 var nd: FILE of tPeerPub;
39 var node:tPeerPub;
40 var pos:Word;
41 begin
42 assign(nd,ndfn);
43 try
44 ReSet(nd);
45 except
46 writeln('dhtPersist: can not open state file ',ndfn);
47 exit end;
48 {need to read the file backwards}
49 pos:=FileSize(nd);
50 if pos=0 then exit;
51 for pos:=pos-1 downto 0 do begin
52 Seek(nd,pos);
53 Read(nd,node);
54 //writeln('dhtPersist: load ',string(node.addr));
55 dht.InsertNode(node);
56 end;
57 close(nd);
58 end;
60 procedure LoadID;
61 var nd: TextFile;
62 var line:string;
63 begin
64 assign(nd,idfn);
65 try
66 ReSet(nd);
67 except
68 writeln('dhtPersist: can not open id file ',idfn);
69 exit end;
70 readln(nd,line);
71 writeln('dhtPersist: set ID to ',line);
72 dht.MyID:=line;
73 close(nd);
74 end;
76 procedure LoadIDFromArgs;
77 var oi:word;
78 const opt='-id';
79 begin
80 oi:=OptIndex(opt);
81 if oi>0 then begin
82 assert(OptParamCount(oi)=1,opt+'(pid:sha1)');
83 writeln('dhtPersist: set ID to '+paramstr(oi+1));
84 MyID:=tPID(paramstr(oi+1));
85 end;
86 end;
87 procedure LoadIDRandom;
88 var oi:word;
89 const opt='-id-rnd';
90 var b:byte;
91 begin
92 oi:=OptIndex(opt);
93 if oi>0 then begin
94 assert(OptParamCount(oi)=0,opt+'()');
95 for b:=0 to 19 do MyID[b]:=Random(256);
96 writeln('dhtPersist: set ID to ',string(MyID));
97 end;
98 end;
100 type t=object
101 pot:procedure;
102 procedure Init;
103 procedure doPeriodic;
104 procedure doSoon;
105 end;
107 procedure doLast;
108 begin
109 Save;
110 end;
112 procedure t.doSoon;
113 begin
114 Load;
115 end;
117 procedure t.doPeriodic;
118 begin
119 Save;
120 Shedule(61273,@doPeriodic);
121 end;
123 procedure t.Init;
124 begin
125 LoadID;
126 LoadIDFromArgs;
127 LoadIDRandom;
128 Shedule(2000,@doSoon);
129 Shedule(25000,@doPeriodic);
131 pot:=ServerLoop.OnTerminate;
132 ServerLoop.OnTerminate:=@doLast;
134 end;
136 var o:t;
137 BEGIN
138 o.init;
139 END.