Class: Makitzo::Migrations::Migrator

Inherits:
Object
  • Object
show all
Includes:
ApplicationAware, Paths, SSH::Multi
Defined in:
lib/makitzo/migrations/migrator.rb

Instance Method Summary collapse

Methods included from Paths

#local_migration_path

Methods included from SSH::Multi

#multi_connect, #multi_session, #multi_ssh, #ssh_context_class

Methods included from ApplicationAware

#app, #config, #logger, #store

Constructor Details

#initialize(app) ⇒ Migrator

Returns a new instance of Migrator.



7
8
9
# File 'lib/makitzo/migrations/migrator.rb', line 7

def initialize(app)
  @app = app
end

Instance Method Details

#migrate(target_hosts) ⇒ Object



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
# File 'lib/makitzo/migrations/migrator.rb', line 11

def migrate(target_hosts)
  all_migrations = migrations
  return if all_migrations.empty?
  
  # start with a query matching all hosts and reduce to set of hosts
  # affected by existing migrations
  migration_hosts_query = World::Query.all
  all_migrations.each { |m| migration_hosts_query.merge!(m.query) }
  
  # get list of hosts and intersect with hosts specified on command-line
  migration_hosts = migration_hosts_query.exec(config)
  migration_hosts &= target_hosts
  
  # finally, remove any hosts with no pending migrations
  applied_migrations = store.applied_migrations_for_all_hosts
  migration_hosts.delete_if { |host|
    all_migrations.all? { |m|
      (applied_migrations[host.to_s] || []).include?(m.timestamp) || !m.query.includes?(host)
    }
  }
  
  multi_ssh(migration_hosts) do |host, conn, error|
    logger.with_host(host) do
      if error
        # log connection error
      else
        begin
          overseer_session = ssh_context_class.new(host, conn)
          overseer_session.makitzo_install_check!
      
          # then select the appropriate migrations, create session classes and run
          all_migrations.each do |migration_klass|
            next if (applied_migrations[host.to_s] || []).include?(migration_klass.timestamp)
            next unless migration_klass.query.includes?(host)
            migration = migration_klass.new(host, conn)
            migration.exec!("mkdir -p #{migration.x(migration.remote_directory)}")
            migration.up
            host.mark_migration_as_applied(migration)
            logger.success "Migration #{migration_klass.timestamp} applied"
          end
        rescue SSH::CommandFailed => e
          logger.error "Migration failed"
        end
      end
    end
  end
end