summaryrefslogtreecommitdiff
path: root/bin/rbotdb
blob: b59498033011e9e2903612eb9fbbee70a416906b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env ruby
#-- vim:sw=2:et
#++
#
# :title: RBot Registry Backup, Restore and Migration Script.
#
# You can use this script to,
#   - backup the rbot registry in a format that is platform/engine independent
#   - restore these backups in supported formats (dbm, daybreak)
#   - migrate old rbot registries bdb (ruby 1.8) and tokyocabinet.
#
# For more information, just execute the script without any arguments!
#
# Author:: apoc (Matthias Hecker) <apoc@geekosphere.org>
# Copyright:: (C) 2014 Matthias Hecker
# License:: GPLv3

begin; require 'rubygems'; rescue Exception; end

# load registry formats:
begin; require 'bdb'; rescue Exception; end
begin; require 'tokyocabinet'; rescue Exception; end
begin; require 'dbm'; rescue Exception; end
begin; require 'daybreak'; rescue Exception; end
begin; require 'sqlite3'; rescue Exception; end

puts 'RBot Registry Backup/Restore/Migrate'
puts '[%s]' % ['Ruby: ' + RUBY_VERSION,
               'DBM: ' + (DBM::VERSION rescue '-'),
               'BDB: ' + (BDB::VERSION rescue '-'),
               'TokyoCabinet: ' + (TokyoCabinet::VERSION rescue '-'),
               'Daybreak: ' + (Daybreak::VERSION rescue '-'),
               'SQLite: ' + (SQLite3::VERSION rescue '-'),
              ].join(' | ')

require 'date'
require 'optparse'

TYPES = [:bdb, :tc, :dbm, :daybreak, :sqlite]
options = {
  :profile => '~/.rbot',
  :registry => nil,
  :dbfile => './%s.rbot' % DateTime.now.strftime('backup_%Y-%m-%d_%H%M%S'),
  :type => nil
}
opt_parser = OptionParser.new do |opt|
  opt.banner = 'Usage: rbotdb COMMAND [OPTIONS]'
  opt.separator ''
  opt.separator 'Commands:'
  opt.separator '     backup: store rbot registry platform-independently in a file.'
  opt.separator '     restore: restore rbot registry from such a file.'
  opt.separator ''
  opt.separator 'Options:'

  opt.on('-t', '--type TYPE', TYPES, 'format to backup/restore. Values: %s.' % [TYPES.join(', ')]) do |type|
    options[:type] = type
  end

  opt.on('-p', '--profile [PROFILE]', 'rbot profile directory. Defaults to: %s.' % options[:profile]) do |profile|
    options[:profile] = profile
  end

  opt.on('-r', '--registry [REGISTRY]', 'registry-path to read/write, Optional, defaults to: <PROFILE>/registry_<TYPE>.') do |profile|
    options[:registry] = profile
  end

  opt.on('-f', '--file [DBFILE]', 'cross-platform file to backup to/restore from. Defaults to: %s.' % options[:dbfile]) do |dbfile|
    options[:dbfile] = dbfile
  end

  opt.separator ''
end

class BackupRegistry
  def initialize(profile, type, registry)
    @profile = File.expand_path profile
    @type = type
    @registry = registry
    puts 'Using type=%s profile=%s registry=%s' % [@type, @profile, @registry.inspect]
  end

  # returns a hash with the complete registry data
  def backup
    listings = search
    puts 'Found registry types: bdb=%d tc=%d dbm=%d daybreak=%d sqlite=%d' % [
      listings[:bdb].length, listings[:tc].length,
      listings[:dbm].length, listings[:daybreak].length, listings[:sqlite].length
    ]
    if listings[@type].empty?
      puts 'No suitable registry found!'
      exit
    end
    puts 'Using registry type: %s' % @type
    read(listings[@type])
  end

  def read(listing)
    print "~Reading... (this might take a moment)\r"
    data = {}
    count = 0
    listing.each do |file|
      begin
        data[file.key] = case @type
        when :tc
          read_tc(file)
        when :bdb
          read_bdb(file)
        when :dbm
          read_dbm(file)
        when :daybreak
          read_daybreak(file)
        when :sqlite
          read_sqlite(file)
        end
        count += data[file.key].length
      rescue
        puts 'ERROR: <%s> %s' % [$!.class, $!]
        puts $@.join("\n")
        puts 'Keep in mind that, even minor version differences of'
        puts 'Barkeley DB or Tokyocabinet make files unreadable. Use this'
        puts 'script on the exact same platform rbot was running!'
        exit
      end
    end
    puts 'Read %d registry files, with %d entries.' % [data.length, count]
    data
  end

  def read_bdb(file)
    data = {}
    db = BDB::Hash.open(file.abs, nil, 'r')
    db.each do |key, value|
      data[key] = value
    end
    db.close
    data
  end

  def read_tc(file)
    data = {}
    db = TokyoCabinet::BDB.new
    db.open(file.abs, TokyoCabinet::BDB::OREADER)
    db.each do |key, value|
      data[key] = value
    end
    db.close
    data
  end

  def read_dbm(file)
    db = DBM.open(file.abs.gsub(/\.[^\.]+$/,''), 0666, DBM::READER)
    data = db.to_hash
    db.close
    data
  end

  def read_daybreak(file)
    data = {}
    db = Daybreak::DB.new(file.abs)
    db.each do |key, value|
      data[key] = value
    end
    db.close
    data
  end

  def read_sqlite(file)
    data = {}
    db = SQLite3::Database.new(file.abs)
    res = db.execute('SELECT key, value FROM data')
    res.each do |row|
      key, value = row
      data[key] = value
    end
    db.close
    data
  end

  # searches in profile directory for existing registry formats
  def search
    {
      :bdb => list(get_registry, '*.db'),
      :tc => list(get_registry('_tc'), '*.tdb'),
      :dbm => list(get_registry('_dbm'), '*.*'),
      :daybreak => list(get_registry('_daybreak'), '*.db'),
      :sqlite => list(get_registry('_sqlite'), '*.db'),
    }
  end

  def get_registry(suffix='')
    if @registry
      File.expand_path(@registry)
    else
      File.join(@profile, 'registry'+suffix)
    end
  end

  class RegistryFile
    def initialize(folder, name)
      @folder = folder
      @name = name
      @key = name.gsub(/\.[^\.]+$/,'')
    end
    attr_reader :folder, :name, :key
    def abs
      File.expand_path(File.join(@folder, @name))
    end
    def ext
      File.extname(@name)
    end
  end

  def list(folder, ext='*.db')
    return [] if not File.directory? folder
    Dir.chdir(folder) do
      Dir.glob(File.join('**', ext)).map do |name|
        RegistryFile.new(folder, name) if File.exists?(name)
      end
    end
  end
end

class RestoreRegistry
  def initialize(profile, type, registry)
    @profile = File.expand_path profile
    @registry = registry ? File.expand_path(registry) : nil
    @type = type
    puts 'Using type=%s profile=%s' % [@type, @profile]
  end

  def restore(data)
    puts 'Using registry type: %s' % @type
    folder = create_folder
    print "~Restoring... (this might take a moment)\r"
    data.each do |file, hash|
      file = File.join(folder, file)
      create_subdir(file)
      case @type
      when :dbm
        write_dbm(file, hash)
      when :tc
        write_tc(file, hash)
      when :daybreak
        write_daybreak(file, hash)
      when :sqlite
        write_sqlite(file, hash)
      end
    end
    puts  'Restore successful!                        '
  end

  def write_dbm(file, data)
    db = DBM.open(file, 0666, DBM::WRCREAT)
    data.each_pair do |key, value|
      db[key] = value
    end
    db.close
  end

  def write_tc(file, data)
    db = TokyoCabinet::BDB.new
    db.open(file + '.tdb',
          TokyoCabinet::BDB::OREADER | 
          TokyoCabinet::BDB::OCREAT | 
          TokyoCabinet::BDB::OWRITER)
    data.each_pair do |key, value|
      db[key] = value
    end
    db.optimize
    db.close
  end

  def write_daybreak(file, data)
    db = Daybreak::DB.new(file + '.db')
    data.each_pair do |key, value|
      db[key] = value
    end
    db.close
  end

  def write_sqlite(file, data)
    db = SQLite3::Database.new(file + '.db')
    db.execute('CREATE TABLE data (key string, value blob)') 
    data.each_pair do |key, value|
      db.execute('INSERT INTO data VALUES (?, ?)', 
            key, value)
    end
    db.close
  end

  def create_folder
    if @registry
      folder = @registry
    else
      folder = File.join(@profile, 'registry_%s' % [@type.to_s])
    end
    Dir.mkdir(folder) unless File.directory?(folder)
    if File.directory?(folder) and Dir.glob(File.join(folder, '**')).select{|f|File.file? f}.length>0
      puts 'ERROR: Unable to restore!'
      puts 'Restore folder exists and is not empty: ' + folder
      exit
    end
    folder
  end

  # used to create subregistry folders
  def create_subdir(path)
    dirs = File.dirname(path).split('/')
    dirs.length.times { |i|
      dir = dirs[0,i+1].join("/")+"/"
      unless File.exist?(dir)
        Dir.mkdir(dir)
      end
    }
  end
end

opt_parser.parse!
if ARGV.length > 0 and options[:type].nil?
  puts opt_parser
  puts 'Missing Argument: -t [type]'
  exit
end

case ARGV[0]
when 'backup'
  if File.exists? options[:dbfile]
    puts 'Backup file already exists.'
    exit 
  end

  reg = BackupRegistry.new(options[:profile], options[:type], options[:registry])

  data = reg.backup

  if not data.empty?
    File.open(options[:dbfile], 'w') do |f|
      f.write(Marshal.dump(data))
    end
    puts 'Written registry to ' + options[:dbfile]
  end

when 'restore'
  unless File.exists? options[:dbfile]
    puts 'Backup file does not exist.'
    exit 
  end

  reg = RestoreRegistry.new(options[:profile], options[:type], options[:registry])
  data = Marshal.load File.read(options[:dbfile])

  puts 'Read %d registry files from backup file.' % data.length
  reg.restore data

else
  puts opt_parser

end