registry.rb: don't create registry file unless accessing it for writing
[rbot] / lib / rbot / registry.rb
1 require 'rbot/dbhash'
2
3 module Irc
4 class Bot
5
6   # This class is now used purely for upgrading from prior versions of rbot
7   # the new registry is split into multiple DBHash objects, one per plugin
8   class Registry
9     def initialize(bot)
10       @bot = bot
11       upgrade_data
12       upgrade_data2
13     end
14
15     # check for older versions of rbot with data formats that require updating
16     # NB this function is called _early_ in init(), pretty much all you have to
17     # work with is @bot.botclass.
18     def upgrade_data
19       if File.exist?("#{@bot.botclass}/registry.db")
20         log _("upgrading old-style (rbot 0.9.5 or earlier) plugin registry to new format")
21         old = BDB::Hash.open("#{@bot.botclass}/registry.db", nil,
22                              "r+", 0600)
23         new = BDB::CIBtree.open("#{@bot.botclass}/plugin_registry.db", nil,
24                                 BDB::CREATE | BDB::EXCL,
25                                 0600)
26         old.each {|k,v|
27           new[k] = v
28         }
29         old.close
30         new.close
31         File.rename("#{@bot.botclass}/registry.db", "#{@bot.botclass}/registry.db.old")
32       end
33     end
34
35     def upgrade_data2
36       if File.exist?("#{@bot.botclass}/plugin_registry.db")
37         Dir.mkdir("#{@bot.botclass}/registry") unless File.exist?("#{@bot.botclass}/registry")
38         env = BDB::Env.open("#{@bot.botclass}", BDB::INIT_TRANSACTION | BDB::CREATE | BDB::RECOVER)# | BDB::TXN_NOSYNC)
39         dbs = Hash.new
40         log _("upgrading previous (rbot 0.9.9 or earlier) plugin registry to new split format")
41         old = BDB::CIBtree.open("#{@bot.botclass}/plugin_registry.db", nil,
42           "r+", 0600, "env" => env)
43         old.each {|k,v|
44           prefix,key = k.split("/", 2)
45           prefix.downcase!
46           # subregistries were split with a +, now they are in separate folders
47           if prefix.gsub!(/\+/, "/")
48             # Ok, this code needs to be put in the db opening routines
49             dirs = File.dirname("#{@bot.botclass}/registry/#{prefix}.db").split("/")
50             dirs.length.times { |i|
51               dir = dirs[0,i+1].join("/")+"/"
52               unless File.exist?(dir)
53                 log _("creating subregistry directory #{dir}")
54                 Dir.mkdir(dir)
55               end
56             }
57           end
58           unless dbs.has_key?(prefix)
59             log _("creating db #{@bot.botclass}/registry/#{prefix}.db")
60             dbs[prefix] = BDB::CIBtree.open("#{@bot.botclass}/registry/#{prefix}.db",
61               nil, BDB::CREATE | BDB::EXCL,
62               0600, "env" => env)
63           end
64           dbs[prefix][key] = v
65         }
66         old.close
67         File.rename("#{@bot.botclass}/plugin_registry.db", "#{@bot.botclass}/plugin_registry.db.old")
68         dbs.each {|k,v|
69           log _("closing db #{k}")
70           v.close
71         }
72         env.close
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 Registry#[]
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 Accessor
121
122     attr_accessor :recovery
123
124     # plugins don't call this - a Registry::Accessor is created for them and
125     # is accessible via @registry.
126     def initialize(bot, name)
127       @bot = bot
128       @name = name.downcase
129       @filename = "#{@bot.botclass}/registry/#{@name}"
130       dirs = File.dirname(@filename).split("/")
131       dirs.length.times { |i|
132         dir = dirs[0,i+1].join("/")+"/"
133         unless File.exist?(dir)
134           debug "creating subregistry directory #{dir}"
135           Dir.mkdir(dir)
136         end
137       }
138       @filename << ".db"
139       @registry = nil
140       @default = nil
141       @recovery = nil
142       # debug "initializing registry accessor with name #{@name}"
143     end
144
145     def registry
146         @registry ||= DBTree.new @bot, "registry/#{@name}"
147     end
148
149     def flush
150       # debug "fushing registry #{registry}"
151       return if !@registry
152       registry.flush
153       registry.sync
154     end
155
156     def close
157       # debug "closing registry #{registry}"
158       return if !@registry
159       registry.close
160     end
161
162     # convert value to string form for storing in the registry
163     # defaults to Marshal.dump(val) but you can override this in your module's
164     # registry object to use any method you like.
165     # For example, if you always just handle strings use:
166     #   def store(val)
167     #     val
168     #   end
169     def store(val)
170       Marshal.dump(val)
171     end
172
173     # restores object from string form, restore(store(val)) must return val.
174     # If you override store, you should override restore to reverse the
175     # action.
176     # For example, if you always just handle strings use:
177     #   def restore(val)
178     #     val
179     #   end
180     def restore(val)
181       begin
182         Marshal.restore(val)
183       rescue Exception => e
184         error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
185         debug e
186         if defined? @recovery and @recovery
187           begin
188             return @recovery.call(val)
189           rescue Exception => ee
190             error _("marshal recovery failed, trying default")
191             debug ee
192           end
193         end
194         unless @default.nil?
195           begin
196             return Marshal.restore(@default)
197           rescue
198             return nil
199           end
200         else
201           return nil
202         end
203       end
204     end
205
206     # lookup a key in the registry
207     def [](key)
208       return nil unless File.exist?(@filename)
209       if registry.has_key?(key)
210         return restore(registry[key])
211       elsif @default != nil
212         return restore(@default)
213       else
214         return nil
215       end
216     end
217
218     # set a key in the registry
219     def []=(key,value)
220       registry[key] = store(value)
221     end
222
223     # set the default value for registry lookups, if the key sought is not
224     # found, the default will be returned. The default default (har) is nil.
225     def set_default (default)
226       @default = store(default)
227     end
228
229     # just like Hash#each
230     def each(&block)
231       return nil unless File.exist?(@filename)
232       registry.each {|key,value|
233         block.call(key, restore(value))
234       }
235     end
236
237     # just like Hash#each_key
238     def each_key(&block)
239       return nil unless File.exist?(@filename)
240       registry.each {|key, value|
241         block.call(key)
242       }
243     end
244
245     # just like Hash#each_value
246     def each_value(&block)
247       return nil unless File.exist?(@filename)
248       registry.each {|key, value|
249         block.call(restore(value))
250       }
251     end
252
253     # just like Hash#has_key?
254     def has_key?(key)
255       return false unless File.exist?(@filename)
256       return registry.has_key?(key)
257     end
258     alias include? has_key?
259     alias member? has_key?
260     alias key? has_key?
261
262     # just like Hash#has_both?
263     def has_both?(key, value)
264       return false unless File.exist?(@filename)
265       return registry.has_both?(key, store(value))
266     end
267
268     # just like Hash#has_value?
269     def has_value?(value)
270       return false unless File.exist?(@filename)
271       return registry.has_value?(store(value))
272     end
273
274     # just like Hash#index?
275     def index(value)
276       return nil unless File.exist?(@filename)
277       ind = registry.index(store(value))
278       if ind
279         return ind
280       else
281         return nil
282       end
283     end
284
285     # delete a key from the registry
286     def delete(key)
287       return nil unless File.exist?(@filename)
288       return registry.delete(key)
289     end
290
291     # returns a list of your keys
292     def keys
293       return [] unless File.exist?(@filename)
294       return registry.keys
295     end
296
297     # Return an array of all associations [key, value] in your namespace
298     def to_a
299       return [] unless File.exist?(@filename)
300       ret = Array.new
301       registry.each {|key, value|
302         ret << [key, restore(value)]
303       }
304       return ret
305     end
306
307     # Return an hash of all associations {key => value} in your namespace
308     def to_hash
309       return {} unless File.exist?(@filename)
310       ret = Hash.new
311       registry.each {|key, value|
312         ret[key] = restore(value)
313       }
314       return ret
315     end
316
317     # empties the registry (restricted to your namespace)
318     def clear
319       return true unless File.exist?(@filename)
320       registry.clear
321     end
322     alias truncate clear
323
324     # returns an array of the values in your namespace of the registry
325     def values
326       return [] unless File.exist?(@filename)
327       ret = Array.new
328       self.each {|k,v|
329         ret << restore(v)
330       }
331       return ret
332     end
333
334     def sub_registry(prefix)
335       return Accessor.new(@bot, @name + "/" + prefix.to_s)
336     end
337
338     # returns the number of keys in your registry namespace
339     def length
340       self.keys.length
341     end
342     alias size length
343
344   end
345
346   end
347 end
348 end