Class: Drebs::Main

Inherits:
Object
  • Object
show all
Defined in:
lib/drebs/main.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Main

Returns a new instance of Main.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/drebs/main.rb', line 7

def initialize(params)
  unless @config = params['config'].clone()
    raise "No config_file_path passed!" 
  end
  unless @db = params['db']
    raise "No db passed!" 
  end
  update_strategies(@config.delete("strategies"))
  @cloud = Drebs::Cloud.new(@config)
  @log = Logger.new(@config["log_path"])
  @log.level = Logger::WARN
end

Instance Attribute Details

#cloudObject (readonly)

Returns the value of attribute cloud.



4
5
6
# File 'lib/drebs/main.rb', line 4

def cloud
  @cloud
end

#configObject (readonly)

Returns the value of attribute config.



3
4
5
# File 'lib/drebs/main.rb', line 3

def config
  @config
end

#dbObject (readonly)

Returns the value of attribute db.



5
6
7
# File 'lib/drebs/main.rb', line 5

def db
  @db
end

Class Method Details

.check_config(reference_config, other_config) ⇒ Object



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

def Main.check_config(reference_config, other_config)
  reference_config = reference_config.clone()
  reference_strategy = reference_config.delete('strategies').last
  
  errors = []
  
  config_ok = reference_config.keys.each do |key|
    config_ok = other_config.has_key?(key) and other_config[key] != nil and other_config[key] != ""
    errors.push("Missing key/value for key: #{key}") unless config_ok
  end
  
  strategies = other_config['strategies']
  if strategies.is_a?(Array) and strategies.first()
    strategies.each_with_index do |strategy, i|
      strategies_ok = reference_strategy.keys.all?{|key|
        unless strategy.has_key?(key) and strategy[key] != nil and strategy[key] != ""
          errors.push("Missing key/value for key: #{key}") unless config_ok
        end
      }
    end
  else
    errors.push("Missing strategies array")
  end
  
  return errors
end

Instance Method Details

#check_cloudObject



20
21
22
# File 'lib/drebs/main.rb', line 20

def check_cloud
  @cloud.check_cloud()
end

#executeObject



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
# File 'lib/drebs/main.rb', line 133

def execute
  active_strategies = @db[:strategies].filter({:status=>"active"})
  
  #Decrement time_til_next_run, save
  active_strategies.each do |s|
    @db[:strategies].filter(:config=>s[:config]).update(
      :time_til_next_run => (s[:time_til_next_run].to_i - 1)
    )
  end
  
  active_strategies = @db[:strategies].filter({:status=>"active"})

  #backup_now = strategies where time_til_next_run <= 0
  backup_now = active_strategies.to_a.select{|s| s[:time_til_next_run].to_i <= 0}
  
  #loop over strategies grouped by mount_point
  backup_now.group_by{|s| s[:mount_point]}.each do |mount_point, strategies|
    pre_snapshot_tasks = strategies.map{|s| s[:pre_snapshot_tasks].split(",")}.flatten.uniq
    post_snapshot_tasks = strategies.map{|s| s[:pre_snapshot_tasks].split(",")}.flatten.uniq
  
    @log.info("creating snapshot of #{mount_point}")
    begin
      snapshot = @cloud.create_local_snapshot(pre_snapshot_tasks, post_snapshot_tasks, mount_point)
  
      strategies.collect {|s|
        snapshots = s[:snapshots].split(",")
        snapshots.select!{|snapshot| @cloud.local_ebs_ids.include? snapshot.split(":")[1]}
        snapshots.push(
          s[:status]=='active' ?
            "#{snapshot[:aws_id]}:#{snapshot[:aws_volume_id]}" : nil
        )
        @db[:strategies].filter(:config=>s[:config]).update(
          :snapshots => snapshots.join(","),
          :time_til_next_run => s[:time_between_runs]
        )
      }

    rescue Exception => error
      @log.error("Exception occured during backup: #{error.message}\n#{error.backtrace.join("\n")}")
      send_email("DREBS Error!", "AWS Instance: #{@cloud.find_local_instance[:aws_instance_id]}\n#{error.message}\n#{error.backtrace.join("\n")}")
    end
  end

  prune_backups(@db[:strategies])
end

#prune_backups(strategies) ⇒ Object



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
# File 'lib/drebs/main.rb', line 94

def prune_backups(strategies)
  to_prune = []

  strategies.each do |strategy|
    snapshots = strategy[:snapshots].split(",")
    if snapshots.uniq==[nil]
      @db[:strategies].filter(:config=>strategy[:config]).update(:snapshots => "")
    elsif snapshots == []
    elsif snapshots.count > strategy[:num_to_keep].to_i
      # only remove it from EC2 if there are no other strategies with this snapshot
      to_prune.push(Map.for({
        :snapshot => snapshots.first,
        :strategy => strategy
      }))
    end
  end

  to_prune.each do |prune_obj|
    snapshot = prune_obj.snapshot
    strategy = prune_obj.strategy

    # make sure that no other strategies have this snapshot
    strategies_with_snapshot = @db[:strategies].all.select{|strategy| strategy[:snapshots].split(',').include?(snapshot)}

    if strategies_with_snapshot.count == 1
      begin
        @cloud.ec2.delete_snapshot(snapshot.split(":")[0])
      rescue RightAws::AwsError => e
        type = e.errors.first.first rescue ''
        raise unless type == "InvalidSnapshot.NotFound"
      end
    end

    # update the strategy's snapshots to include all except given snapshot
    new_snapshots = strategy[:snapshots].split(',').delete_if{|snap| snap == snapshot}.join(',')
    @db[:strategies].filter(:config=>strategy[:config]).update(:snapshots => new_snapshots)
  end
end

#send_email(subject, body) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/drebs/main.rb', line 79

def send_email(subject, body)
  host = @config['email_host']
  port = @config['email_port']
  domain = @config['email_domain']
  username = @config['email_user']
  password = @config['email_password']
  
  msg = "Subject: #{subject}\n\n#{body}"
  smtp = Net::SMTP.new(host, port)
  smtp.enable_starttls
  smtp.start(domain, username, password, :login) {|smtp|
    smtp.send_message(msg, username, @config['email_on_exception'])
  }
end

#update_strategies(new_strategies) ⇒ Object



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
# File 'lib/drebs/main.rb', line 52

def update_strategies(new_strategies)
  new_strategies.each do |strategy|
    exists = @db[:strategies].filter(:config=>strategy.to_yaml).update(:status=>"active")
    if exists==0
      pre_snapshot_tasks = strategy['pre_snapshot_tasks']
      pre_snapshot_tasks = pre_snapshot_tasks ? pre_snapshot_tasks.join(",") : ""
      post_snapshot_tasks = strategy['post_snapshot_tasks']
      post_snapshot_tasks = post_snapshot_tasks ? post_snapshot_tasks.join(",") : ""
      @db[:strategies].insert(
        :config=>strategy.to_yaml,
        :snapshots=>"",
        :status=>"active",
        :time_til_next_run => strategy['hours_between'],
        :time_between_runs => strategy['hours_between'],
        :num_to_keep => strategy['num_to_keep'],
        :pre_snapshot_tasks => pre_snapshot_tasks,
        :post_snapshot_tasks => post_snapshot_tasks,
        :mount_point => strategy['mount_point']
      )
    end
  end
  deactivate_filter = new_strategies.map do |strategy|
    "(config != '#{strategy.to_yaml}' and status == 'active')"
  end.join(" and ")
  @db[:strategies].filter(deactivate_filter).update(:status => 'inactive')
end