]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/registry/bdb.rb
* wrap BDB::Fatal classes for abstract trapping
[user/henk/code/ruby/rbot.git] / lib / rbot / registry / bdb.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Berkeley DB interface
5
6 begin
7   require 'bdb'
8 rescue LoadError
9   fatal "rbot couldn't load the bdb module, perhaps you need to install it? try: http://www.ruby-lang.org/en/raa-list.rhtml?name=bdb"
10 rescue Exception => e
11   fatal "rbot couldn't load the bdb module: #{e.pretty_inspect}"
12 end
13
14 if not defined? BDB
15   exit 2
16 end
17
18 module Irc
19   DBFatal = BDB::Fatal
20 end
21
22 if BDB::VERSION_MAJOR < 4
23   fatal "Your bdb (Berkeley DB) version #{BDB::VERSION} is too old!"
24   fatal "rbot will only run with bdb version 4 or higher, please upgrade."
25   fatal "For maximum reliability, upgrade to version 4.2 or higher."
26   raise BDB::Fatal, BDB::VERSION + " is too old"
27 end
28
29 if BDB::VERSION_MAJOR == 4 and BDB::VERSION_MINOR < 2
30   warning "Your bdb (Berkeley DB) version #{BDB::VERSION} may not be reliable."
31   warning "If possible, try upgrade version 4.2 or later."
32 end
33
34 # make BTree lookups case insensitive
35 module BDB
36   class CIBtree < Btree
37     def bdb_bt_compare(a, b)
38       if a == nil || b == nil
39         warning "CIBTree: comparing #{a.inspect} (#{self[a].inspect}) with #{b.inspect} (#{self[b].inspect})"
40       end
41       (a||'').downcase <=> (b||'').downcase
42     end
43   end
44 end
45
46 module Irc
47
48   # DBHash is for tying a hash to disk (using bdb).
49   # Call it with an identifier, for example "mydata". It'll look for
50   # mydata.db, if it exists, it will load and reference that db.
51   # Otherwise it'll create and empty db called mydata.db
52   class DBHash
53
54     # absfilename:: use +key+ as an actual filename, don't prepend the bot's
55     #               config path and don't append ".db"
56     def initialize(bot, key, absfilename=false)
57       @bot = bot
58       @key = key
59       relfilename = @bot.path key
60       relfilename << '.db'
61       if absfilename && File.exist?(key)
62         # db already exists, use it
63         @db = DBHash.open_db(key)
64       elsif absfilename
65         # create empty db
66         @db = DBHash.create_db(key)
67       elsif File.exist? relfilename
68         # db already exists, use it
69         @db = DBHash.open_db relfilename
70       else
71         # create empty db
72         @db = DBHash.create_db relfilename
73       end
74     end
75
76     def method_missing(method, *args, &block)
77       return @db.send(method, *args, &block)
78     end
79
80     def DBHash.create_db(name)
81       debug "DBHash: creating empty db #{name}"
82       return BDB::Hash.open(name, nil,
83       BDB::CREATE | BDB::EXCL, 0600)
84     end
85
86     def DBHash.open_db(name)
87       debug "DBHash: opening existing db #{name}"
88       return BDB::Hash.open(name, nil, "r+", 0600)
89     end
90
91   end
92
93
94   # DBTree is a BTree equivalent of DBHash, with case insensitive lookups.
95   class DBTree
96     @@env=nil
97     # TODO: make this customizable
98     # Note that it must be at least four times lg_bsize
99     @@lg_max = 8*1024*1024
100     # absfilename:: use +key+ as an actual filename, don't prepend the bot's
101     #               config path and don't append ".db"
102     def initialize(bot, key, absfilename=false)
103       @bot = bot
104       @key = key
105       if @@env.nil?
106         begin
107           @@env = BDB::Env.open(@bot.botclass, BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER, "set_lg_max" => @@lg_max)
108           debug "DBTree: environment opened with max log size #{@@env.conf['lg_max']}"
109         rescue => e
110           debug "DBTree: failed to open environment: #{e.pretty_inspect}. Retrying ..."
111           @@env = BDB::Env.open(@bot.botclass, BDB::INIT_TRANSACTION | BDB::CREATE |  BDB::RECOVER)
112         end
113         #@@env = BDB::Env.open(@bot.botclass, BDB::CREATE | BDB::INIT_MPOOL | BDB::RECOVER)
114       end
115
116       relfilename = @bot.path key
117       relfilename << '.db'
118
119       if absfilename && File.exist?(key)
120         # db already exists, use it
121         @db = DBTree.open_db(key)
122       elsif absfilename
123         # create empty db
124         @db = DBTree.create_db(key)
125       elsif File.exist? relfilename
126         # db already exists, use it
127         @db = DBTree.open_db relfilename
128       else
129         # create empty db
130         @db = DBTree.create_db relfilename
131       end
132     end
133
134     def method_missing(method, *args, &block)
135       return @db.send(method, *args, &block)
136     end
137
138     def DBTree.create_db(name)
139       debug "DBTree: creating empty db #{name}"
140       return @@env.open_db(BDB::CIBtree, name, nil, BDB::CREATE | BDB::EXCL, 0600)
141     end
142
143     def DBTree.open_db(name)
144       debug "DBTree: opening existing db #{name}"
145       return @@env.open_db(BDB::CIBtree, name, nil, "r+", 0600)
146     end
147
148     def DBTree.cleanup_logs()
149       begin
150         debug "DBTree: checkpointing ..."
151         @@env.checkpoint
152       rescue Exception => e
153         debug "Failed: #{e.pretty_inspect}"
154       end
155       begin
156         debug "DBTree: flushing log ..."
157         @@env.log_flush
158         logs = @@env.log_archive(BDB::ARCH_ABS)
159         debug "DBTree: deleting archivable logs: #{logs.join(', ')}."
160         logs.each { |log|
161           File.delete(log)
162         }
163       rescue Exception => e
164         debug "Failed: #{e.pretty_inspect}"
165       end
166     end
167
168     def DBTree.stats()
169       begin
170         debug "General stats:"
171         debug @@env.stat
172         debug "Lock stats:"
173         debug @@env.lock_stat
174         debug "Log stats:"
175         debug @@env.log_stat
176         debug "Txn stats:"
177         debug @@env.txn_stat
178       rescue
179         debug "Couldn't dump stats"
180       end
181     end
182
183     def DBTree.cleanup_env()
184       begin
185         debug "DBTree: checking transactions ..."
186         has_active_txn = @@env.txn_stat["st_nactive"] > 0
187         if has_active_txn
188           warning "DBTree: not all transactions completed!"
189         end
190         DBTree.cleanup_logs
191         debug "DBTree: closing environment #{@@env}"
192         path = @@env.home
193         @@env.close
194         @@env = nil
195         if has_active_txn
196           debug "DBTree: keeping file because of incomplete transactions"
197         else
198           debug "DBTree: cleaning up environment in #{path}"
199           BDB::Env.remove("#{path}")
200         end
201       rescue Exception => e
202         error "failed to clean up environment: #{e.pretty_inspect}"
203       end
204     end
205
206   end
207
208 end
209
210
211 module Irc
212 class Bot
213
214   # This class is now used purely for upgrading from prior versions of rbot
215   # the new registry is split into multiple DBHash objects, one per plugin
216   class Registry
217     def initialize(bot)
218       @bot = bot
219       upgrade_data
220       upgrade_data2
221     end
222
223     # check for older versions of rbot with data formats that require updating
224     # NB this function is called _early_ in init(), pretty much all you have to
225     # work with is @bot.botclass.
226     def upgrade_data
227       oldreg = @bot.path 'registry.db'
228       newreg = @bot.path 'plugin_registry.db'
229       if File.exist?(oldreg)
230         log _("upgrading old-style (rbot 0.9.5 or earlier) plugin registry to new format")
231         old = BDB::Hash.open(oldreg, nil, "r+", 0600)
232         new = BDB::CIBtree.open(newreg, nil, BDB::CREATE | BDB::EXCL, 0600)
233         old.each {|k,v|
234           new[k] = v
235         }
236         old.close
237         new.close
238         File.rename(oldreg, oldreg + ".old")
239       end
240     end
241
242     def upgrade_data2
243       oldreg = @bot.path 'plugin_registry.db'
244       newdir = @bot.path 'registry'
245       if File.exist?(oldreg)
246         Dir.mkdir(newdir) unless File.exist?(newdir)
247         env = BDB::Env.open(@bot.botclass, BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER)# | BDB::TXN_NOSYNC)
248         dbs = Hash.new
249         log _("upgrading previous (rbot 0.9.9 or earlier) plugin registry to new split format")
250         old = BDB::CIBtree.open(oldreg, nil, "r+", 0600, "env" => env)
251         old.each {|k,v|
252           prefix,key = k.split("/", 2)
253           prefix.downcase!
254           # subregistries were split with a +, now they are in separate folders
255           if prefix.gsub!(/\+/, "/")
256             # Ok, this code needs to be put in the db opening routines
257             dirs = File.dirname("#{@bot.botclass}/registry/#{prefix}.db").split("/")
258             dirs.length.times { |i|
259               dir = dirs[0,i+1].join("/")+"/"
260               unless File.exist?(dir)
261                 log _("creating subregistry directory #{dir}")
262                 Dir.mkdir(dir)
263               end
264             }
265           end
266           unless dbs.has_key?(prefix)
267             log _("creating db #{@bot.botclass}/registry/#{prefix}.db")
268             dbs[prefix] = BDB::CIBtree.open("#{@bot.botclass}/registry/#{prefix}.db",
269               nil, BDB::CREATE | BDB::EXCL,
270               0600, "env" => env)
271           end
272           dbs[prefix][key] = v
273         }
274         old.close
275         File.rename(oldreg, oldreg + ".old")
276         dbs.each {|k,v|
277           log _("closing db #{k}")
278           v.close
279         }
280         env.close
281       end
282     end
283
284
285   # This class provides persistent storage for plugins via a hash interface.
286   # The default mode is an object store, so you can store ruby objects and
287   # reference them with hash keys. This is because the default store/restore
288   # methods of the plugins' RegistryAccessor are calls to Marshal.dump and
289   # Marshal.restore,
290   # for example:
291   #   blah = Hash.new
292   #   blah[:foo] = "fum"
293   #   @registry[:blah] = blah
294   # then, even after the bot is shut down and disconnected, on the next run you
295   # can access the blah object as it was, with:
296   #   blah = @registry[:blah]
297   # The registry can of course be used to store simple strings, fixnums, etc as
298   # well, and should be useful to store or cache plugin data or dynamic plugin
299   # configuration.
300   #
301   # WARNING:
302   # in object store mode, don't make the mistake of treating it like a live
303   # object, e.g. (using the example above)
304   #   @registry[:blah][:foo] = "flump"
305   # will NOT modify the object in the registry - remember that Registry#[]
306   # returns a Marshal.restore'd object, the object you just modified in place
307   # will disappear. You would need to:
308   #   blah = @registry[:blah]
309   #   blah[:foo] = "flump"
310   #   @registry[:blah] = blah
311   #
312   # If you don't need to store objects, and strictly want a persistant hash of
313   # strings, you can override the store/restore methods to suit your needs, for
314   # example (in your plugin):
315   #   def initialize
316   #     class << @registry
317   #       def store(val)
318   #         val
319   #       end
320   #       def restore(val)
321   #         val
322   #       end
323   #     end
324   #   end
325   # Your plugins section of the registry is private, it has its own namespace
326   # (derived from the plugin's class name, so change it and lose your data).
327   # Calls to registry.each etc, will only iterate over your namespace.
328   class Accessor
329
330     attr_accessor :recovery
331
332     # plugins don't call this - a Registry::Accessor is created for them and
333     # is accessible via @registry.
334     def initialize(bot, name)
335       @bot = bot
336       @name = name.downcase
337       @filename = @bot.path 'registry', @name
338       dirs = File.dirname(@filename).split("/")
339       dirs.length.times { |i|
340         dir = dirs[0,i+1].join("/")+"/"
341         unless File.exist?(dir)
342           debug "creating subregistry directory #{dir}"
343           Dir.mkdir(dir)
344         end
345       }
346       @filename << ".db"
347       @registry = nil
348       @default = nil
349       @recovery = nil
350       # debug "initializing registry accessor with name #{@name}"
351     end
352
353     def registry
354         @registry ||= DBTree.new @bot, "registry/#{@name}"
355     end
356
357     def flush
358       # debug "fushing registry #{registry}"
359       return if !@registry
360       registry.flush
361       registry.sync
362     end
363
364     def close
365       # debug "closing registry #{registry}"
366       return if !@registry
367       registry.close
368     end
369
370     # convert value to string form for storing in the registry
371     # defaults to Marshal.dump(val) but you can override this in your module's
372     # registry object to use any method you like.
373     # For example, if you always just handle strings use:
374     #   def store(val)
375     #     val
376     #   end
377     def store(val)
378       Marshal.dump(val)
379     end
380
381     # restores object from string form, restore(store(val)) must return val.
382     # If you override store, you should override restore to reverse the
383     # action.
384     # For example, if you always just handle strings use:
385     #   def restore(val)
386     #     val
387     #   end
388     def restore(val)
389       begin
390         Marshal.restore(val)
391       rescue Exception => e
392         error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
393         debug e
394         if defined? @recovery and @recovery
395           begin
396             return @recovery.call(val)
397           rescue Exception => ee
398             error _("marshal recovery failed, trying default")
399             debug ee
400           end
401         end
402         return default
403       end
404     end
405
406     # lookup a key in the registry
407     def [](key)
408       if File.exist?(@filename) && registry.has_key?(key)
409         return restore(registry[key])
410       else
411         return default
412       end
413     end
414
415     # set a key in the registry
416     def []=(key,value)
417       registry[key] = store(value)
418     end
419
420     # set the default value for registry lookups, if the key sought is not
421     # found, the default will be returned. The default default (har) is nil.
422     def set_default (default)
423       @default = default
424     end
425
426     def default
427       @default && (@default.dup rescue @default)
428     end
429
430     # just like Hash#each
431     def each(set=nil, bulk=0, &block)
432       return nil unless File.exist?(@filename)
433       registry.each(set, bulk) {|key,value|
434         block.call(key, restore(value))
435       }
436     end
437
438     # just like Hash#each_key
439     def each_key(set=nil, bulk=0, &block)
440       return nil unless File.exist?(@filename)
441       registry.each_key(set, bulk) {|key|
442         block.call(key)
443       }
444     end
445
446     # just like Hash#each_value
447     def each_value(set=nil, bulk=0, &block)
448       return nil unless File.exist?(@filename)
449       registry.each_value(set, bulk) { |value|
450         block.call(restore(value))
451       }
452     end
453
454     # just like Hash#has_key?
455     def has_key?(key)
456       return false unless File.exist?(@filename)
457       return registry.has_key?(key)
458     end
459     alias include? has_key?
460     alias member? has_key?
461     alias key? has_key?
462
463     # just like Hash#has_both?
464     def has_both?(key, value)
465       return false unless File.exist?(@filename)
466       return registry.has_both?(key, store(value))
467     end
468
469     # just like Hash#has_value?
470     def has_value?(value)
471       return false unless File.exist?(@filename)
472       return registry.has_value?(store(value))
473     end
474
475     # just like Hash#index?
476     def index(value)
477       return nil unless File.exist?(@filename)
478       ind = registry.index(store(value))
479       if ind
480         return ind
481       else
482         return nil
483       end
484     end
485
486     # delete a key from the registry
487     def delete(key)
488       return default unless File.exist?(@filename)
489       return registry.delete(key)
490     end
491
492     # returns a list of your keys
493     def keys
494       return [] unless File.exist?(@filename)
495       return registry.keys
496     end
497
498     # Return an array of all associations [key, value] in your namespace
499     def to_a
500       return [] unless File.exist?(@filename)
501       ret = Array.new
502       registry.each {|key, value|
503         ret << [key, restore(value)]
504       }
505       return ret
506     end
507
508     # Return an hash of all associations {key => value} in your namespace
509     def to_hash
510       return {} unless File.exist?(@filename)
511       ret = Hash.new
512       registry.each {|key, value|
513         ret[key] = restore(value)
514       }
515       return ret
516     end
517
518     # empties the registry (restricted to your namespace)
519     def clear
520       return true unless File.exist?(@filename)
521       registry.clear
522     end
523     alias truncate clear
524
525     # returns an array of the values in your namespace of the registry
526     def values
527       return [] unless File.exist?(@filename)
528       ret = Array.new
529       self.each {|k,v|
530         ret << restore(v)
531       }
532       return ret
533     end
534
535     def sub_registry(prefix)
536       return Accessor.new(@bot, @name + "/" + prefix.to_s)
537     end
538
539     # returns the number of keys in your registry namespace
540     def length
541       self.keys.length
542     end
543     alias size length
544
545   end
546
547   end
548 end
549 end