Vagrantfile 14.5 KB
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 360 361 362 363 364 365 366 367 368 369 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 434 435 436 437 438 439 440 441 442 443 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
Vagrant.require_version '>= 1.6.0'

require 'yaml'
require 'tempfile'
require 'socket'

$blackfish_community_ami = "ami-a2abc0d1" #v0.1.4-3
$certs_path = ENV['BLACKFISH_CERTS_DIR'] || "#{ENV['HOME']}/.blackfish"
$nodes_yaml_path = ENV["BLACKFISH_NODES_YML"] || "./nodes.yml"

def compute_node_fields(spec)
  spec['nodes'].each_with_index{ |node,i|
    id = node['id'] || i
    node['name'] = "#{spec['stack']}_#{spec['dc']}_#{spec['id']}-#{id}"
    if not node.key?('control-cert')
      node['control-cert'] = "#{$certs_path}/#{spec['stack']}/#{spec['dc']}/#{node['name']}-control.pem"
      node['control-cert-key'] = "#{$certs_path}/#{spec['stack']}/#{spec['dc']}/#{node['name']}-control-key.pem"
    elsif not File.file? node['control-cert']
      puts "File #{node['control-cert']} not found."
      exit 1
    end

    if not node.key?('node-cert')
      node['node-cert'] = "#{$certs_path}/#{spec['stack']}/cert.pem"
      node['node-cert-key'] = "#{$certs_path}/#{spec['stack']}/key.pem"
    elsif not File.file? node['node-cert']
      puts "File #{node['node-cert']} not found."
      exit 1
    end
  }
end

def init_tls_ca_certs (spec)
  puts "generating ca cert and cert for client"
  init = system("CERTDIR=#{$certs_path}/#{spec['stack']} ./bin/init-certs #{spec['stack']} #{spec['dc']}")
  if not init
    puts "failed to init ca certificates"
    exit 1
  end
end

def init_ssh_keypair (spec)
  files = ["ssh-keypair", "ssh-keypair.pub"].map{ |c| "#{$certs_path}/#{spec['stack']}/#{c}"}
  if not files.map{ |f| File.file?(f) }.reduce{|r,c| r && c }
    puts "generating ssh keypair for client"
    init = system("KEYPAIRDIR=#{$certs_path}/#{spec['stack']} ./bin/init-ssh-keypair #{spec['stack']}")
    if not init
      puts "failed to init ssh keypair"
      exit 1
    end
  end
end

def init_tls_nodes_certs(spec)
  nodes = spec['nodes']
  puts "generating certs for nodes: #{nodes.map{ |s| s['name'] }.join(' ')}"
  nodes_args = nodes.map{ |n| "#{n['name']}:#{n['ip']}" }.join(' ')
  init_nodes = system("CACERTDIR=#{$certs_path}/#{spec['stack']} CERTDIR=#{$certs_path}/#{spec['stack']}/#{spec['dc']} ./bin/node-certs #{spec['stack']} #{spec['dc']} #{nodes_args}")
  if not init_nodes
    puts "failed to init nodes certificates"
    exit 1
  end
end

def indent_file_content_for_cloud_init (file_name)
  indent_content_for_cloud_init IO.read(file_name)
end

def indent_content_for_cloud_init (content)
  content.split("\n").collect{|line| "     #{line}"}.join("\n")
end

def cert(spec, node, type)
  if node.key? 'cert' and File.file? node['cert']
    node['cert']
  else
    "#{$certs_path}/#{spec['stack']}/#{spec['dc']}/#{node['name']}-#{type}.pem"
  end
end

def cert_key(spec, node, type)
  if node.key? 'cert-key' and File.file? node['cert-key']
    node['cert-key']
  else
    "#{$certs_path}/#{spec['stack']}/#{spec['dc']}/#{node['name']}-#{type}-key.pem"
  end
end

def cacert(spec)
  if spec.key? 'ca' and File.file? spec['ca']
    spec['ca']
  else
    "#{$certs_path}/#{spec['stack']}/ca.pem"
  end
end

def client_cert(spec)
  if spec.key? 'client-cert' and File.file? spec['client-cert']
    spec['client-cert']
  else
    "#{$certs_path}/#{spec['stack']}/cert.pem"
  end
end

def client_cert_key(spec)
  if spec.key? 'client-cert-key' and File.file? spec['client-cert-key']
    spec['client-cert-key']
  else
    "#{$certs_path}/#{spec['stack']}/key.pem"
  end
end

def user_services_cert(spec)
  if spec.key? 'user-services-cert' and File.file? spec['user-services-cert']
    spec['user-services-cert']
  else
    "#{$certs_path}/#{spec['stack']}/wildcard-user-#{spec['dc']}-services.pem"
  end
end

def user_services_cert_key(spec)
  if spec.key? 'user-services-cert-key' and File.file? spec['user-services-cert-key']
    spec['user-services-cert-key']
  else
    "#{$certs_path}/#{spec['stack']}/wildcard-user-#{spec['dc']}-services-key.pem"
  end
end

def ssh_pubkey_content(spec)
  if spec.key? 'ssh-key' and File.file? spec['ssh-key']
    IO.read(spec['ssh-key'])
  else
    IO.read("#{$certs_path}/#{spec['stack']}/ssh-keypair.pub")
  end
end

def config_virtualbox_srv(srv, spec, node)
  srv.vm.provider :virtualbox do |v|
    v.check_guest_additions = false
    v.functional_vboxsf     = false
    v.memory = node['memory']
    v.cpus   = node['cpus']
  end
  srv.vm.synced_folder ".", "/vagrant", disabled: true
  srv.vm.box = spec['box'] || "yanndegat/blackfish"
  # Don't check for box updates
  srv.vm.box_check_update = false

  # Assign an additional static private network
  srv.vm.network 'private_network', ip: node['ip']
  userdata_file = Tempfile.new(node['name'])
  userdata_file.write userdata(spec, node )
  userdata_file.close

  srv.vm.provision :file, :source => userdata_file.path(), :destination => "/tmp/vagrantfile-user-data"
  srv.vm.provision :shell, :inline => "mv /tmp/vagrantfile-user-data /var/lib/coreos-vagrant/", :privileged => true
end

def config_aws_srv(srv, spec, node)
  srv.vm.synced_folder ".", "/vagrant", disabled: true
  srv.vm.provider :aws do |aws, override|
    aws.access_key_id = spec['aws']['access-key-id']
    aws.instance_type = node['instance-type'] || spec['aws']['instance-type']
    aws.monitoring = spec['aws']['monitoring'] || false
    aws.session_token = spec['aws']['session-token']
    aws.secret_access_key = spec['aws']['secret-access-key']
    aws.security_groups = spec['aws']['security-groups']
    aws.iam_instance_profile_arn = spec['aws']['iam-instance-profile-arn']
    aws.iam_instance_profile_name = spec['aws']['iam-instance-profile-name']
    aws.tenancy = spec['aws']['tenancy'] || "default"
    aws.use_iam_profile = spec['aws']['use-iam-profile'] || false
    aws.elb = spec['aws']['elb']
    aws.ebs_optimized = spec['aws']['ebs-optimized'] || false
    aws.unregister_elb_from_az = spec['aws']['unregister-elb-from-az'] || false
    aws.terminate_on_shutdown = spec['aws']['terminate-on-shutdown'] || false
    aws.availability_zone = spec ['aws']['availability-zone']
    aws.subnet_id = spec ['aws']['subnet-id']

    aws.region = spec['aws']['region']
    aws.region_config spec['aws']['region'] do |region|
      region.ami = spec['box'] || $blackfish_community_ami
      region.keypair_name = spec['aws']['keypair-name']
    end

    aws.tags =  { 'Name' => "#{spec['stack']}-#{spec['dc']}-#{node['name']}",
                  'Stack' => spec['stack'],
                  'Datacenter' => spec['dc'],
                  'Id' => node['name'] }

    aws.user_data = userdata(spec, node)
    aws.ami = node['backup-ami-id'] || spec['box'] || $blackfish_community_ami
    aws.private_ip_address = node['ip']
    aws.elastic_ip = spec['aws']['elastic-ip'] || false
    aws.associate_public_ip = spec['aws']['associate-public-ip'] || false

    if node.key? 'docker-storage' and node['docker-storage'] == 'ebs'
      size = if node.key? 'ebs-volumesize'
               node['ebs-volumesize']
             else
               100
             end
      type = if node.key? 'ebs-volumetype'
               node['ebs-volumetype']
             else
               "standard"
             end

      snapshotid = if node.key? 'ebs-snapshotid'
                     aws.block_device_mapping = [{
                                                   'DeviceName' => '/dev/xvde',
                                                   'Ebs.VolumeSize' => size,
                                                   'Ebs.VolumeType' => type,
                                                   'Ebs.SnapshotId' => node['ebs-snapshotid']
                                                 }]
                   else
                     aws.block_device_mapping = [{
                                                   'DeviceName' => '/dev/xvde',
                                                   'Ebs.VolumeSize' => size,
                                                   'Ebs.VolumeType' => type
                                                 }]
                   end
    end

    aws.ssh_host_attribute = :private_ip_address
  end
end

def flocker_agent_conf(spec)
  if spec['volume-driver'] != 'flocker' || spec['provider'] != 'aws'
    ""
  else
    conf = <<EOF
"version": 1
"control-service":
   "hostname": "flocker.service.#{spec['stack']}"
   "port": 4524
dataset:
  backend: "aws"
  region: "#{spec['aws']['region']}"
  zone: "#{spec['aws']['availability-zone']}"
  access_key_id: "#{spec['aws']['access-key-id']}"
  secret_access_key: "#{spec['aws']['secret-access-key']}"
EOF

    userdata_part = <<EOF
  - path: "/etc/blackfish/flocker-agent.yml"
    permissions: "0600"
    owner: "root"
    content: |
#{indent_content_for_cloud_init(conf)}
EOF
    return userdata_part
  end
end

def docker_registry_conf(spec)
  conf = <<EOF
---
version: 0.1
log:
   fields:
     service: registry
http:
   addr: :5000
   headers:
     X-Content-Type-Options: [nosniff]
EOF

  if spec['provider'] == 'virtualbox'
    conf << <<EOF
storage:
   filesystem:
      rootdirectory: /var/lib/registry
      cache:
         blobdescriptor: inmemory
EOF
  elsif spec['provider'] == 'aws'
    conf << <<EOF
storage:
  s3:
      region: "#{spec['aws']['region']}"
      zone: "#{spec['aws']['availability-zone']}"
      accesskey: "#{spec['aws']['access-key-id']}"
      secretkey: "#{spec['aws']['secret-access-key']}"
      bucket: #{spec['aws']['s3bucket']}
      encrypt: true
      secure: true
      v4auth: true
      chunksize: 5242880
      rootdirectory: /docker-registry
  cache:
      blobdescriptor: inmemory
EOF
  end

  userdata_part = <<EOF
  - path: "/etc/blackfish/registry-config.yml"
    permissions: "0644"
    owner: "root"
    content: |
#{indent_content_for_cloud_init(conf)}
EOF
  return userdata_part

end

def swarm_mode(node)
  swarm_agent = if node.key? 'swarm-agent'
                  node['swarm-agent']
                else
                  true
                end

  swarm_manager = if node.key? 'swarm-manager'
                    node['swarm-manager']
                  else
                    true
                  end

  if swarm_agent && swarm_manager
    return 'both'
  elsif swarm_agent && !swarm_manager
    return 'agent'
  else
    return 'off'
  end
end

def registry_mode(node)
  if node.key? 'docker-registry'
    node['docker-registry'] ? 'server' : ''
  else
    ''
  end
end

def consul_mode(node)
  if node.key? 'consul-server'
    node['consul-server'] ? 'server' : 'agent'
  else
    'server'
  end
end

def flocker_mode(node)
  if node.key? 'flocker-control'
    node['flocker-control'] ? 'server' : 'agent'
  else
    'agent'
  end
end

def docker_labels_opts(spec, node)
  labels = "--label clusterid=#{spec['id']}"

  if node.key? 'storage'
    labels << " --label storage=#{node['storage']}"
  else
    labels << " --label storage=ephemeral"
  end

  if spec.key? 'labels' and spec['labels'].size > 0
    labels << " --label "<< spec['labels'].join(' --label ')
  end

  if node.key? 'labels' and node['labels'].size > 0
    labels << " --label " << node['labels'].join(' --label ')
  end

  return labels
end

def userdata(spec, node)

  certs = {
    "ca.pem"                  => IO.read(cacert(spec)),
    "node.pem"                => IO.read(cert(spec, node, 'control')),
    "node-key.pem"            => IO.read(cert_key(spec, node, 'control')),
    "api.pem"                 => IO.read(cert(spec, node, 'node')),
    "api-key.pem"             => IO.read(cert_key(spec, node, 'node')),
    "user-services.pem"       => IO.read(user_services_cert(spec)),
    "user-services-key.pem"   => IO.read(user_services_cert_key(spec)),
    "client.pem"              => IO.read(client_cert(spec)),
    "client-key.pem"          => IO.read(client_cert_key(spec))
  }

  certs_gzip_base64_content = Dir.mktmpdir {|dir|
    certs.each { |file,content|
      open("#{dir}/#{file}", "w") { |f| f.write content }
    }
    system("cd #{dir} && tar -czf certs.tgz *.pem")
    `cat #{dir}/certs.tgz | base64`
  }

  userdata = <<EOF
#cloud-config
hostname: #{node['name']}
ssh_authorized_keys:
  - #{ssh_pubkey_content(spec)}
write_files:
  - path: "/etc/blackfish/blackfish.conf"
    permissions: "0644"
    owner: "root"
    content: |
      JOINIPADDR=#{spec['consul-joinip']}
      JOINIPADDR_WAN=#{spec['consul-joinip-wan']}
      CLUSTER_SIZE=#{spec['nodes'].find_all{ |n| consul_mode(n) == 'server'}.size}
      CONSUL_OPTS="-ui -node=#{node['name']}"
      ADMIN_NETWORK="#{spec['admin-network']}"
      PUBLIC_NETWORK="#{spec['public-network'] || spec['admin-network'] }"
      SWARM_MODE="#{swarm_mode(node)}"
      CONSUL_MODE="#{consul_mode(node)}"
      FLOCKER_MODE="#{flocker_mode(node)}"
      VOLUME_DRIVER="#{spec['volume-driver']}"
      STACK_NAME=#{spec['stack']}
      DATACENTER=#{spec['dc']}
      INFLUXDB_URL="#{spec['influxdb-url']}"
      INFLUXDB_DB="#{spec['influxdb-db'] || spec['stack'] }"
      INFLUXDB_USER="#{spec['influxdb-user'] || 'telegraf'}"
      INFLUXDB_PASSWORD="#{spec['influxdb-password']}"
      JOURNALD_SINK="#{spec['journald-sink']}"
      REGISTRY_MODE="#{registry_mode(node)}"
      REGISTRY_HTTP_SECRET=#{spec['registry-secret']}
      CONSUL_ENCRYPT_KEY=#{spec['consul-key']}
      NTP_SERVERS=#{spec['ntp-servers']}
  - path: "/etc/blackfish/docker.conf.d/20-labels.conf"
    permissions: "0600"
    owner: "root"
    content: |
      DOCKER_OPTS="#{docker_labels_opts(spec,node)}"
#{docker_registry_conf(spec)}
#{flocker_agent_conf(spec)}
  - path: "/etc/blackfish/certs/certs.tar"
    permissions: "0600"
    owner: "root"
    encoding: "gzip+base64"
    content: |
#{indent_content_for_cloud_init(certs_gzip_base64_content)}
EOF
    return userdata
end

spec = YAML.load_file(File.join(File.dirname(__FILE__), $nodes_yaml_path ))
compute_node_fields(spec)

## Generates ssh keypair
init_ssh_keypair(spec)

## Generates TLS CA CERT and Client Cert
init_tls_ca_certs(spec)

## Generates TLS Certs for every node
init_tls_nodes_certs(spec)

# Create and configure the VMs
Vagrant.configure("2") do |config|

  # Always use Vagrant's default insecure key
  config.ssh.insert_key = false
  config.ssh.username = 'core'
  config.ssh.forward_agent = true
  config.ssh.private_key_path = if spec.key? 'private-ssh-key'
                                    spec['private-ssh-key']
                                  else
                                    "#{$certs_path}/#{spec['stack']}/ssh-keypair"
                                  end

  spec['nodes'].each do |node|
    config.vm.define "#{node['name']}" do |srv|
      case spec['provider']
      when "aws"
        config.vm.box = "dummybox"
        config_aws_srv(srv, spec, node)
      when "virtualbox"
        config_virtualbox_srv(srv, spec, node)
      else
        puts "provider #{spec['provider']} not supported."
        exit 1
      end
    end
  end
end