def handle(self, job_id, **options):
        job = Job.objects.get(id=job_id)
        if not job.physical:
            return ''
        config = Configuration.get()
        job.redirect_output()

        preseed_path = os.path.join(os.getcwd(), 'preseeds', 'build-node.preseed')

        with open(preseed_path, 'w') as fp:
            fp.write(render_to_string('build-node.preseed.tmpl',
                                      {'config': config}))

        try:
            run_cmd(['sudo', 'cobbler', 'system', 'remove', '--name=%s' % (job.build_node().name,)])
        except:
            pass
        run_cmd(['sudo', 'cobbler', 'system', 'add',
                                '--name=%s' % (job.build_node().name,),
                                '--mac-address=%s' % (job.build_node().mac,),
                                '--profile=%s-x86_64' % (job.description['ubuntu_series'],),
                                '--ip-address=%s' % (job.build_node().ip,),
                                '--dns-name=%s' % (job.build_node().fqdn(),),
                                '--hostname=%s' % (job.build_node().fqdn(),),
                                '--kickstart=%s' % (preseed_path,),
                                '--kopts="log_host=%s '
                                         'log_port=%d '
                                         'netcfg/disable_autoconfig=true '
                                         'netcfg/dhcp_failed=true '
                                         "netcfg/dhcp_options='Configure network manually' "
                                         'netcfg/get_nameservers=%s '
                                         'netcfg/get_ipaddress=%s '
                                         'netcfg/get_netmask=%s '
                                         'netcfg/get_gateway=%s '
                                         'netcfg/confirm_static=true '
                                         'clock-setup/ntp-server=%s '
                                         'partman-auto/disk=%s"' % (utils.src_ip(job.build_node().ip),
                                                                    job.log_listener_port,
                                                                    config.name_server(),
                                                                    job.build_node().ip,
                                                                    config.netmask,
                                                                    config.gateway,
                                                                    config.ntp_server(),
                                                                    job.build_node().hardware_profile.description['boot_disk']),
                                '--power-user=%s' % (job.build_node().power_user,),
                                '--power-address=%s' % (job.build_node().power_address,),
                                '--power-pass=%s' % (job.build_node().power_password,),
                                '--power-id=%s' % (job.build_node().power_id,),
                                '--power-type=%s' % (job.build_node().power_type,),])

        run_cmd(['sudo', 'cobbler', 'system', 'edit', '--name=%s' % (job.build_node().name,), '--netboot-enabled=true'])
        run_cmd(['sudo', 'cobbler', 'sync'])
        run_cmd(['sudo', 'cobbler', 'system', 'poweroff', '--name=%s' % (job.build_node().name,)])
        sleep(5)
        run_cmd(['sudo', 'cobbler', 'system', 'poweron', '--name=%s' % (job.build_node().name,)])
    def handle(self, job_id, **options):
        job = Job.objects.get(id=job_id)
        if not job.physical:
            return ''
        config = Configuration.get()
        job.redirect_output()

        fabric_env.host_string = '%s@%s' % (config.admin_user, job.build_node().ip)
        fabric_env.password = config.admin_password
        fabric_env.abort_on_prompts = True
        fabric_env.sudo_prefix = 'sudo -H -S -p \'%(sudo_prompt)s\' '
        
        nodes = job.non_build_nodes()

        for node in nodes:
            sudo('timeout 10 cobbler system poweroff --name=%s' % (node,))
    def handle(self, job_id, **options):
        print "a"
        job = Job.objects.get(id=job_id)
        print "b"
        if not job.physical:
            print "c"
            timeout = time() + 300
            print "d"
            while timeout > time():
                print "e"
                if job.cloud_slave_reservation.update_state() == job.cloud_slave_reservation.READY:
                    return ""
                print "f"
                sleep(5)
                print "g"
            print "h"
            return "Did not work"
        print "i"
        config = Configuration.get()
        job.redirect_output()

        def wait_for_ubuntu_install_to_finish():
            timeout = time() + 60 * 25
            while time() < timeout:
                output = run_cmd(["sudo", "cobbler", "system", "dumpvars", "--name=%s" % (job.build_node().name,)])
                for l in output.split("\n"):
                    if l.startswith("netboot_enabled") and l.endswith("False"):
                        return True
                print "Not done yet. %s seconds left." % (timeout - time(),)
                self.stdout.flush()
                sleep(5)
            return False

        def wait_for_ssh_to_become_available():
            timeout = time() + 60 * 25
            while time() < timeout:
                try:
                    run("true")
                    return True
                except NetworkError, e:
                    print e
                    self.stdout.flush()
                sleep(5)
            return False
    def handle(self, job_id, **options):
        job = Job.objects.get(id=job_id)
        config = Configuration.get()
        job.redirect_output()

        print 'General config: '
        print 'Subnet      :', config.subnet
        print 'Netmask     :', config.netmask
        print 'Domain      :', config.domain
        print 'Gateway     :', config.gateway
        print 'NTP servers :', config.ntp_servers
        print 'Name servers:', config.nameservers
        print 'Proxy       :', config.proxy
        print 'Admin user  :'******'Admin passwd:', config.admin_password
        print
        print 'Job details:'
        print 'Ubuntu version:', job.description['ubuntu_series']
        if 'manifest' in job.description:
            print 'Manifest    :'
            print '  Repository:', job.description['manifest']['git']['repository']
            print '  Branch    :', job.description['manifest']['git']['branch']
            print '  Subdir    :', job.description['manifest']['git'].get('subdir', '.')
        print 'Users and tenants:'
        for tenant in job.description.get('tenants', []):
            print '  Tenant:'
            print '     Name       :', tenant['name']
            print '     Description:', tenant.get('description')

        for user in job.description.get('users', []):
            print '  User:'******'     Name    :', user['name']
            print '     Password:'******'password']
            print '     E-mail  :', user.get('email')
            print '     Tenant  :', user['tenant']
            print '     Roles   :', user.get('roles', [])
        
        print 'Images:'
        for image in job.description.get('images', []):
            print '  Image:'
            print '    Name            :', image['name']
            print '    Container format:', image.get('container_format', 'bare')
            print '    Disk format     :', image.get('disk-format', 'raw')
            print '    Source          :', image['url']

        print 'Archive information:'
        for archive in job.description['archives']:
           print '  Archive:'
           print '    Name      :', archive['name']
           print '    Pocket    :', archive['pocket']
           print '    Location  :', archive['location']
           print '    Components:', ' '.join(archive['components'])
           print '    Key ID    :', archive['key_id']
           print '    Line      :', archive['line']
           print '    Proxy     :', archive['proxy']
           print '    Key data  :'
           print '\n'.join(['      %s' % l for l in archive['key_data'].split('\n')])

        print
        print "Participating nodes:"
        header()
        for node in job.nodes():
            extra_info = []
            if node == job.build_node():
                extra_info += ['build node']
            if node == job.control_node():
                extra_info += ['controller node']
            describe_node(node, ', '.join(extra_info))
    def handle(self, job_id, **options):
        job = Job.objects.get(id=job_id)
        config = Configuration.get()
        job.redirect_output()

        job._configure_fabric_for_control_node()
 
        # This is crude and horrible
        admin_user = job.description['users'][0]
        non_priv_user1 = job.description['users'][1]
        non_priv_user2 = job.description['users'][2]
        tempest_default_overrides['ALL'] = {'username' : non_priv_user1['name'],
                                            'tenant_name': non_priv_user1['tenant'],
                                            'password': non_priv_user1['password'],
                                            'alt_username' : non_priv_user2['name'],
                                            'alt_tenant_name': non_priv_user2['tenant'],
                                            'alt_password': non_priv_user2['password']}
        tempest_default_overrides['identity-admin'] = {'username' : admin_user['name'],
                                                      'tenant_name': admin_user['tenant'],
                                                      'password': admin_user['password']}
        tempest_default_overrides['compute-admin'] = tempest_default_overrides['identity-admin']
        tempest_default_overrides['compute'] = {}
        tempest_default_overrides['compute']['create_image_enabled'] = 'false'
        tempest_default_overrides['compute']['resize_available'] = 'false'
        tempest_default_overrides['compute']['change_password_available'] = 'false'
        tempest_default_overrides['compute']['whitebox_enabled'] = 'false'
        tempest_default_overrides['network'] = {}
        tempest_default_overrides['network']['api_version'] = 'v2.0'
        
        sudo('apt-get -y install python-glanceclient')
        image_id =  run('OS_USERNAME=%s OS_PASSWORD=%s OS_TENANT_NAME=%s OS_AUTH_URL=%s glance image-list --name="%s" | tail -n 2 | head -n 1 | sed -e "s/^..//g" -e "s/ .*//g"' % (non_priv_user1['name'],
                                                                                                              non_priv_user1['password'],
                                                                                                              non_priv_user1['tenant'],
                                                                                                              'http://%s:5000/v2.0/' % (job.control_node().external_ip),
                                                                                                              job.description['images'][0]['name'])).strip()
        if not 'ALL' in tempest_default_overrides:
            tempest_default_overrides['ALL'] = {}

        tempest_default_overrides['ALL']['image_ref'] = image_id
        tempest_default_overrides['ALL']['image_ref_alt'] = image_id
        sudo('apt-get -y install git python-unittest2 python-testtools python-testresources')
        run('git clone -b stable/folsom https://github.com/CiscoSystems/tempest')
      
        conf_sample = StringIO()
        get('tempest/etc/tempest.conf.sample', conf_sample)
        
        out = ''
        for l in conf_sample.getvalue().split('\n'):
            if l.startswith('['):
                section = l[1:-1]
            elif l.strip() == '':
                pass
            elif l.startswith('#'):
                pass
            else:
                k, v = l.split('=')
                k, v = k.strip(), v.strip()
                if section in tempest_default_overrides and k in tempest_default_overrides[section]:
                    v = tempest_default_overrides[section][k]
                elif 'ALL' in tempest_default_overrides and k in tempest_default_overrides['ALL']:
                    v = tempest_default_overrides['ALL'][k]
                l = "%s = %s" % (k, v)
            out += "%s\n" % (l,)

        put(StringIO(out), 'tempest/etc/tempest.conf')
        result = run("cd tempest ; nosetests -v -a '!whitebox' tempest")
        if (result.return_code == 0):
           print "gate packages"