registry.rb: suppress warning when @recovery is not defined
[rbot] / lib / rbot / registry.rb
1 require 'rbot/dbhash'
2
3 module Irc
4
5   # this class is now used purely for upgrading from prior versions of rbot
6   # the new registry is split into multiple DBHash objects, one per plugin
7   class BotRegistry
8     def initialize(bot)
9       @bot = bot
10       upgrade_data
11       upgrade_data2
12     end
13
14     # check for older versions of rbot with data formats that require updating
15     # NB this function is called _early_ in init(), pretty much all you have to
16     # work with is @bot.botclass.
17     def upgrade_data
18       if File.exist?("#{@bot.botclass}/registry.db")
19         log _("upgrading old-style (rbot 0.9.5 or earlier) plugin registry to new format")
20         old = BDB::Hash.open("#{@bot.botclass}/registry.db", nil,
21                              "r+", 0600)
22         new = BDB::CIBtree.open("#{@bot.botclass}/plugin_registry.db", nil,
23                                 BDB::CREATE | BDB::EXCL,
24                                 0600)
25         old.each {|k,v|
26           new[k] = v
27         }
28         old.close
29         new.close
30         File.rename("#{@bot.botclass}/registry.db", "#{@bot.botclass}/registry.db.old")
31       end
32     end
33
34     def upgrade_data2
35       if File.exist?("#{@bot.botclass}/plugin_registry.db")
36         Dir.mkdir("#{@bot.botclass}/registry") unless File.exist?("#{@bot.botclass}/registry")
37         env = BDB::Env.open("#{@bot.botclass}", BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER)# | BDB::TXN_NOSYNC)
38         dbs = Hash.new
39         log _("upgrading previous (rbot 0.9.9 or earlier) plugin registry to new split format")
40         old = BDB::CIBtree.open("#{@bot.botclass}/plugin_registry.db", nil,
41           "r+", 0600, "env" => env)
42         old.each {|k,v|
43           prefix,key = k.split("/", 2)
44           prefix.downcase!
45           # subregistries were split with a +, now they are in separate folders
46           if prefix.gsub!(/\+/, "/")
47             # Ok, this code needs to be put in the db opening routines
48             dirs = File.dirname("#{@bot.botclass}/registry/#{prefix}.db").split("/")
49             dirs.length.times { |i|
50               dir = dirs[0,i+1].join("/")+"/"
51               unless File.exist?(dir)
52                 log _("creating subregistry directory #{dir}")
53                 Dir.mkdir(dir)
54               end
55             }
56           end
57           unless dbs.has_key?(prefix)
58             log _("creating db #{@bot.botclass}/registry/#{prefix}.db")
59             dbs[prefix] = BDB::CIBtree.open("#{@bot.botclass}/registry/#{prefix}.db",
60               nil, BDB::CREATE | BDB::EXCL,
61               0600, "env" => env)
62           end
63           dbs[prefix][key] = v
64         }
65         old.close
66         File.rename("#{@bot.botclass}/plugin_registry.db", "#{@bot.botclass}/plugin_registry.db.old")
67         dbs.each {|k,v|
68           log _("closing db #{k}")
69           v.close
70         }
71         env.close
72       end
73     end
74   end
75
76
77   # This class provides persistent storage for plugins via a hash interface.
78   # The default mode is an object store, so you can store ruby objects and
79   # reference them with hash keys. This is because the default store/restore
80   # methods of the plugins' RegistryAccessor are calls to Marshal.dump and
81   # Marshal.restore,
82   # for example:
83   #   blah = Hash.new
84   #   blah[:foo] = "fum"
85   #   @registry[:blah] = blah
86   # then, even after the bot is shut down and disconnected, on the next run you
87   # can access the blah object as it was, with:
88   #   blah = @registry[:blah]
89   # The registry can of course be used to store simple strings, fixnums, etc as
90   # well, and should be useful to store or cache plugin data or dynamic plugin
91   # configuration.
92   #
93   # WARNING:
94   # in object store mode, don't make the mistake of treating it like a live
95   # object, e.g. (using the example above)
96   #   @registry[:blah][:foo] = "flump"
97   # will NOT modify the object in the registry - remember that BotRegistry#[]
98   # returns a Marshal.restore'd object, the object you just modified in place
99   # will disappear. You would need to:
100   #   blah = @registry[:blah]
101   #   blah[:foo] = "flump"
102   #   @registry[:blah] = blah
103
104   # If you don't need to store objects, and strictly want a persistant hash of
105   # strings, you can override the store/restore methods to suit your needs, for
106   # example (in your plugin):
107   #   def initialize
108   #     class << @registry
109   #       def store(val)
110   #         val
111   #       end
112   #       def restore(val)
113   #         val
114   #       end
115   #     end
116   #   end
117   # Your plugins section of the registry is private, it has its own namespace
118   # (derived from the plugin's class name, so change it and lose your data).
119   # Calls to registry.each etc, will only iterate over your namespace.
120   class BotRegistryAccessor
121
122     attr_accessor :recovery
123
124     # plugins don't call this - a BotRegistryAccessor is created for them and
125     # is accessible via @registry.
126     def initialize(bot, name)
127       @bot = bot
128       @name = name.downcase
129       dirs = File.dirname("#{@bot.botclass}/registry/#{@name}").split("/")
130       dirs.length.times { |i|
131         dir = dirs[0,i+1].join("/")+"/"
132         unless File.exist?(dir)
133           debug "creating subregistry directory #{dir}"
134           Dir.mkdir(dir)
135         end
136       }
137       @registry = nil
138       @default = nil
139       @recover = nil
140       # debug "initializing registry accessor with name #{@name}"
141     end
142
143     def registry
144         @registry ||= DBTree.new @bot, "registry/#{@name}"
145     end
146
147     def flush
148       # debug "fushing registry #{registry}"
149       return if !@registry
150       registry.flush
151       registry.sync
152     end
153
154     def close
155       # debug "closing registry #{registry}"
156       return if !@registry
157       registry.close
158     end
159
160     # convert value to string form for storing in the registry
161     # defaults to Marshal.dump(val) but you can override this in your module's
162     # registry object to use any method you like.
163     # For example, if you always just handle strings use:
164     #   def store(val)
165     #     val
166     #   end
167     def store(val)
168       Marshal.dump(val)
169     end
170
171     # restores object from string form, restore(store(val)) must return val.
172     # If you override store, you should override restore to reverse the
173     # action.
174     # For example, if you always just handle strings use:
175     #   def restore(val)
176     #     val
177     #   end
178     def restore(val)
179       begin
180         Marshal.restore(val)
181       rescue Exception => e
182         error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
183         debug e
184         if defined? @recovery and @recovery
185           begin
186             return @recovery.call(val)
187           rescue Exception => ee
188             error _("marshal recovery failed, trying default")
189             debug ee
190           end
191         end
192         unless @default.nil?
193           begin
194             return Marshal.restore(@default)
195           rescue
196             return nil
197           end
198         else
199           return nil
200         end
201       end
202     end
203
204     # lookup a key in the registry
205     def [](key)
206       if registry.has_key?(key)
207         return restore(registry[key])
208       elsif @default != nil
209         return restore(@default)
210       else
211         return nil
212       end
213     end
214
215     # set a key in the registry
216     def []=(key,value)
217       registry[key] = store(value)
218     end
219
220     # set the default value for registry lookups, if the key sought is not
221     # found, the default will be returned. The default default (har) is nil.
222     def set_default (default)
223       @default = store(default)
224     end
225
226     # just like Hash#each
227     def each(&block)
228       registry.each {|key,value|
229         block.call(key, restore(value))
230       }
231     end
232
233     # just like Hash#each_key
234     def each_key(&block)
235       registry.each {|key, value|
236         block.call(key)
237       }
238     end
239
240     # just like Hash#each_value
241     def each_value(&block)
242       registry.each {|key, value|
243         block.call(restore(value))
244       }
245     end
246
247     # just like Hash#has_key?
248     def has_key?(key)
249       return registry.has_key?(key)
250     end
251     alias include? has_key?
252     alias member? has_key?
253
254     # just like Hash#has_both?
255     def has_both?(key, value)
256       return registry.has_both?(key, store(value))
257     end
258
259     # just like Hash#has_value?
260     def has_value?(value)
261       return registry.has_value?(store(value))
262     end
263
264     # just like Hash#index?
265     def index(value)
266       ind = registry.index(store(value))
267       if ind
268         return ind
269       else
270         return nil
271       end
272     end
273
274     # delete a key from the registry
275     def delete(key)
276       return registry.delete(key)
277     end
278
279     # returns a list of your keys
280     def keys
281       return registry.keys
282     end
283
284     # Return an array of all associations [key, value] in your namespace
285     def to_a
286       ret = Array.new
287       registry.each {|key, value|
288         ret << [key, restore(value)]
289       }
290       return ret
291     end
292
293     # Return an hash of all associations {key => value} in your namespace
294     def to_hash
295       ret = Hash.new
296       registry.each {|key, value|
297         ret[key] = restore(value)
298       }
299       return ret
300     end
301
302     # empties the registry (restricted to your namespace)
303     def clear
304       registry.clear
305     end
306     alias truncate clear
307
308     # returns an array of the values in your namespace of the registry
309     def values
310       ret = Array.new
311       self.each {|k,v|
312         ret << restore(v)
313       }
314       return ret
315     end
316
317     def sub_registry(prefix)
318       return BotRegistryAccessor.new(@bot, @name + "/" + prefix.to_s)
319     end
320
321     # returns the number of keys in your registry namespace
322     def length
323       self.keys.length
324     end
325     alias size length
326
327   end
328
329 end