Remove Unecessary Files.

Minor cleanups.
This commit is contained in:
Chirag Jog 2012-02-18 12:03:14 -08:00
parent 885c9f64a5
commit 28cadfcd58
7 changed files with 541 additions and 741 deletions

View File

@ -1,632 +0,0 @@
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2012 Citrix. All rights reserved.
#
""" Base class for all Cloudstack resources
-Virtual machine, Volume, Snapshot etc
"""
from utils import is_server_ssh_ready, random_gen
from cloudstackAPI import *
#Import System modules
import time
import hashlib
class Account:
""" Account Life Cycle """
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, admin=False):
cmd = createAccount.createAccountCmd()
#0 - User, 1 - Root Admin
cmd.accounttype = int(admin)
cmd.email = services["email"]
cmd.firstname = services["firstname"]
cmd.lastname = services["lastname"]
# Password Encoding
mdf = hashlib.md5()
mdf.update(services["password"])
cmd.password = mdf.hexdigest()
cmd.username = "-".join([services["username"], random_gen()])
account = apiclient.createAccount(cmd)
return Account(account.__dict__)
def delete(self, apiclient):
cmd = deleteAccount.deleteAccountCmd()
cmd.id = self.account.id
apiclient.deleteAccount(cmd)
class VirtualMachine:
"""Manage virtual machine lifecycle"""
def __init__(self, items, services):
self.__dict__.update(items)
self.username = services["username"]
self.password = services["password"]
self.ssh_port = services["ssh_port"]
self.ssh_client = None
#extract out the ipaddress
self.ipaddress = self.nic[0].ipaddress
@classmethod
def create(cls, apiclient, services, templateid=None, accountid=None,
networkids=None, serviceofferingid=None):
cmd = deployVirtualMachine.deployVirtualMachineCmd()
if serviceofferingid:
cmd.serviceofferingid = serviceofferingid
elif "serviceoffering" in services:
cmd.serviceofferingid = services["serviceoffering"]
cmd.zoneid = services["zoneid"]
cmd.hypervisor = services["hypervisor"]
if accountid:
cmd.account = accountid
elif "account" in services:
cmd.account = services["account"]
cmd.domainid = services["domainid"]
# List Networks for that user
command = listNetworks.listNetworksCmd()
command.zoneid = services["zoneid"]
command.account = accountid or services["account"]
command.domainid = services["domainid"]
network = apiclient.listNetworks(command)
if networkids:
cmd.networkids = networkids
elif "networkids" in services:
cmd.networkids = services["networkids"]
elif network: #If user already has source NAT created, then use that
if hasattr(network[0], "account"):
cmd.networkids = network[0].id
if templateid:
cmd.templateid = templateid
elif "template" in services:
cmd.templateid = services["template"]
if "diskoffering" in services:
cmd.diskofferingid = services["diskoffering"]
return VirtualMachine(
apiclient.deployVirtualMachine(cmd).__dict__,
services
)
def get_ssh_client(self, ipaddress=None, reconnect=False):
if ipaddress != None:
self.ipaddress = ipaddress
if reconnect:
self.ssh_client = is_server_ssh_ready(
self.ipaddress,
self.ssh_port,
self.username,
self.password
)
self.ssh_client = self.ssh_client or is_server_ssh_ready(
self.ipaddress,
self.ssh_port,
self.username,
self.password
)
return self.ssh_client
def delete(self, apiclient):
cmd = destroyVirtualMachine.destroyVirtualMachineCmd()
cmd.id = self.id
apiclient.destroyVirtualMachine(cmd)
def attach_volume(self, apiclient, volume):
cmd = attachVolume.attachVolumeCmd()
cmd.id = volume.id
cmd.virtualmachineid = self.id
return apiclient.attachVolume(cmd)
def detach_volume(self, apiclient, volume):
cmd = detachVolume.detachVolumeCmd()
cmd.id = volume.id
return apiclient.detachVolume(cmd)
class Volume:
"""Manage Volume Lifecycle
"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, zoneid=None, account=None,
diskofferingid=None):
cmd = createVolume.createVolumeCmd()
cmd.name = services["diskname"]
cmd.domainid = services["domainid"]
if diskofferingid:
cmd.diskofferingid = diskofferingid
elif "diskofferingid" in services:
cmd.diskofferingid = services["diskofferingid"]
if zoneid:
cmd.zoneid = zoneid
elif "zoneid" in services:
cmd.zoneid = services["zoneid"]
if account:
cmd.account = account
elif "account" in services:
cmd.account = services["account"]
return Volume(apiclient.createVolume(cmd).__dict__)
@classmethod
def create_custom_disk(cls, apiclient, services):
cmd = createVolume.createVolumeCmd()
cmd.name = services["diskname"]
cmd.diskofferingid = services["customdiskofferingid"]
cmd.size = services["customdisksize"]
cmd.zoneid = services["zoneid"]
cmd.account = services["account"]
cmd.domainid = services["domainid"]
return Volume(apiclient.createVolume(cmd).__dict__)
@classmethod
def create_from_snapshot(cls, apiclient, snapshot_id, services):
cmd = createVolume.createVolumeCmd()
cmd.name = "-".join([services["diskname"], random_gen()])
cmd.snapshotid = snapshot_id
cmd.zoneid = services["zoneid"]
cmd.size = services["size"]
cmd.account = services["account"]
cmd.domainid = services["domainid"]
return Volume(apiclient.createVolume(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteVolume.deleteVolumeCmd()
cmd.id = self.id
apiclient.deleteVolume(cmd)
class Snapshot:
"""Manage Snapshot Lifecycle
"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, volume_id):
cmd = createSnapshot.createSnapshotCmd()
cmd.volumeid = volume_id
return Snapshot(apiclient.createSnapshot(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteSnapshot.deleteSnapshotCmd()
cmd.id = self.id
apiclient.deleteSnapshot(cmd)
class Template:
"""Manage template life cycle"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, volume, services):
#Create template from Virtual machine and Volume ID
cmd = createTemplate.createTemplateCmd()
cmd.displaytext = services["displaytext"]
cmd.name = "-".join([services["name"], random_gen()])
cmd.ostypeid = services["ostypeid"]
if "isfeatured" in services:
cmd.isfeatured = services["isfeatured"]
else:
cmd.isfeatured = False
if "ispublic" in services:
cmd.ispublic = services["ispublic"]
else:
cmd.ispublic = False
if "isextractable" in services:
cmd.isextractable = services["isextractable"]
else:
cmd.isextractable = False
cmd.volumeid = volume.id
return Template(apiclient.createTemplate(cmd).__dict__)
@classmethod
def create_from_snapshot(cls, apiclient, snapshot, services):
#Create template from Virtual machine and Snapshot ID
cmd = createTemplate.createTemplateCmd()
cmd.displaytext = services["displaytext"]
cmd.name = services["name"]
cmd.ostypeid = services["ostypeid"]
cmd.snapshotid = snapshot.id
return Template(apiclient.createTemplate(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteTemplate.deleteTemplateCmd()
cmd.id = self.id
apiclient.deleteTemplate(cmd)
class Iso:
"""Manage ISO life cycle"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
#Create ISO from URL
cmd = registerIso.registerIsoCmd()
cmd.displaytext = services["displaytext"]
cmd.name = services["name"]
cmd.ostypeid = services["ostypeid"]
cmd.url = services["url"]
cmd.zoneid = services["zoneid"]
if "isextractable" in services:
cmd.isextractable = services["isextractable"]
if "isfeatured" in services:
cmd.isfeatured = services["isfeatured"]
if "ispublic" in services:
cmd.ispublic = services["ispublic"]
return Iso(apiclient.registerIso(cmd)[0].__dict__)
def delete(self, apiclient):
cmd = deleteIso.deleteIsoCmd()
cmd.id = self.id
apiclient.deleteIso(cmd)
return
def download(self, apiclient):
#Ensuring ISO is successfully downloaded
while True:
time.sleep(120)
cmd = listIsos.listIsosCmd()
cmd.id = self.id
response = apiclient.listIsos(cmd)[0]
# Check whether download is in progress (for Ex: 10% Downloaded)
# or ISO is 'Successfully Installed'
if response.status == 'Successfully Installed':
return
elif 'Downloaded' not in response.status.split():
raise Exception
return
class PublicIPAddress:
"""Manage Public IP Addresses"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, accountid, zoneid=None, domainid=None,
services=None, networkid=None):
cmd = associateIpAddress.associateIpAddressCmd()
cmd.account = accountid
cmd.zoneid = zoneid or services["zoneid"]
cmd.domainid = domainid or services["domainid"]
if networkid:
cmd.networkid = networkid
return PublicIPAddress(apiclient.associateIpAddress(cmd).__dict__)
def delete(self, apiclient):
cmd = disassociateIpAddress.disassociateIpAddressCmd()
cmd.id = self.ipaddress.id
apiclient.disassociateIpAddress(cmd)
return
class NATRule:
"""Manage NAT rule"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, virtual_machine, services, ipaddressid=None):
cmd = createPortForwardingRule.createPortForwardingRuleCmd()
if ipaddressid:
cmd.ipaddressid = ipaddressid
elif "ipaddressid" in services:
cmd.ipaddressid = services["ipaddressid"]
cmd.privateport = services["privateport"]
cmd.publicport = services["publicport"]
cmd.protocol = services["protocol"]
cmd.virtualmachineid = virtual_machine.id
return NATRule(apiclient.createPortForwardingRule(cmd).__dict__)
def delete(self, apiclient):
cmd = deletePortForwardingRule.deletePortForwardingRuleCmd()
cmd.id = self.id
apiclient.deletePortForwardingRule(cmd)
return
class ServiceOffering:
"""Manage service offerings cycle"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
cmd = createServiceOffering.createServiceOfferingCmd()
cmd.cpunumber = services["cpunumber"]
cmd.cpuspeed = services["cpuspeed"]
cmd.displaytext = services["displaytext"]
cmd.memory = services["memory"]
cmd.name = services["name"]
return ServiceOffering(apiclient.createServiceOffering(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteServiceOffering.deleteServiceOfferingCmd()
cmd.id = self.id
apiclient.deleteServiceOffering(cmd)
return
class DiskOffering:
"""Manage disk offerings cycle"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, custom=False):
cmd = createDiskOffering.createDiskOfferingCmd()
cmd.displaytext = services["displaytext"]
cmd.name = services["name"]
if custom:
cmd.customized = True
else:
cmd.disksize = services["disksize"]
return DiskOffering(apiclient.createDiskOffering(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteDiskOffering.deleteDiskOfferingCmd()
cmd.id = self.id
apiclient.deleteDiskOffering(cmd)
return
class SnapshotPolicy:
"""Manage snapshot policies"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, volumeid, services):
cmd = createSnapshotPolicy.createSnapshotPolicyCmd()
cmd.intervaltype = services["intervaltype"]
cmd.maxsnaps = services["maxsnaps"]
cmd.schedule = services["schedule"]
cmd.timezone = services["timezone"]
cmd.volumeid = volumeid
return SnapshotPolicy(apiclient.createSnapshotPolicy(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteSnapshotPolicies.deleteSnapshotPoliciesCmd()
cmd.id = self.id
apiclient.deleteSnapshotPolicies(cmd)
return
class LoadBalancerRule:
"""Manage Load Balancer rule"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, ipaddressid, accountid=None):
cmd = createLoadBalancerRule.createLoadBalancerRuleCmd()
cmd.publicipid = ipaddressid or services["ipaddressid"]
cmd.account = accountid or services["account"]
cmd.name = services["name"]
cmd.algorithm = services["alg"]
cmd.privateport = services["privateport"]
cmd.publicport = services["publicport"]
return LoadBalancerRule(apiclient.createLoadBalancerRule(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteLoadBalancerRule.deleteLoadBalancerRuleCmd()
cmd.id = self.id
apiclient.deleteLoadBalancerRule(cmd)
return
def assign(self, apiclient, vms):
cmd = assignToLoadBalancerRule.assignToLoadBalancerRuleCmd()
cmd.id = self.id
cmd.virtualmachineids = [str(vm.id) for vm in vms]
apiclient.assignToLoadBalancerRule(cmd)
return
def remove(self, apiclient, vms):
cmd = removeFromLoadBalancerRule.removeFromLoadBalancerRuleCmd()
cmd.virtualmachineids = [vm.id for vm in vms]
self.apiclient.removeFromLoadBalancerRule(cmd)
return
class Cluster:
"""Manage Cluster life cycle"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
cmd = addCluster.addClusterCmd()
cmd.clustertype = services["clustertype"]
cmd.hypervisor = services["hypervisor"]
cmd.zoneid = services["zoneid"]
cmd.podid = services["podid"]
if "username" in services:
cmd.username = services["username"]
if "password" in services:
cmd.password = services["password"]
if "url" in services:
cmd.url = services["url"]
if "clustername" in services:
cmd.clustername = services["clustername"]
return Cluster(apiclient.addCluster(cmd)[0].__dict__)
def delete(self, apiclient):
cmd = deleteCluster.deleteClusterCmd()
cmd.id = self.id
apiclient.deleteCluster(cmd)
return
class Host:
"""Manage Host life cycle"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, cluster, services):
cmd = addHost.addHostCmd()
cmd.hypervisor = services["hypervisor"]
cmd.url = services["url"]
cmd.zoneid = services["zoneid"]
cmd.clusterid = cluster.id
cmd.podid = services["podid"]
if "clustertype" in services:
cmd.clustertype = services["clustertype"]
if "username" in services:
cmd.username = services["username"]
if "password" in services:
cmd.password = services["password"]
return Host(apiclient.addHost(cmd)[0].__dict__)
def delete(self, apiclient):
# Host must be in maintenance mode before deletion
cmd = prepareHostForMaintenance.prepareHostForMaintenanceCmd()
cmd.id = self.id
apiclient.prepareHostForMaintenance(cmd)
time.sleep(60)
cmd = deleteHost.deleteHostCmd()
cmd.id = self.id
apiclient.deleteHost(cmd)
return
class StoragePool:
"""Manage Storage pools"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
cmd = createStoragePool.createStoragePoolCmd()
cmd.name = services["name"]
cmd.podid = services["podid"]
cmd.url = services["url"]
cmd.clusterid = services["clusterid"]
cmd.zoneid = services["zoneid"]
return StoragePool(apiclient.createStoragePool(cmd).__dict__)
def delete(self, apiclient):
# Storage pool must be in maintenance mode before deletion
cmd = enableStorageMaintenance.enableStorageMaintenanceCmd()
cmd.id = self.id
apiclient.enableStorageMaintenance(cmd)
time.sleep(60)
cmd = deleteStoragePool.deleteStoragePoolCmd()
cmd.id = self.id
apiclient.deleteStoragePool(cmd)
return
class Network:
"""Manage Network pools"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, accountid=None, domainid=None):
cmd = createNetwork.createNetworkCmd()
cmd.name = services["name"]
cmd.displaytext = services["displaytext"]
cmd.networkofferingid = services["networkoffering"]
cmd.zoneid = services["zoneid"]
if accountid:
cmd.account = accountid
if domainid:
cmd.domainid = domainid
return Network(apiclient.createNetwork(cmd).__dict__)
def delete(self, apiclient):
cmd = deleteNetwork.deleteNetworkCmd()
cmd.id = self.id
apiclient.deleteNetwork(cmd)
def get_zone(apiclient):
"Returns a default zone"
cmd = listZones.listZonesCmd()
return apiclient.listZones(cmd)[0]
def get_pod(apiclient, zoneid):
"Returns a default pod for specified zone"
cmd = listPods.listPodsCmd()
cmd.zoneid = zoneid
return apiclient.listPods(cmd)[0]
def get_template(apiclient, zoneid, ostypeid=12):
"Returns a template"
cmd = listTemplates.listTemplatesCmd()
cmd.templatefilter = 'featured'
cmd.zoneid = zoneid
list_templates = apiclient.listTemplates(cmd)
for template in list_templates:
if template.ostypeid == ostypeid:
return template

View File

@ -1,6 +0,0 @@
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2012 Citrix. All rights reserved.
#
"""Test Information Services
"""

View File

@ -44,8 +44,7 @@ class Services:
"password": 'fr3sca',
"url": 'http://192.168.100.17/CloudStack-Clogeny-Pune/Pune-1',
# Format:http://vCenter Host/Datacenter/Cluster
"clustername": '192.168.100.17/CloudStack-Clogeny-Pune/Pune-1',
# Format: http://IP_Address/Datacenter/Cluster
"clustername": 'VMWare Cluster',
},
},
"hosts": {

View File

@ -51,7 +51,6 @@ class Services:
"medium": # Create a medium virtual machine instance
{
"displayname": "testserver",
"account":"admin",
"username": "root",
"password": "password",
"ssh_port": 22,

View File

@ -1,73 +0,0 @@
# -*- encoding: utf-8 -*-
#
# Copyright (c) 2012 Citrix. All rights reserved.
#
"""Utilities functions
"""
import time
import remoteSSHClient
from cloudstackAPI import *
import cloudstackConnection
#from cloudstackConnection import cloudConnection
import configGenerator
import logging
import string
import random
def random_gen(size = 6, chars = string.ascii_uppercase + string.digits):
"""Generate Random Strings of variable length"""
return ''.join(random.choice(chars) for x in range(size))
def cleanup_resources(api_client, resources):
"""Delete resources"""
for obj in resources:
obj.delete(api_client)
def is_server_ssh_ready(ipaddress, port, username, password, retries = 50):
"""Return ssh handle else wait till sshd is running"""
loop_cnt = retries
while True:
try:
ssh = remoteSSHClient.remoteSSHClient(
ipaddress,
port,
username,
password
)
except Exception as e:
if loop_cnt == 0:
raise e
loop_cnt = loop_cnt - 1
time.sleep(60)
else:
return ssh
def format_volume_to_ext3(ssh_client, device = "/dev/sda"):
"""Format attached storage to ext3 fs"""
cmds = [
"echo -e 'n\np\n1\n\n\nw' | fdisk %s" % device,
"mkfs.ext3 %s1" % device,
]
for c in cmds:
ssh_client.execute(c)
def fetch_api_client(config_file = 'datacenterCfg'):
"""Fetch the Cloudstack API Client"""
config = configGenerator.get_setup_config(config_file)
mgt = config.mgtSvr[0]
testClientLogger = logging.getLogger("testClient")
asyncTimeout = 3600
return cloudstackAPIClient.CloudStackAPIClient(
cloudstackConnection.cloudConnection(
mgt.mgtSvrIp,
mgt.port,
mgt.apiKey,
mgt.securityKey,
asyncTimeout,
testClientLogger
)
)

View File

@ -13,18 +13,65 @@ from cloudstackAPI import *
import time
import hashlib
class Domain:
""" Domain Life Cycle """
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, name=None, networkdomain=None,
parentdomainid=None):
"""Creates an domain"""
cmd = createDomain.createDomainCmd()
if name:
cmd.name = "-".join([name, random_gen()])
elif "name" in services:
cmd.name = "-".join([services["name"], random_gen()])
if networkdomain:
cmd.networkdomain = networkdomain
elif "networkdomain" in services:
cmd.networkdomain = services["networkdomain"]
if parentdomainid:
cmd.parentdomainid = parentdomainid
elif "parentdomainid" in services:
cmd.parentdomainid = services["parentdomainid"]
return Domain(apiclient.createDomain(cmd).__dict__)
def delete(self, apiclient, cleanup=None):
"""Delete an domain"""
cmd = deleteDomain.deleteDomainCmd()
cmd.id = self.id
if cleanup:
cmd.cleanup = cleanup
apiclient.deleteDomain(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists domains"""
cmd = listDomains.listDomainsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listDomains(cmd))
class Account:
""" Account Life Cycle """
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, admin=False):
cmd = createAccount.createAccountCmd()
def create(cls, apiclient, services, admin=False, domainid=None):
"""Creates an account"""
cmd = createAccount.createAccountCmd()
#0 - User, 1 - Root Admin, 2 - Domain Admin
cmd.accounttype = 2 if (admin and domainid) else int(admin)
#0 - User, 1 - Root Admin
cmd.accounttype = int(admin)
cmd.email = services["email"]
cmd.firstname = services["firstname"]
cmd.lastname = services["lastname"]
@ -34,6 +81,9 @@ class Account:
mdf.update(services["password"])
cmd.password = mdf.hexdigest()
cmd.username = "-".join([services["username"], random_gen()])
if domainid:
cmd.domainid = domainid
account = apiclient.createAccount(cmd)
return Account(account.__dict__)
@ -44,6 +94,16 @@ class Account:
cmd.id = self.account.id
apiclient.deleteAccount(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists accounts and provides detailed account information for
listed accounts"""
cmd = listAccounts.listAccountsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listAccounts(cmd))
class User:
""" User Life Cycle """
def __init__(self, items):
@ -75,6 +135,16 @@ class User:
cmd.id = self.id
apiclient.deleteUser(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists users and provides detailed account information for
listed users"""
cmd = listUsers.listUsersCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listUsers(cmd))
class VirtualMachine:
"""Manage virtual machine lifecycle"""
@ -89,8 +159,8 @@ class VirtualMachine:
@classmethod
def create(cls, apiclient, services, templateid=None, accountid=None,
networkids=None, serviceofferingid=None,
mode='basic'):
domainid=None, networkids=None, serviceofferingid=None,
mode='basic'):
"""Create the instance"""
cmd = deployVirtualMachine.deployVirtualMachineCmd()
@ -107,13 +177,16 @@ class VirtualMachine:
elif "account" in services:
cmd.account = services["account"]
cmd.domainid = services["domainid"]
if domainid:
cmd.domainid = domainid
elif "domainid" in services:
cmd.domainid = services["domainid"]
# List Networks for that user
command = listNetworks.listNetworksCmd()
command.zoneid = services["zoneid"]
command.account = accountid or services["account"]
command.domainid = services["domainid"]
command.domainid = domainid or services["domainid"]
network = apiclient.listNetworks(command)
if networkids:
@ -214,6 +287,14 @@ class VirtualMachine:
cmd.id = volume.id
return apiclient.detachVolume(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""List all VMs matching criteria"""
cmd = listVirtualMachines.listVirtualMachinesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listVirtualMachines(cmd))
class Volume:
"""Manage Volume Lifecycle
@ -222,12 +303,11 @@ class Volume:
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, zoneid=None, account=None,
def create(cls, apiclient, services, zoneid=None, account=None, domainid=None,
diskofferingid=None):
"""Create Volume"""
cmd = createVolume.createVolumeCmd()
cmd.name = services["diskname"]
cmd.domainid = services["domainid"]
if diskofferingid:
cmd.diskofferingid = diskofferingid
@ -244,6 +324,11 @@ class Volume:
elif "account" in services:
cmd.account = services["account"]
if domainid:
cmd.domainid = domainid
elif "domainid" in services:
cmd.domainid = services["domainid"]
return Volume(apiclient.createVolume(cmd).__dict__)
@classmethod
@ -276,6 +361,13 @@ class Volume:
cmd.id = self.id
apiclient.deleteVolume(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""List all volumes matching criteria"""
cmd = listVolumes.listVolumesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listVolumes(cmd))
class Snapshot:
"""Manage Snapshot Lifecycle
@ -300,6 +392,14 @@ class Snapshot:
cmd.id = self.id
apiclient.deleteSnapshot(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""List all snapshots matching criteria"""
cmd = listSnapshots.listSnapshotsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listSnapshots(cmd))
class Template:
"""Manage template life cycle"""
@ -317,25 +417,12 @@ class Template:
cmd.name = "-".join([services["name"], random_gen()])
cmd.ostypeid = services["ostypeid"]
if "isfeatured" in services:
cmd.isfeatured = services["isfeatured"]
else:
cmd.isfeatured = False
if "ispublic" in services:
cmd.ispublic = services["ispublic"]
else:
cmd.ispublic = False
if "isextractable" in services:
cmd.isextractable = services["isextractable"]
else:
cmd.isextractable = False
cmd.isfeatured = services["isfeatured"] if "isfeatured" in services else False
cmd.ispublic = services["ispublic"] if "ispublic" in services else False
cmd.isextractable = services["isextractable"] if "isextractable" in services else False
if volumeid:
cmd.volumeid = volumeid
elif "url" in services:
cmd.url = services["url"]
if account:
cmd.account = account
@ -345,6 +432,31 @@ class Template:
return Template(apiclient.createTemplate(cmd).__dict__)
@classmethod
def register(cls, apiclient, services, account=None, domainid=None):
"""Create template from Volume or URL"""
#Create template from Virtual machine and Volume ID
cmd = registerTemplate.registerTemplateCmd()
cmd.displaytext = services["displaytext"]
cmd.name = "-".join([services["name"], random_gen()])
cmd.format = services["format"]
cmd.hypervisor = services["hypervisor"]
cmd.ostypeid = services["ostypeid"]
cmd.url = services["url"]
cmd.zoneid = services["zoneid"]
cmd.isfeatured = services["isfeatured"] if "isfeatured" in services else False
cmd.ispublic = services["ispublic"] if "ispublic" in services else False
cmd.isextractable = services["isextractable"] if "isextractable" in services else False
if account:
cmd.account = account
if domainid:
cmd.domainid = domainid
return Template(apiclient.registerTemplate(cmd)[0].__dict__)
@classmethod
def create_from_snapshot(cls, apiclient, snapshot, services):
"""Create Template from snapshot"""
@ -384,6 +496,13 @@ class Template:
elif 'Downloaded' in template.status.split():
time.sleep(120)
@classmethod
def list(cls, apiclient, **kwargs):
"""List all templates matching criteria"""
cmd = listTemplates.listTemplatesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listTemplates(cmd))
class Iso:
"""Manage ISO life cycle"""
@ -439,6 +558,14 @@ class Iso:
raise Exception
return
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists all available ISO files."""
cmd = listIsos.listIsosCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listIsos(cmd))
class PublicIPAddress:
"""Manage Public IP Addresses"""
@ -457,6 +584,7 @@ class PublicIPAddress:
if networkid:
cmd.networkid = networkid
return PublicIPAddress(apiclient.associateIpAddress(cmd).__dict__)
def delete(self, apiclient):
@ -466,6 +594,13 @@ class PublicIPAddress:
apiclient.disassociateIpAddress(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""List all Public IPs matching criteria"""
cmd = listPublicIpAddresses.listPublicIpAddressesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listPublicIpAddresses(cmd))
class NATRule:
"""Manage NAT rule"""
@ -496,6 +631,13 @@ class NATRule:
apiclient.deletePortForwardingRule(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""List all NAT rules matching criteria"""
cmd = listPortForwardingRules.listPortForwardingRulesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listPortForwardingRules(cmd))
class FireWallRule:
"""Manage Firewall rule"""
@ -526,6 +668,14 @@ class FireWallRule:
apiclient.deleteFirewallRule(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""List all Firewall Rules matching criteria"""
cmd = listFirewallRules.listFirewallRulesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listFirewallRules(cmd))
class ServiceOffering:
"""Manage service offerings cycle"""
@ -534,7 +684,7 @@ class ServiceOffering:
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
def create(cls, apiclient, services, domainid=None):
"""Create Service offering"""
cmd = createServiceOffering.createServiceOfferingCmd()
cmd.cpunumber = services["cpunumber"]
@ -542,6 +692,11 @@ class ServiceOffering:
cmd.displaytext = services["displaytext"]
cmd.memory = services["memory"]
cmd.name = services["name"]
# Service Offering private to that domain
if domainid:
cmd.domainid = domainid
return ServiceOffering(apiclient.createServiceOffering(cmd).__dict__)
def delete(self, apiclient):
@ -551,6 +706,13 @@ class ServiceOffering:
apiclient.deleteServiceOffering(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists all available service offerings."""
cmd = listServiceOfferings.listServiceOfferingsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listServiceOfferings(cmd))
class DiskOffering:
"""Manage disk offerings cycle"""
@ -577,6 +739,13 @@ class DiskOffering:
apiclient.deleteDiskOffering(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists all available disk offerings."""
cmd = listDiskOfferings.listDiskOfferingsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listDiskOfferings(cmd))
class SnapshotPolicy:
"""Manage snapshot policies"""
@ -602,6 +771,14 @@ class SnapshotPolicy:
apiclient.deleteSnapshotPolicies(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists snapshot policies."""
cmd = listSnapshotPolicies.listSnapshotPoliciesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listSnapshotPolicies(cmd))
class LoadBalancerRule:
"""Manage Load Balancer rule"""
@ -645,6 +822,13 @@ class LoadBalancerRule:
apiclient.removeFromLoadBalancerRule(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""List all Load balancing rules matching criteria"""
cmd = listLoadBalancerRules.listLoadBalancerRulesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listLoadBalancerRules(cmd))
class Cluster:
"""Manage Cluster life cycle"""
@ -679,6 +863,13 @@ class Cluster:
apiclient.deleteCluster(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""List all Clusters matching criteria"""
cmd = listClusters.listClustersCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listClusters(cmd))
class Host:
"""Manage Host life cycle"""
@ -718,6 +909,13 @@ class Host:
apiclient.deleteHost(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""List all Hosts matching criteria"""
cmd = listHosts.listHostsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listHosts(cmd))
class StoragePool:
"""Manage Storage pools"""
@ -754,6 +952,14 @@ class StoragePool:
apiclient.deleteStoragePool(cmd)
return
@classmethod
def list(cls, apiclient, **kwargs):
"""List all storage pools matching criteria"""
cmd = listStoragePools.listStoragePoolsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listStoragePools(cmd))
class Network:
"""Manage Network pools"""
@ -782,6 +988,13 @@ class Network:
cmd.id = self.id
apiclient.deleteNetwork(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""List all Networks matching criteria"""
cmd = listNetworks.listNetworksCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listNetworks(cmd))
class Vpn:
"""Manage Network pools"""
@ -835,3 +1048,138 @@ class VpnUser:
cmd = removeVpnUser.removeVpnUserCmd()
cmd.username = self.username
apiclient.removeVpnUser(cmd)
class Zone:
"""Manage Zone"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services, domainid=None):
"""Create zone"""
cmd = createZone.createZoneCmd()
cmd.dns1 = services["dns1"]
cmd.internaldns1 = services["internaldns1"]
cmd.name = services["name"]
cmd.networktype = services["networktype"]
if "dns2" in services:
cmd.dns2 = services["dns2"]
if "internaldns2" in services:
cmd.internaldns2 = services["internaldns2"]
if domainid:
cmd.domainid = domainid
return Zone(apiclient.createZone(cmd).__dict__)
def delete(self, apiclient):
"""Delete Zone"""
cmd = deleteZone.deleteZoneCmd()
cmd.id = self.id
apiclient.deleteZone(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""List all Zones matching criteria"""
cmd = listZones.listZonesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listZones(cmd))
class Pod:
"""Manage Pod"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
"""Create Pod"""
cmd = createPod.createPodCmd()
cmd.gateway = services["gateway"]
cmd.netmask = services["netmask"]
cmd.name = services["name"]
cmd.startip = services["startip"]
cmd.endip = services["endip"]
cmd.zoneid = services["zoneid"]
return Pod(apiclient.createPod(cmd).__dict__)
def delete(self, apiclient):
"""Delete Pod"""
cmd = deletePod.deletePodCmd()
cmd.id = self.id
apiclient.deletePod(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"Returns a default pod for specified zone"
cmd = listPods.listPodsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return apiclient.listPods(cmd)
class PublicIp:
"""Manage VlanIpRange"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
"""Create VlanIpRange"""
cmd = createVlanIpRange.createVlanIpRangeCmd()
cmd.gateway = services["gateway"]
cmd.netmask = services["netmask"]
cmd.forvirtualnetwork = services["forvirtualnetwork"]
cmd.startip = services["startip"]
cmd.endip = services["endip"]
cmd.zoneid = services["zoneid"]
cmd.podid = services["podid"]
cmd.vlan = services["vlan"]
return PublicIp(apiclient.createVlanIpRange(cmd).__dict__)
def delete(self, apiclient):
"""Delete VlanIpRange"""
cmd = deleteVlanIpRange.deleteVlanIpRangeCmd()
cmd.id = self.id
apiclient.deleteVlanIpRange(cmd)
@classmethod
def list(cls, apiclient, **kwargs):
"""Lists all VLAN IP ranges."""
cmd = listVlanIpRanges.listVlanIpRangesCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listVlanIpRanges(cmd))
class SecondaryStorage:
"""Manage Secondary storage"""
def __init__(self, items):
self.__dict__.update(items)
@classmethod
def create(cls, apiclient, services):
"""Create Sec Storage"""
cmd = addSecondaryStorage.addSecondaryStorageCmd()
cmd.url = services["url"]
if "zoneid" in services:
cmd.zoneid = services["zoneid"]
return Pod(apiclient.addSecondaryStorage(cmd).__dict__)
def delete(self, apiclient):
"""Delete Sec. Storage"""
cmd = deleteHost.deleteHostCmd()
cmd.id = self.id
apiclient.deleteHost(cmd)

View File

@ -54,6 +54,156 @@ def get_template(apiclient, zoneid, ostypeid=12, services=None):
if template.ostypeid == ostypeid:
return template
def download_systemplates_sec_storage(server, services):
"""Download System templates on sec storage"""
# Login to management server
ssh = remoteSSHClient.remoteSSHClient(
server["ipaddress"],
server["port"],
server["username"],
server["password"]
)
print ssh
# Mount Secondary Storage on Management Server
cmds = [
"mkdir -p %s" % services["mnt_dir"],
"mount -t nfs %s:/%s %s" % (
services["sec_storage"],
services["path"],
services["mnt_dir"]
),
"%s -m %s -u %s -h %s -F" % (
services["command"],
services["mnt_dir"],
services["download_url"],
services["hypervisor"]
)
]
for c in cmds:
print c
result = ssh.execute(c)
print result
res = str(result)
# Unmount the Secondary storage
ssh.execute("umount %s" % (services["mnt_dir"]))
if res.count("Successfully installed system VM template") == 1:
return
else:
self.debug("Failed to download System Templates on Sec Storage")
return
def wait_for_ssvms(apiclient, zoneid, podid):
"""After setup wait for SSVMs to come Up"""
time.sleep(180)
timeout = 20
while True:
list_ssvm_response = list_ssvms(
apiclient,
systemvmtype='secondarystoragevm',
zoneid=zoneid,
podid=podid
)
ssvm = list_ssvm_response[0]
if ssvm.state != 'Running':
# Sleep to ensure SSVMs are Up and Running
time.sleep(120)
timeout = timeout - 1
elif ssvm.state == 'Running':
break
elif timeout == 0:
self.debug("SSVMs failed to start")
break
timeout = 20
while True:
list_ssvm_response = list_ssvms(
apiclient,
systemvmtype='consoleproxy',
zoneid=zoneid,
podid=podid
)
cpvm = list_ssvm_response[0]
if cpvm.state != 'Running':
# Sleep to ensure SSVMs are Up and Running
time.sleep(120)
timeout = timeout - 1
elif cpvm.state == 'Running':
break
elif timeout == 0:
self.debug("SSVMs failed to start")
break
return
def download_builtin_templates(apiclient, zoneid, hypervisor, host, linklocalip):
"""After setup wait till builtin templates are downloaded"""
# Change IPTABLES Rules
result = get_process_status(
host["ipaddress"],
host["port"],
host["username"],
host["password"],
linklocalip,
"iptables -P INPUT ACCEPT"
)
# Find the BUILTIN Templates for given Zone, Hypervisor
list_template_response = list_templates(
apiclient,
hypervisor=hypervisor,
zoneid=zoneid,
templatefilter='self'
)
# Ensure all BUILTIN templates are downloaded
templateid = None
for template in list_template_response:
if template.templatetype == "BUILTIN":
templateid = template.id
# Sleep to ensure that template is in downloading state after adding
# Sec storage
time.sleep(120)
while True:
template_response = list_templates(
apiclient,
id=templateid,
zoneid=zoneid,
templatefilter='self'
)
template = template_response[0]
# If template is ready,
# template.status = Download Complete
# Downloading - x% Downloaded
# Error - Any other string
if template.status == 'Download Complete' :
break
elif 'Downloaded' not in template.status.split():
raise Exception
elif 'Downloaded' in template.status.split():
time.sleep(120)
return
def update_resource_limit(apiclient, resourcetype, account=None, domainid=None,
max=None):
"""Updates the resource limit to 'max' for given account"""
cmd = updateResourceLimit.updateResourceLimitCmd()
cmd.resourcetype = resourcetype
if account:
cmd.account = account
if domainid:
cmd.domainid = domainid
if max:
cmd.max = max
apiclient.updateResourceLimit(cmd)
return
def list_routers(apiclient, **kwargs):
"""List all Routers matching criteria"""
@ -180,6 +330,13 @@ def list_templates(apiclient, **kwargs):
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listTemplates(cmd))
def list_domains(apiclient, **kwargs):
"""Lists domains"""
cmd = listDomains.listDomainsCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listDomains(cmd))
def list_accounts(apiclient, **kwargs):
"""Lists accounts and provides detailed account information for
listed accounts"""
@ -188,6 +345,14 @@ def list_accounts(apiclient, **kwargs):
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listAccounts(cmd))
def list_users(apiclient, **kwargs):
"""Lists users and provides detailed account information for
listed users"""
cmd = listUsers.listUsersCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return(apiclient.listUsers(cmd))
def list_snapshot_policy(apiclient, **kwargs):
"""Lists snapshot policies."""