def TerminateServer(self):
        try:
            logging.debug('Terminating VM %s with IP %s' % (self.vmDbId, self.serverIp,))
            vm = utils.nova_client().servers.find(id=self.serverId)
            vm.delete()
        except:
            logging.error('Error while terminating VM %s with IP %s: %s' % (self.vmDbId, self.serverIp, traceback.format_exc()))
            print 'Error while terminating VM %s with IP %s' % (self.vmDbId, self.serverIp,)
            return False

        try:
            logging.debug('Removing VM %s from the database' % (self.vmDbId,))
            cvlsql.delete_vm(self.serverIp)
        except:
            logging.error('Error while removing VM %s from the database: %s' % (self.serverIp, traceback.format_exc()))
            print 'Error while removing VM %s from the database' % (self.serverIp,)

        print 'Terminated VM %s' % (self.serverIp,)
        return True
from utils import nova_client, get_vm_info
from cvlsql import Cvl_cvl_vm

nc = nova_client()

db_vms   = list(Cvl_cvl_vm.select())
nova_vms = nc.servers.list()

db_ips   = [x.vmIp for x in db_vms]
nova_ips = [get_vm_info(x.name)['ip'] for x in nova_vms]

# VMs with the same name?

duplicate_db_names   = [x.vmServerName for x in db_vms    if len([y for y in db_vms   if y.vmServerName == x]) > 1]
duplicate_nova_names = [x.name         for x in nova_vms  if len([y for y in nova_vms if y.name         == x]) > 1]

if len(duplicate_db_names) > 0:
    print 'Multiple VMs exist in the database with the following names:', duplicate_db_names
if len(duplicate_nova_names) > 0:
    print 'Multiple VMs exist in Nectar with the following names:', duplicate_nova_names

# Unmanaged VMs?
unmanaged_vms = [x for x in nova_vms if get_vm_info(x.name)['ip'] not in db_ips]

if len(unmanaged_vms) > 0:
    print 'VMs in Nectar tenancy %s that are not managed by by the User Management system:' % (nc.project_id,)
    for x in unmanaged_vms:
        print get_vm_info(x.name)['ip'], x.name
    print

# Orphaned VM records?
import logging
import utils
import cvl_config

if len(sys.argv) < 2:
    logging.error("Missing argument: number of requested CPUs")
    sys.exit(1)

numberCpu = sys.argv[1]
try:
    if Environment.checkOrSet() == False:
        logging.error("Failed to set environment credential")
        sys.exit(1)
    else:
        availableCpu = utils.get_nr_available_vcpus()
        logging.debug("numberCpu index: " + str(numberCpu) + " number cpu: " + str(cvl_config.VM_CPU[int(numberCpu)]) + " available CPU: " + str(availableCpu));
        if availableCpu <= cvl_config.QUOTA_THRESHOLD:

            utils.send_email(cvl_config.CVL_HELP_EMAIL,
                             "CVL project resource warning",
                             "Warning: there are only " + str(availableCpu) + " CPUs available in the %s tenancy." % (utils.nova_client().project_id,))

        if availableCpu < cvl_config.VM_CPU[int(numberCpu)]:
            message = "Resources for " + str(cvl_config.VM_CPU[int(numberCpu)]) + " CPUs are not available"
            print message
            logging.error(message)
        print "OK"
except:
    logging.error("Exception:" + traceback.format_exc())
    sys.exit(1)
    def CreateServer(self):
        try:
            from utils import CreateCvlVm
            job = CreateCvlVm.apply_async(args=[self.serverName, self.username, self.email, self.cpu, self.userId, self.path, self.projectGroup, self.nectarId], kwargs={}, queue='usermanagement')
            logging.debug('CreateServer: celery job: ' + str(job))
            utils.send_email(cvl_config.CVL_HELP_EMAIL,
                             "CVL project: notification of VM build",
                             "Building new VM: " + str((self.serverName, self.username, self.email, self.cpu, self.userId, self.path, self.projectGroup, self.nectarId)) + ' in tenancy ' + utils.nova_client().project_id + '\ncelery job id: ' + str(job))
        except:
            logging.error('Could not create VM: %s' % (traceback.format_exc(),))
            print 'Error while creating VM "%s"' % (self.serverName,)
            return False

        print 'Creation of VM "%s" is in progress with job id %s. A status email has been sent to %s.' % (self.serverName, job, self.email,)
        return True