use a db env for the databases to avoid some corruption problems (I hope)
[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         puts "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.delete("#{@bot.botclass}/registry.db")
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)
38         dbs = Hash.new
39         puts "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           unless dbs.has_key?(prefix)
46             puts "creating db #{@bot.botclass}/registry/#{prefix}.db"
47             dbs[prefix] = BDB::CIBtree.open("#{@bot.botclass}/registry/#{prefix}.db",
48               nil, BDB::CREATE | BDB::EXCL,
49               0600, "env" => env)
50               
51           end
52           dbs[prefix][key] = v
53         }
54         old.close
55         File.rename("#{@bot.botclass}/plugin_registry.db", "#{@bot.botclass}/plugin_registry.db.old")
56         dbs.each {|k,v|
57           puts "closing db #{k}"
58           v.close
59         }
60         env.close
61       end
62     end
63   end
64   
65
66   # This class provides persistent storage for plugins via a hash interface.
67   # The default mode is an object store, so you can store ruby objects and
68   # reference them with hash keys. This is because the default store/restore
69   # methods of the plugins' RegistryAccessor are calls to Marshal.dump and
70   # Marshal.restore,
71   # for example:
72   #   blah = Hash.new
73   #   blah[:foo] = "fum"
74   #   @registry[:blah] = blah
75   # then, even after the bot is shut down and disconnected, on the next run you
76   # can access the blah object as it was, with:
77   #   blah = @registry[:blah]
78   # The registry can of course be used to store simple strings, fixnums, etc as
79   # well, and should be useful to store or cache plugin data or dynamic plugin
80   # configuration. 
81   #
82   # WARNING:
83   # in object store mode, don't make the mistake of treating it like a live
84   # object, e.g. (using the example above)
85   #   @registry[:blah][:foo] = "flump"
86   # will NOT modify the object in the registry - remember that BotRegistry#[]
87   # returns a Marshal.restore'd object, the object you just modified in place
88   # will disappear. You would need to:
89   #   blah = @registry[:blah]
90   #   blah[:foo] = "flump"
91   #   @registry[:blah] = blah
92
93   # If you don't need to store objects, and strictly want a persistant hash of
94   # strings, you can override the store/restore methods to suit your needs, for
95   # example (in your plugin):
96   #   def initialize
97   #     class << @registry
98   #       def store(val)
99   #         val
100   #       end
101   #       def restore(val)
102   #         val
103   #       end
104   #     end
105   #   end
106   # Your plugins section of the registry is private, it has its own namespace
107   # (derived from the plugin's class name, so change it and lose your data).
108   # Calls to registry.each etc, will only iterate over your namespace.
109   class BotRegistryAccessor
110     # plugins don't call this - a BotRegistryAccessor is created for them and
111     # is accessible via @registry.
112     def initialize(bot, name)
113       @bot = bot
114       @name = name.downcase
115       @registry = DBTree.new bot, "registry/#{@name}"
116       @default = nil
117       # debug "initializing registry accessor with name #{@name}"
118     end
119
120     def flush
121       @registry.flush
122     end
123
124     # convert value to string form for storing in the registry
125     # defaults to Marshal.dump(val) but you can override this in your module's
126     # registry object to use any method you like.
127     # For example, if you always just handle strings use:
128     #   def store(val)
129     #     val
130     #   end
131     def store(val)
132       Marshal.dump(val)
133     end
134
135     # restores object from string form, restore(store(val)) must return val.
136     # If you override store, you should override restore to reverse the
137     # action.
138     # For example, if you always just handle strings use:
139     #   def restore(val)
140     #     val
141     #   end
142     def restore(val)
143       begin
144         Marshal.restore(val)
145       rescue Exception
146         $stderr.puts "failed to restore marshal data, falling back to default"
147         if @default != nil
148           begin
149             return Marshal.restore(@default)
150           rescue
151             return nil
152           end
153         else
154           return nil
155         end
156       end
157     end
158
159     # lookup a key in the registry
160     def [](key)
161       if @registry.has_key?(key)
162         return restore(@registry[key])
163       elsif @default != nil
164         return restore(@default)
165       else
166         return nil
167       end
168     end
169
170     # set a key in the registry
171     def []=(key,value)
172       @registry[key] = store(value)
173     end
174
175     # set the default value for registry lookups, if the key sought is not
176     # found, the default will be returned. The default default (har) is nil.
177     def set_default (default)
178       @default = store(default)
179     end
180
181     # just like Hash#each
182     def each(&block)
183       @registry.each {|key,value|
184         block.call(key, restore(value))
185       }
186     end
187     
188     # just like Hash#each_key
189     def each_key(&block)
190       @registry.each {|key, value|
191         block.call(key)
192       }
193     end
194     
195     # just like Hash#each_value
196     def each_value(&block)
197       @registry.each {|key, value|
198         block.call(restore(value))
199       }
200     end
201
202     # just like Hash#has_key?
203     def has_key?(key)
204       return @registry.has_key?(key)
205     end
206     alias include? has_key?
207     alias member? has_key?
208
209     # just like Hash#has_both?
210     def has_both?(key, value)
211       return @registry.has_both?(key, store(value))
212     end
213     
214     # just like Hash#has_value?
215     def has_value?(value)
216       return @registry.has_value?(store(value))
217     end
218
219     # just like Hash#index?
220     def index(value)
221       ind = @registry.index(store(value))
222       if ind
223         return ind
224       else
225         return nil
226       end
227     end
228     
229     # delete a key from the registry
230     def delete(key)
231       return @registry.delete(key)
232     end
233
234     # returns a list of your keys
235     def keys
236       return @registry.keys
237     end
238
239     # Return an array of all associations [key, value] in your namespace
240     def to_a
241       ret = Array.new
242       @registry.each {|key, value|
243         ret << [key, restore(value)]
244       }
245       return ret
246     end
247     
248     # Return an hash of all associations {key => value} in your namespace
249     def to_hash
250       ret = Hash.new
251       @registry.each {|key, value|
252         ret[key] = restore(value)
253       }
254       return ret
255     end
256
257     # empties the registry (restricted to your namespace)
258     def clear
259       @registry.clear
260     end
261     alias truncate clear
262
263     # returns an array of the values in your namespace of the registry
264     def values
265       ret = Array.new
266       self.each {|k,v|
267         ret << restore(v)
268       }
269       return ret
270     end
271
272     # returns the number of keys in your registry namespace
273     def length
274       self.keys.length
275     end
276     alias size length
277
278   end
279
280 end