File: PDB.pmod

package info (click to toggle)
roxen 1.2beta2-3
  • links: PTS
  • area: contrib
  • in suites: slink
  • size: 16,920 kB
  • ctags: 8,589
  • sloc: ansic: 89,632; asm: 8,431; sh: 2,915; makefile: 1,784; cpp: 377
file content (644 lines) | stat: -rw-r--r-- 12,879 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
/*
 * $Id: PDB.pmod,v 1.27 1998/03/28 19:10:14 noring Exp $
 */

#if constant(thread_create)
#define THREAD_SAFE
#define LOCK() do { object key; catch(key=lock())
#define UNLOCK() key=0; } while(0)
#else
#undef THREAD_SAFE
#define LOCK() do {
#define UNLOCK() } while(0)
#endif

#define PDB_ERR(msg) (exceptions?throw(({ "(PDB) "+msg+"\n",backtrace() })):0)
#define PDB_WARN(msg) werror("(PDB Warning) "+msg+"\n")

class FileIO {

#ifdef THREAD_SAFE
  static inherit Thread.Mutex;
#endif

  static int exceptions, sov;

  static private object open(string f, string m)
  {
    object o = Stdio.File();
    if(!o->open(f,m))
      return PDB_ERR("Failed to open file. "+f+": "+strerror(o->errno()));
    return o;
  }
  
  static int safe_write(object o, string d, string ctx)
  {
    int warned_already=0;
    int n;
    for(;;) {
      n = o->write(d);
      if(!sov || n == sizeof(d) || (n<0 && !(<11,12,16,24,28,49>)[o->errno()]))
	break;
      d = d[n..];
      if(!warned_already) {
	if(n<0)
	  PDB_WARN(ctx+": "+strerror(o->errno())+" (sleeping)");
	else
	  PDB_WARN(ctx+": Disk seems to be full. (sleeping)");
	warned_already=1;
      }
      sleep(1);
    }
    if(warned_already)
      PDB_WARN(ctx+": I'm OK now.");
    return (n<0? n : (n==strlen(d)? 1 : 0));
  }

  static int write_file(string f, mixed d)
  {
    d = encode_value(d);
    catch {
      string q;
      object g;
      if (sizeof(indices(g=Gz))) {
	if(strlen(q=g->deflate()->deflate(d)) < strlen(d))
	  d=q;
      }
    };
    object o = open(f+".tmp","wct");
    int n = safe_write(o, d, "write_file("+f+")");
    o->close();
    if(n == 1)
      return mv(f+".tmp", f)?1:PDB_ERR("Cannot move file.");
    rm(f+".tmp");
    return PDB_ERR("Failed to write file. Disk full?");
  }
  
  static mixed read_file(string f)
  {
    object o = open(f,"r");
    string d = o->read();
    catch {
      object g;
      if (sizeof(indices(g=Gz))) {
	d=g->inflate()->inflate(d);
      }
    };
    return decode_value(d);
  }
}


class Bucket
{
  inherit FileIO;
  static object file=Stdio.File();
  static array free_blocks = ({});
  static string rf;
  static int last_block, dirty;
  static function db_log;
  int size;

  static int log(int subtype, mixed arg)
  {
    return db_log('B', subtype, size, arg);
  }

  static int write_at(int offset, string to)
  {
    if(file->seek(offset*size) < 0)
      return PDB_ERR("write_at: seek failed");

    if(safe_write(file, to, "write_at") == 1)
      return 1;

    return PDB_ERR("Failed to write file. Disk full?");
  }
  
  static string read_at(int offset)
  {
    if(file->seek(offset*size) == -1)
      return PDB_ERR("Failed to seek.");
    return file->read(size);
  }
  
  mixed get_entry(int offset)
  {
    LOCK();
    return read_at(offset);
    UNLOCK();
  }
  
  static void save_free_blocks()
  {
    if(write_file(rf+".free", ({last_block, free_blocks})))
      dirty = 0;
  }
  
  void free_entry(int offset)
  {
    LOCK();
    free_blocks += ({ offset });
    dirty = 1;
    log('F', offset);
    if(size<4)   write_at(offset,"F");
    else         write_at(offset,"FREE");
    UNLOCK();
  }

  int allocate_entry()
  {
    int b;
    LOCK();
    if(sizeof(free_blocks)) {
      b = free_blocks[0];
      free_blocks -= ({ b });
    } else
      b = last_block++;
    dirty = 1;
    if(!log('A', b))
      return -1;
    UNLOCK();
    return b;
  }

  int sync()
  {
    LOCK();
    if(dirty)
      save_free_blocks();
    return !dirty;
    UNLOCK();
  }

  int set_entry(int offset, string to)
  {
    if(strlen(to) > size) return 0;
    LOCK();
    return write_at(offset, to);
    UNLOCK();
  }

  void restore_from_log(array log)
  {
    multiset alloced = (< >);
    multiset freed = (< >);
    foreach(log, array entry)
      switch(entry[0]) {
      case 'A':
	alloced[entry[1]] = 1;
	freed[entry[1]] = 0;
	break;
      case 'F':
	freed[entry[1]] = 1;
	alloced[entry[1]] = 0;
	break;
      }
    foreach(sort(indices(alloced)), int a)
      if(a>=last_block) {
	int i;
	for(i=last_block; i<a; i++)
	  free_blocks += ({ i });
	last_block = a+1;
	dirty = 1;
      } else if(search(free_blocks, a)>=0) {
	free_blocks -= ({ a });
	dirty = 1;
      }
    array(int) fr = indices(freed) - free_blocks;
    if(sizeof(fr)) {
      free_blocks += fr;
      foreach(fr, int f)
	if(size<4)   write_at(f,"F");
	else         write_at(f,"FREE");
      dirty = 1;
    }
  }
  
  void create(string d, int ms, int write, function logfun, int exceptions_in,
	      int sov_in)
  {
    string mode="r";
    size=ms;
    rf = d+ms;
    db_log = logfun;
    exceptions = exceptions_in;
    sov = sov_in;
    if(write) { mode="rwc"; }
    catch {
      array t = read_file(rf+".free");
      last_block = t[0];
      free_blocks = t[1];
    };
    if(!file->open(rf,mode)) destruct();
  }

  void destroy()
  {
    sync();
    if(file)
      destruct(file);
  }
};


class Table
{
  inherit FileIO;
  static mapping index = ([ ]);
  static int compress, write;
  static string dir, name;
  static function get_bucket;
  static int dirty;
  static function db_log;

  static int log(int subtype, mixed ... arg)
  {
    return db_log('T', subtype, name, @arg);
  }

  int sync()
  {
    LOCK();
    if(dirty) {
      if(write_file(dir+".INDEX", index))
	dirty = 0;
    }
    return !dirty;
    UNLOCK();
  }

  int find_nearest_2x(int num)
  {
    for(int b=4;b<32;b++) if((1<<b) >= num) return (1<<b);
  }

  function scheme = find_nearest_2x;


  void delete(string in)
  {
    if(!write) return;
    LOCK();
    array i;
    if(i=index[in]) {
      m_delete(index,in);
      dirty = 1;
      log('D', in);
      object bucket = get_bucket(i[0]);
      bucket->free_entry(i[1]);
    }
    UNLOCK();
  }

  mixed set(string in, mixed to)
  {
    if(!write) return 0;
    string ts = encode_value(to);
    if(compress)
      catch {
	string q;
	object g;
	if (sizeof(indices(g=Gz))) {
	  if(strlen(q=g->deflate()->deflate(ts)) < strlen(ts))
	    ts=q;
	}
      };
    LOCK();
    object bucket = get_bucket(scheme(strlen(ts)));
    int of = bucket->allocate_entry();
    if(of>=0 && bucket->set_entry(of, ts)) {
      array new_entry = ({ bucket->size, of });
      if(log('C', in, new_entry)) {
	delete(in);
	index[in]=new_entry;
	dirty = 1;
      } else
	to = 0;
    } else
      to = 0;
    UNLOCK();
    return to;
  }

  mixed `[]=(string in,mixed to) {
    return set(in,to);
  }
  
  mixed get(string in)
  {
    array i;
    mixed d;
    LOCK();
    if(!(i=index[in])) return 0;
    object bucket = get_bucket(i[0]);
    d = bucket->get_entry(i[1]);
    UNLOCK();
    catch {
      object g;
      if (sizeof(indices(g=Gz))) {
	d=g->inflate()->inflate(d);
      }
    };
    return decode_value( d );
  }

  mixed `[](string in) {
    return get(in);
  }

  array list_keys() {
//  LOCK();
    return indices(index);
//  UNLOCK();
  }
  
  array _indices() {
    return list_keys();
  }

  array match(string match)
  {
    return glob(match, _indices());
  }

  void purge()
  {
    // remove table...
    if(!write) return;
    LOCK();
    foreach(_indices(), string d)
      delete(d);
    rm(dir+".INDEX");
    index=([]);
    dirty = 0;
    log('P');
    UNLOCK();
  }

  void rehash()
  {
    // TBD ...
  }
  
  void restore_from_log(array log)
  {
    int purge = 0;
    foreach(log, array entry)
      switch(entry[0]) {
      case 'D':
	m_delete(index, entry[1]);
	break;
      case 'C':
	index[entry[1]] = entry[2];
	break;
      case 'P':
	index = ([]);
	purge = 1;
	break;
      }
    if(!write) return;
    if(purge) {
      rm(dir+".INDEX");
      dirty = sizeof(index)>0;
    } else
      dirty = sizeof(log)>0;
  }

  void create(string n, string d, int wp, int cp, function fn, function logfun, int exceptions_in, int sov_in)
  {
    name = n;
    get_bucket = fn;
    db_log = logfun;
    dir = d;
    exceptions = exceptions_in;
    sov = sov_in;
    if(sizeof(predef::indices(Gz)) && cp) compress=1;
    if(wp) write=1;
    catch { index = read_file(dir+".INDEX"); };
  }

  void destroy()
  {
    sync();
  }
};


class db
{
  inherit FileIO;
#ifdef THREAD_SAFE
  static inherit Thread.Mutex;
#endif

  static int write, compress;
  static string dir;
  static mapping (int:object(Bucket)) buckets = ([]);
  static mapping (string:object(Table)) tables = ([]);
  static object(Stdio.File) logfile;

  static int log(int major, int minor, mixed ... args)
  {
    LOCK();
    if(logfile) {
      int rc;
      string entry = sprintf("%c%c%s\n", major, minor,
			     replace(encode_value(args),
				     ({ "\203", "\n" }),
				     ({ "\203\203", "\203n" })));

      if((rc = safe_write(logfile, entry, "log"))!=1)
	return PDB_ERR("Failed to write log: "+(rc<0? strerror(logfile->errno()):
						"Disk full (probably)"));
    }
    UNLOCK();
    return 1;
  }

  static object(Bucket) get_bucket(int s)
  {
    object bucket;
    LOCK();
    if(!(bucket = buckets[s]))
      buckets[s] = bucket = Bucket( dir+"Buckets/", s, write, log, exceptions, sov );
    UNLOCK();
    return bucket;
  }
  
  static void mkdirhier(string from)
  {
    string a, b;
    array f;

    f=(from/"/");
    b="";

    foreach(f[0..sizeof(f)-2], a)
    {
      mkdir(b+a);
      b+=a+"/";
    }
  }

  object(Table) table(string tname)
  {
    tname -= "/";
    LOCK();
    if(tables[tname])
      return tables[tname];
    return tables[tname] =
      Table(tname, combine_path(dir, tname), write, compress, get_bucket, log, exceptions, sov );
    UNLOCK();
  }

  object(Table) `[](string t)
  {
    return table(t);
  }
  
  array(string) list_tables()
  {
    LOCK();
    return Array.map(glob("*.INDEX", get_dir(dir) || ({})),
		     lambda(string s) {
		       return s[..(sizeof(s)-1-sizeof(".INDEX"))];
		     })|indices(tables);
    UNLOCK();
  }

  array(string) _indices()
  {
    return list_tables();
  }

  static void rotate_logs()
  {
    mv(dir+"log.1", dir+"log.2");
    logfile->open(dir+"log.1", "cwta");
  }

  int sync()
  {
    array b, t;
    int rc, ok=1;
    LOCK();
    rc = log('D', '1');
    b = values(buckets);
    t = values(tables);
    UNLOCK();
    if(rc) {
      foreach(b+t, object o)
	if(catch{if(!o->sync()) ok=0;}) ok=0;
      if(ok) {
	LOCK();
	if(log('D', '2'))
	  rotate_logs();
	else ok=0;
	UNLOCK();
      }
    } else ok=0;
    remove_call_out(sync);
    call_out(sync, 200);
    return ok;
  }

  // Remove maximum one level of directories and files
  static void level2_rm(string f)
  {
    if(sizeof(f) > 1 && f[-1] == '/')
      f = f[0..sizeof(f)-2];  // remove /'s
    if((file_stat(f)||({0,0}))[1] == -2)  // directory
      foreach(get_dir(f)||({}), string file)
	rm(f+"/"+file);  // delete file
    rm(f);  // delete file/directory
  }

  void purge()
  {
    // remove whole db...
    LOCK();
    foreach(values(buckets)+values(tables)+({ logfile }), object o)
      destruct(o);
    buckets = 0;
    tables = 0;
    level2_rm(dir+"Buckets");
    level2_rm(dir);
    dir = 0;
    destruct();
    UNLOCK();
  }

  static void restore_logs()
  {
    string log = "\n"+(Stdio.read_file(dir+"log.2")||"")+
      (Stdio.read_file(dir+"log.1")||"")+"\n";
    int p=-1, d1_pos=-1, d2_pos=-1;
    while((p=search(log, "\nD", p+1))>=0)
      if(log[p+2]=='1')
	d1_pos = p;
      else if(log[p+2]=='2')
	d2_pos = d1_pos;
    if(d2_pos >= 0)
      log = log[d2_pos..];

    mapping(int:array(array)) bucket_log = ([]);
    mapping(string:array(array)) table_log = ([]);

    foreach(log/"\n", string entry) {
      int main, sub;
      array a;
      if(sscanf(entry, "%c%c%s", main, sub, entry)==3 &&
	 !catch(a = decode_value(replace(entry, ({ "\203\203", "\203n" }),
					 ({ "\203", "\n" })))))
	switch(main) {
	case 'D':
	  break;
	case 'T':
	  if(table_log[a[0]])
	    table_log[a[0]] += ({ ({ sub }) + a[1..] });
	  else
	    table_log[a[0]] = ({ ({ sub }) + a[1..] });
	  break;
	case 'B':
	  if(bucket_log[a[0]])
	    bucket_log[a[0]] += ({ ({ sub }) + a[1..] });
	  else
	    bucket_log[a[0]] = ({ ({ sub }) + a[1..] });
	  break;
	  break;
	}
    }
    log = 0;

    foreach(indices(bucket_log), int bucket)
      get_bucket(bucket)->restore_from_log(bucket_log[bucket]);
    foreach(indices(table_log), string t)
      table(t)->restore_from_log(table_log[t]);
  }
  
  void create(string d, string mode)
  {
    if(search(mode,"e")+1) exceptions=1;
    if(search(mode,"w")+1) write=1;
    if(search(mode,"C")+1) compress=1;
    if(search(mode,"s")+1) sov=1;
    if(search(mode,"c")+1) if(!file_stat(d))
    {
      mkdirhier(d+"/foo");
      mkdirhier(d+"/Buckets/foo");
    }
    dir = replace(d+"/","//","/");
    logfile = 0;
    restore_logs();
    if (write) {
      logfile = Stdio.File();
      logfile->open(dir+"log.1", "cwa");
      if(logfile->write("\n")!=1) {
	destruct(this_object());
	PDB_ERR("Failed to write a single byte to log.");
      }
      sync();
    }
  }
};