Class: Mongolly::Shepherd

Inherits:
Object
  • Object
show all
Defined in:
lib/mongolly/shepherd.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Shepherd

Returns a new instance of Shepherd.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/mongolly/shepherd.rb', line 3

def initialize(options = {})
  @options           = options
  @access_key_id     = options[:access_key_id]
  @secret_access_key = options[:secret_access_key]
  @region            = options[:region] || "us-east-1"
  @database          = options[:database]
  @db_username       = options[:db_username]
  @db_password       = options[:db_password]
  @dry_run           = options[:dry_run]
  @op_timeout        = options[:op_timeout] || 120
  @logger            = options[:logger] || Logger.new(STDOUT)
  @logger.level = case options[:log_level].strip
                  when "fatal"; then Logger::FATAL
                  when "error"; then Logger::ERROR
                  when "warn"; then Logger::WARN
                  when "debug"; then Logger::DEBUG
                  else Logger::INFO
                  end
end

Instance Method Details

#backupObject



23
24
25
26
27
# File 'lib/mongolly/shepherd.rb', line 23

def backup
  @logger.info "Starting backup..."
  connection.snapshot_ebs({ logger: @logger }.merge(@options))
  @logger.info "Backup complete."
end

#cleanup(age) ⇒ Object

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mongolly/shepherd.rb', line 29

def cleanup(age)
  @logger.info "Starting cleanup..."
  raise ArgumentError, "Must provide a Time object to cleanup" unless age.class <= Time

  ec2 = AWS::EC2.new(access_key_id: @access_key_id,
                     secret_access_key: @secret_access_key,
                     region: @region)

  @logger.debug "deleting snapshots older than #{age}}"
  ec2.snapshots.with_owner(:self).each do |snapshot|
    next if snapshot.tags[:created_at].nil? || snapshot.tags[:backup_key].nil?
    if Time.parse(snapshot.tags[:created_at]).utc < age
      @logger.debug "deleting snapshot #{snapshot.id} tagged #{snapshot.tags[:backup_key]} created at #{snapshot.tags[:created_at]}, earlier than #{age}"
      snapshot.delete unless @dry_run
    end
  end
  @logger.info "Cleanup complete."
end

#connectionObject



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/mongolly/shepherd.rb', line 48

def connection
  db = if @database.is_a? Array
         @logger.debug "connecting to a replica set #{@database}"
         Mongo::MongoReplicaSetClient.new(@database, op_timeout: @op_timeout.to_i)
       else
         @logger.debug "connecting to a single instance #{@database}"
         Mongo::MongoClient.new(*@database.split(":"), op_timeout: @op_timeout.to_i)
       end
  if @db_username && @db_password
    db["admin"].authenticate(@db_username, @db_password)
  end
  db
end