Class: Six::Repositories::Rsync::Lib

Inherits:
Object
  • Object
show all
Defined in:
lib/six/rsync/lib.rb

Constant Summary collapse

PROTECTED =
false
WINDRIVE =
/\"(\w)\:/
DEFAULT_CONFIG =
{:hosts => [], :exclude => [], :include => []}.to_yaml
DEFAULT_TIMEOUT =
60
PARAMS =
if PROTECTED
  "--dry-run --times -O --no-whole-file -r --delete --progress -h --exclude=.rsync"
else
  "--times -O --no-whole-file -r --delete --progress -h --exclude=.rsync"
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base = nil, logger = nil) ⇒ Lib

Returns a new instance of Lib.



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
# File 'lib/six/rsync/lib.rb', line 24

def initialize(base = nil, logger = nil)
  @rsync_dir = nil
  @rsync_work_dir = nil
  @path = nil
  @stats = false
  @verbose = true
  @logger = logger

  case RUBY_PLATFORM
    when /-mingw32$/, /-mswin32$/
      key = CONFIG[:key] ? CONFIG[:key] : ""
      @rsh = "-r --rsh=\"'cygnative.exe' plink.exe#{" -i #{key}" unless key.empty?}\""
    else
      @rsh = ""
  end

  # which rsync - should return on linux the bin location
  rsync_installed = begin; %x[rsync --version]; true; rescue; false; end
  unless rsync_installed
    puts "rsync command not found"
    raise RsyncError
  end

  @repos_local = {:pack => Hash.new, :wd => Hash.new, :version => 0}
  @repos_remote = {:pack => Hash.new, :wd => Hash.new, :version => 0}

  if base.is_a?(Rsync::Base)
    @rsync_dir = base.repo.path
    @rsync_work_dir = base.dir.path if base.dir
  elsif base.is_a?(Hash)
    @rsync_dir = base[:repository]
    @rsync_work_dir = base[:working_directory]
  end

  @rsync_dir.gsub!("\\", "/") if @rsync_dir
  @rsync_work_dir.gsub!("\\", "/") if @rsync_work_dir
end

Instance Attribute Details

#verboseObject

Returns the value of attribute verbose.



13
14
15
# File 'lib/six/rsync/lib.rb', line 13

def verbose
  @verbose
end

Instance Method Details

#add(file) ⇒ Object

TODO: WIP



161
162
163
164
# File 'lib/six/rsync/lib.rb', line 161

def add(file)
  @logger.error "Please use commit instead!"
  return
end

#bla(file) ⇒ Object



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
# File 'lib/six/rsync/lib.rb', line 166

def bla(file)
  @logger.info "Adding #{file}"
  if (file == ".")
    load_repos(:remote)
    @logger.info "Calculating Checksums..."
    ar = Dir[File.join(@rsync_work_dir, '/**/*')]

    change = false
    ar.each_with_index do |file, i|
      unless file[/\.gz$/]
        relative = file.clone
        relative.gsub!(@rsync_work_dir, '')
        relative.gsub!(/^[\\|\/]/, '')

        checksum = md5(file)
        if checksum != @repos_remote[:wd][relative]
          change = true
          @logger.info "Packing #{i + 1}/#{ar.size}: #{file}"
          gzip(file)
          FileUtils.mkdir_p(File.dirname(pack_path(relative))) unless File.exists?(File.dirname(pack_path(relative)))
          checksum2 = md5("#{file}.gz")
          @repos_remote[:wd][relative] = checksum
          @repos_remote[:pack]["#{relative}.gz"] = checksum2
          @repos_local[:wd][relative] = checksum
          @repos_local[:pack]["#{relative}.gz"] = checksum2
          FileUtils.mv("#{file}.gz", pack_path("#{relative}.gz"))
        end
      end
    end
    if change
      save_repos
      save_repos(:remote)
    end
  else

  end
end

#clone(repository, name, opts = {}) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/six/rsync/lib.rb', line 342

def clone(repository, name, opts = {})
  @path = opts[:path] || '.'
  @rsync_work_dir = opts[:path] ? File.join(@path, name) : name

  # TODO: Solve logger mess completely.
  @logger = opts[:log] if opts[:log]

  case repository
    when Array
      config[:hosts] += repository
    when String
      config[:hosts] << repository
  end

  # TODO: Eval move to update?
  arr_opts = []
  arr_opts << "-I" if opts[:force]

  init
  config[:include] = opts[:include] if opts.keys.include?(:include)
  config[:exclude] = opts[:exclude] if opts.keys.include?(:exclude)
  config[:hosts] = opts[:hosts] if opts.keys.include?(:hosts)
  save_config(config)

  update('', arr_opts, opts.merge({:force => true}))
  opts[:bare] ? {:repository => @rsync_work_dir} : {:working_directory => @rsync_work_dir}
end

#commitObject



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
# File 'lib/six/rsync/lib.rb', line 204

def commit
  cfg = CONFIG[:commit] ? CONFIG[:commit] : Hash.new
  @logger.info "Committing changes on #{@rsync_work_dir}"
  handle_config
  handle_hosts

  load_repos(:local)
  load_repos(:remote)

=begin
  # TODO: Rewrite
  if cfg[:force_downcase]
    # Run through all files, only in the working folder!, and downcase those which are not
    Dir.glob(File.join(@rsync_work_dir, '**', '*')).each do |entry|
      dirname, base = File.dirname(entry), File.basename(entry)
      if base[/[A-Z]/]
        part = entry.sub("#{@rsync_work_dir}", '')
        part.sub!(/^\//, "")
        if @repos_local[:wd][part]
          @repos_local[:wd].delete part
          @repos_local[:wd][]
        end
        rename(entry, File.join(dirname, base.downcase))
      end
    end
  end
=end

  @logger.info "Calculating Checksums..."
  handle_case

  @repos_local[:wd] = calc_sums(:wd)
  # Added or Changed files
  ar = Dir[File.join(@rsync_work_dir, '/**/*')]

  change = false
  i = 0
  @repos_local[:wd].each_pair do |key, value|
    i += 1
    if value != @repos_remote[:wd][key]
      change = true
      @logger.info "Packing #{i}/#{@repos_local[:wd].size}: #{key}"
      file = File.join(@rsync_work_dir, key)
      folder = File.dirname(file)
      folder.gsub!(@rsync_work_dir, '')
      gzip(file)
      @repos_local[:pack]["#{key}.gz"] = md5("#{file}.gz")
      FileUtils.mkdir_p pack_path(folder) if folder.size > 0
      FileUtils.mv("#{file}.gz", pack_path("#{key}.gz"))
    end
  end

  # Deleted files
  @logger.info "Checking for deleted files..."

  i = 0
  @repos_remote[:wd].each_pair do |key, value|
    i += 1
    if @repos_local[:wd][key].nil?
      packed = "#{key}.gz"
      change = true
      file = pack_path(packed)

      @logger.info "Removing: #{packed}"
      @repos_local[:wd].delete key
      @repos_local[:pack].delete packed
      FileUtils.rm_f(file) if File.exists?(file)
    end
  end

  @repos_local[:pack].each_pair do |key, value|
    i += 1
    localkey = "#{key}"
    localkey.gsub!(/\.gz$/, "")
    if @repos_local[:wd][localkey].nil?
      @logger.info "Removing: #{key}"

      change = true
      file = pack_path(key)
      @repos_local[:pack].delete key
      FileUtils.rm_f(file) if File.exists?(file)
    end
  end


  if change
    @logger.info "Changes found!"
    save_repos(:local)

    host = config[:hosts].sample

    verfile_srv = File.join(".pack", ".repository.yml")
    verbose = @verbose
    @verbose = false
    begin
      fetch_file(verfile_srv, host)
    rescue => e
      # FIXME: Should never assume that :)
      @logger.warn "Unable to retrieve version file from server, repository probably doesnt exist!"
      @logger.debug "ERROR: #{e.class} #{e.message} #{e.backtrace.join("\n")}"
      # raise RsyncExecuteError
    end
    @verbose = verbose

    load_repos(:remote)

    if @repos_local[:version] < @repos_remote[:version] # && !force
      @logger.warn "WARNING, version on server is NEWER, aborting!"
      raise RsyncError
    end
    @repos_local[:version] += 1
    @repos_remote[:version] = @repos_local[:version]
    @repos_remote[:pack] = @repos_local[:pack].clone
    @repos_remote[:wd] = @repos_local[:wd].clone
    save_repos(:remote)
    save_repos(:local)
    push(host)
  else
    @logger.info "No changes found!"
  end
end

#compare_set(typ, host = nil, online = true) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/six/rsync/lib.rb', line 498

def compare_set(typ, host = nil, online = true)
  #if local[typ][:md5] == remote[typ][:md5]
  #  @logger.info "#{typ} Match!"
  #else
  # @logger.info "#{typ} NOT match, updating!"

  mismatch = []
  @repos_remote[typ].each_pair do |key, value|
    next unless include_match(key, typ)
    if value == @repos_local[typ][key]
      #@logger.info "Match! #{key}"
    else
      @logger.debug "Mismatch! #{key}"
      mismatch << key
    end
  end

  hosts = h_hosts(host)

  if mismatch.size > 0
    case typ
      when :pack
        # direct unpack of gz into working folder
        done = false

        ## Pack
        if online
          hosts.each_with_index do |host, i|
            @logger.info "Trying #{i + 1}/#{config[:hosts].size}: #{host}"

            slist = nil

            # TODO: Progress bar
            arr_opts = []
            arr_opts << PARAMS
            arr_opts << @rsh if host[/^(\w)*\@/]

            if mismatch.size > (@repos_remote[typ].size / 2)
              # Process full folder
              @logger.info "Many files mismatched (#{mismatch.size}), running full update on .pack folder"
            else
              # Process only selective
              @logger.info "Fetching #{mismatch.size} files... Please wait"
              slist = File.join(TEMP_PATH, ".six-rsync_#{rand 9999}-list")
              slist.gsub!("\\", "/")
              File.open(slist, 'w') { |f| mismatch.each { |e| f.puts e } }

              arr_opts << "--files-from=#{win2cyg("\"#{slist}\"")}"
            end

            begin
              arr_opts << esc(File.join(host, '.pack/.'))
              arr_opts << esc(pack_path)
              command('', arr_opts)

              done = true
              break
            rescue => e
              @logger.debug "ERROR: #{e.class} #{e.message} #{e.backtrace.join("\n")}"
            ensure
              FileUtils.rm_f slist if slist
            end
          end
          unless done
            @logger.warn "Exhausted all mirrors, please retry!"
            raise RsyncError
          end
        end
      when :wd
        mismatch.each_with_index do |e, index|
          # TODO: Nicer progress bar...
          @logger.info "Unpacking #{index + 1}/#{mismatch.size}: #{e}"
          unpack(:path => "#{e}.gz")
        end
    end
  end

  @repos_local[typ].each_pair do |key, value|
    next unless include_match(key, typ)
    del_file(key, typ) unless config[:exclude].include?(key) || !@repos_remote[typ][key].nil?
  end

  # Calculate new sums
  @repos_local[typ] = calc_sums(typ)

  # Save current progress, incase somewhere else goes wrong.
  save_repos
end

#compare_sums(online = true, host = nil) ⇒ Object



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/six/rsync/lib.rb', line 444

def compare_sums(online = true, host = nil)
  load_repos(:local)
  done = false

  hosts = h_hosts(host)

  if online
    verbose = @verbose
    @verbose = false

    hosts.each_with_index do |host, i|
      @logger.info "Trying #{i + 1}/#{config[:hosts].size}: #{host}"

      begin
        FileUtils.cp(pack_path(".repository.yml"), rsync_path(".repository-pack.yml")) if File.exists?(pack_path(".repository.yml"))
        fetch_file(".pack/.repository.yml", host)
        load_repos(:remote)

        if @repos_local[:version] > @repos_remote[:version] # && !force
          @logger.warn "WARNING, version on server is OLDER, aborting!"
          raise RsyncError
        end
        done = true
        break
      rescue => e
        @logger.debug "#{e.class} #{e.message}: #{e.backtrace.join("\n")}"
        FileUtils.cp(rsync_path(".repository-pack.yml"), pack_path(".repository.yml")) if File.exists?(rsync_path(".repository-pack.yml"))
      ensure
        FileUtils.rm(rsync_path(".repository-pack.yml")) if File.exists?(rsync_path(".repository-pack.yml"))
      end
    end
    @verbose = verbose
  else
    load_repos(:remote)
  end

  unless done
    @logger.warn "Exhausted all mirrors, please retry!"
    raise RsyncError
  end

  if online
    @logger.info "Verifying Packed files..."
    compare_set(:pack, host)

    @logger.info "Verifying Unpacked files..."
    compare_set(:wd, host)

    # Bump version and make final save
    @repos_local[:version] = @repos_remote[:version]
    save_repos
  end
end

#convertObject



118
119
120
121
122
# File 'lib/six/rsync/lib.rb', line 118

def convert
  init({:force => true})
  handle_case
  bla(".")
end

#h_hosts(host = nil) ⇒ Object



435
436
437
438
439
440
441
442
# File 'lib/six/rsync/lib.rb', line 435

def h_hosts(host = nil)
  hosts = config[:hosts].clone
  unless host.nil?
    hosts -= [host]
    hosts = hosts.insert(0, host)
  end
  hosts
end

#handle_caseObject



124
125
126
127
# File 'lib/six/rsync/lib.rb', line 124

def handle_case
  return if CONFIG[:override_downcase]
  Six::Renamer.handle_downcase_f(@rsync_work_dir)
end

#infoObject



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/six/rsync/lib.rb', line 62

def info
  handle_config

  load_repos(:local)
  load_repos(:remote)

  @logger.info "Repository #{@rsync_dir}"
  @logger.info "Local Version #{@repos_local[:version]}"
  @logger.info "Remote Version #{@repos_remote[:version]}"
  @logger.info "Local WD File Count #{@repos_local[:wd].size}"
  @logger.info "Remote WD File Count #{@repos_remote[:wd].size}"
end

#init(opts = {}) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/six/rsync/lib.rb', line 129

def init(opts = {})
  @logger.info "Processing: #{rsync_path}"
  if File.exists? rsync_path
    @logger.error "Seems to already be an Rsync repository, Aborting!"
    raise RsyncError
  end
  unless opts[:force]
    if File.exists? @rsync_work_dir
      unless Dir[File.join(@rsync_work_dir, '*')].empty?
        @logger.error "Folder not empty, Aborting!"
        raise RsyncError
      end
    end
  end
  FileUtils.mkdir_p pack_path
  save_config(config)
  save_repos(:local)
  save_repos(:remote)
end

#push(host = nil) ⇒ Object



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/six/rsync/lib.rb', line 326

def push(host = nil)
  @logger.info "Pushing..."
  handle_config
  handle_hosts

  host = config[:hosts].sample unless host
  arr_opts = []
  arr_opts << PARAMS
  arr_opts << @rsh if host[/^(\w)*\@/]
  arr_opts << esc(pack_path('.'))
  arr_opts << esc(File.join(host, '.pack'))

  # Upload .pack changes
  command('', arr_opts)
end

#reset(opts = {}) ⇒ Object

TODO: Allow local-self healing, AND remote healing. reset and fetch?



150
151
152
153
154
155
156
157
158
# File 'lib/six/rsync/lib.rb', line 150

def reset(opts = {})
  @logger.info "Resetting!"
  if opts[:hard]
    @config = load_config
    calc
    save_repos
    compare_sums(false)
  end
end

#statusObject



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
# File 'lib/six/rsync/lib.rb', line 75

def status
  @logger.info "Showing changes on #{@rsync_work_dir}"
  handle_config

  load_repos(:local)
  load_repos(:remote)

  @logger.info "Calculating Checksums..."
  @repos_local[:wd] = calc_sums(:wd)
  # Added or Changed files
  ar = Dir[File.join(@rsync_work_dir, '/**/*')]

  change = false
  i = 0
  @repos_local[:wd].each_pair do |key, value|
    i += 1
    if value != @repos_remote[:wd][key]
      change = true
      @logger.info "Modified: #{i}/#{@repos_local[:wd].size}: #{key}"
    end
  end

  # Deleted files
  @logger.info "Checking for deleted files..."

  i = 0
  @repos_remote[:wd].each_pair do |key, value|
    i += 1
    if @repos_local[:wd][key].nil?
      @logger.info "Removed: #{key}"
    end
  end

  @repos_local[:pack].each_pair do |key, value|
    i += 1
    localkey = "#{key}"
    localkey.gsub!(/\.gz$/, "")
    if @repos_local[:wd][localkey].nil?
      @logger.info "Removed: #{key}"
    end
  end
end

#update(cmd, x_opts = [], opts = {}) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/six/rsync/lib.rb', line 370

def update(cmd, x_opts = [], opts = {})
  @logger.debug "Checking for updates..."

  handle_config
  config[:hosts] = opts[:hosts] if opts.keys.include?(:hosts)
  config[:include] = opts[:include] if opts.keys.include?(:include)
  config[:exclude] = opts[:exclude] if opts.keys.include?(:exclude)
  save_config(config)
  handle_hosts

  load_repos(:local)
  begin
    load_repos(:remote)
  rescue
    @logger.warn "WARN: .pack/.repository.yml seems corrupt, forcing full check"
    opts[:force] = true
  end

  hosts = h_hosts

  man = false
  man = true if !opts[:include].nil? && !opts[:include].empty?
  if opts[:force] && !man
    done = false
    hosts.each_with_index do |host, i|
      # FIXME: Nasty
      @logger.info "Trying #{i + 1}/#{config[:hosts].size}: #{host}"
      begin
        arr_opts = []
        arr_opts << PARAMS
        arr_opts += x_opts
        arr_opts << @rsh if host[/^(\w)*\@/]
        arr_opts << esc(File.join(host, '.pack/.'))
        arr_opts << esc(pack_path)
        command(cmd, arr_opts)
        load_repos(:remote)
        done = true
        break
      rescue => e
        @logger.debug "#{e.class}: #{e.message} #{e.backtrace.join("\n")}"
      end
    end
    #@verbose = verbose
    if done
      calc
      save_repos
      @logger.info "Verifying Unpacked files..."
      compare_set(:wd)
      # Bump version and make final save
      @repos_local[:version] = @repos_remote[:version]
      save_repos
    else
      @logger.warn "Exhausted all mirrors, please retry!"
      raise RsyncError
    end
  else
    #reset(:hard => true)
    calc
    save_repos

    # fetch latest sums and only update when changed
    compare_sums(true)
  end
end