]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/registry.rb
* apparently, synthetic privmsgs for remotectl are hard. may need some massive rework...
[user/henk/code/ruby/rbot.git] / 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     # plugins don't call this - a BotRegistryAccessor is created for them and
122     # is accessible via @registry.
123     def initialize(bot, name)
124       @bot = bot
125       @name = name.downcase
126       dirs = File.dirname("#{@bot.botclass}/registry/#{@name}").split("/")
127       dirs.length.times { |i|
128         dir = dirs[0,i+1].join("/")+"/"
129         unless File.exist?(dir)
130           debug "creating subregistry directory #{dir}"
131           Dir.mkdir(dir) 
132         end
133       }
134       @registry = nil
135       @default = nil
136       # debug "initializing registry accessor with name #{@name}"
137     end
138
139     def registry
140         @registry ||= DBTree.new @bot, "registry/#{@name}"
141     end
142
143     def flush
144       # debug "fushing registry #{registry}"
145       return if !@registry
146       registry.flush
147       registry.sync
148     end
149
150     def close
151       # debug "closing registry #{registry}"
152       return if !@registry
153       registry.close
154     end
155
156     # convert value to string form for storing in the registry
157     # defaults to Marshal.dump(val) but you can override this in your module's
158     # registry object to use any method you like.
159     # For example, if you always just handle strings use:
160     #   def store(val)
161     #     val
162     #   end
163     def store(val)
164       Marshal.dump(val)
165     end
166
167     # restores object from string form, restore(store(val)) must return val.
168     # If you override store, you should override restore to reverse the
169     # action.
170     # For example, if you always just handle strings use:
171     #   def restore(val)
172     #     val
173     #   end
174     def restore(val)
175       begin
176         Marshal.restore(val)
177       rescue Exception => e
178         warning "failed to restore marshal data for #{val.inspect}, falling back to default"
179         debug e.inspect
180         debug e.backtrace.join("\n")
181         if @default != nil
182           begin
183             return Marshal.restore(@default)
184           rescue
185             return nil
186           end
187         else
188           return nil
189         end
190       end
191     end
192
193     # lookup a key in the registry
194     def [](key)
195       if registry.has_key?(key)
196         return restore(registry[key])
197       elsif @default != nil
198         return restore(@default)
199       else
200         return nil
201       end
202     end
203
204     # set a key in the registry
205     def []=(key,value)
206       registry[key] = store(value)
207     end
208
209     # set the default value for registry lookups, if the key sought is not
210     # found, the default will be returned. The default default (har) is nil.
211     def set_default (default)
212       @default = store(default)
213     end
214
215     # just like Hash#each
216     def each(&block)
217       registry.each {|key,value|
218         block.call(key, restore(value))
219       }
220     end
221
222     # just like Hash#each_key
223     def each_key(&block)
224       registry.each {|key, value|
225         block.call(key)
226       }
227     end
228
229     # just like Hash#each_value
230     def each_value(&block)
231       registry.each {|key, value|
232         block.call(restore(value))
233       }
234     end
235
236     # just like Hash#has_key?
237     def has_key?(key)
238       return registry.has_key?(key)
239     end
240     alias include? has_key?
241     alias member? has_key?
242
243     # just like Hash#has_both?
244     def has_both?(key, value)
245       return registry.has_both?(key, store(value))
246     end
247
248     # just like Hash#has_value?
249     def has_value?(value)
250       return registry.has_value?(store(value))
251     end
252
253     # just like Hash#index?
254     def index(value)
255       ind = registry.index(store(value))
256       if ind
257         return ind
258       else
259         return nil
260       end
261     end
262
263     # delete a key from the registry
264     def delete(key)
265       return registry.delete(key)
266     end
267
268     # returns a list of your keys
269     def keys
270       return registry.keys
271     end
272
273     # Return an array of all associations [key, value] in your namespace
274     def to_a
275       ret = Array.new
276       registry.each {|key, value|
277         ret << [key, restore(value)]
278       }
279       return ret
280     end
281
282     # Return an hash of all associations {key => value} in your namespace
283     def to_hash
284       ret = Hash.new
285       registry.each {|key, value|
286         ret[key] = restore(value)
287       }
288       return ret
289     end
290
291     # empties the registry (restricted to your namespace)
292     def clear
293       registry.clear
294     end
295     alias truncate clear
296
297     # returns an array of the values in your namespace of the registry
298     def values
299       ret = Array.new
300       self.each {|k,v|
301         ret << restore(v)
302       }
303       return ret
304     end
305
306     def sub_registry(prefix)
307       return BotRegistryAccessor.new(@bot, @name + "/" + prefix.to_s)
308     end
309
310     # returns the number of keys in your registry namespace
311     def length
312       self.keys.length
313     end
314     alias size length
315
316   end
317
318 end