Exemplo n.º 1
0
 def login_to_vcloud(self):
     """Login to vCloud"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     service_type = config['vcloud']['service_type']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     instance = config['vcloud']['instance']
     self.vca = VCA(
         host=host,
         username=username,
         service_type=service_type,
         version=version,
         verify=True,
         log=True)
     assert self.vca
     if self.vca.VCA_SERVICE_TYPE_STANDALONE == service_type:
         raise Exception('not-supported')
     elif self.vca.VCA_SERVICE_TYPE_VCHS == service_type:
         raise Exception('not-supported')
     elif self.vca.VCA_SERVICE_TYPE_VCA == service_type:
         result = self.vca.login(password=password)
         assert result
         result = self.vca.login_to_instance(
             password=password, instance=instance, token=None, org_url=None)
         assert result
         result = self.vca.login_to_instance(
             password=None,
             instance=instance,
             token=self.vca.vcloud_session.token,
             org_url=self.vca.vcloud_session.org_url)
         assert result
Exemplo n.º 2
0
def login_to_vcloud(username, password, host, version, org, service_type, instance):       

        vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert vca

        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = vca.login(password=password, org=org)
            assert result, "Wrong password or Org?"
            result = vca.login(token=vca.token, org=org, org_url=vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCHS == service_type:
            result = vca.login(password=password)
            assert result, "Wrong Password?"
            result = vca.login(token=vca.token)
            assert result
            result = vca.login_to_org(instance, org)  # service now called instance
            assert result, "Wrong service/aka instance or org?"
        elif VCA.VCA_SERVICE_TYPE_VCA == service_type:
            result = vca.login(password=password)
            assert result
            result = vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
            assert result
            print "token " + vca.vcloud_session.token
            result = vca.login_to_instance(password=None, instance=instance, token=vca.vcloud_session.token, org_url=vca.vcloud_session.org_url)
            assert result

        return vca
Exemplo n.º 3
0
 def test_0023(self):
     """Identify standalone is not vCloud Air vca"""
     vca = VCA(host='https://p1v21-vcd.vchs.vmware.com',
               username='', verify=True, log=True)
     assert vca is not None
     service_type = vca.get_service_type()
     assert service_type != VCA.VCA_SERVICE_TYPE_VCA
Exemplo n.º 4
0
 def login_to_vcloud(self):
     """Login to vCloud"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     service_type = config['vcloud']['service_type']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     org = config['vcloud']['org']
     service = config['vcloud']['service']
     instance = config['vcloud']['instance']
     self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
     assert self.vca
     if vcloudair.VCA_SERVICE_TYPE_STANDALONE == service_type:
         result = self.vca.login(password=password, org=org)
         assert result
         result = self.vca.login(token=self.vca.token, org=org, org_url=self.vca.vcloud_session.org_url)
         assert result
     elif vcloudair.VCA_SERVICE_TYPE_SUBSCRIPTION == service_type:
         result = self.vca.login(password=password)
         assert result
         result = self.vca.login(token=self.vca.token)
         assert result
         result = self.vca.login_to_org(service, org)
         assert result
     elif vcloudair.VCA_SERVICE_TYPE_ONDEMAND == service_type:
         result = self.vca.login(password=password)
         assert result
         # result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
         # assert result
         # result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
         assert result
Exemplo n.º 5
0
 def test_0021(self):
     """Identify vCloud Air vca"""
     vca = VCA(host='https://iam.vchs.vmware.com',
               username='', verify=True, log=True)
     assert vca is not None
     service_type = vca.get_service_type()
     assert service_type == VCA.VCA_SERVICE_TYPE_VCA
Exemplo n.º 6
0
class TestVCASSO:


    def __init__(self):
        self.vca = None
        self.instance = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud VCA"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        self.instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type='vca', version=version, verify=True, log=True)
        assert self.vca
        result = self.vca.login(password=password)
        assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_002(self):
        """Login to instance no password"""
        result = self.vca.login_to_instance_sso(instance=self.instance)
        assert result
Exemplo n.º 7
0
class TestVCASSO:
    def __init__(self):
        self.vca = None
        self.instance = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud VCA"""
        username = config["vcloud"]["username"]
        password = config["vcloud"]["password"]
        host = config["vcloud"]["host"]
        version = config["vcloud"]["version"]
        self.instance = config["vcloud"]["instance"]
        self.vca = VCA(host=host, username=username, service_type="vca", version=version, verify=True, log=True)
        assert self.vca
        result = self.vca.login(password=password)
        assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print "logout"
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_002(self):
        """Login to instance no password"""
        result = self.vca.login_to_instance_sso(instance=self.instance)
        assert result
Exemplo n.º 8
0
class TestVDC:
    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        self.vca = VCA(host=host,
                       username=username,
                       service_type=service_type,
                       version=version,
                       verify=config['vcloud']['verify'],
                       log=True)
        assert self.vca
        result = self.vca.login(password=password, org=org)
        assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print('logout')
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token
Exemplo n.º 9
0
 def login(self,
           host,
           username,
           password,
           instance,
           org,
           version,
           save_password=True):
     self.vca = VCA(host=host,
                    username=username,
                    version=version,
                    verify=self.verify,
                    log=self.debug)
     service_type = self.vca.get_service_type()
     if service_type == VCA.VCA_SERVICE_TYPE_UNKNOWN:
         raise Exception('service type unknown')
     self.vca.service_type = service_type
     if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type and \
        org is None:
         self.error_message = 'Org can\'t be null'
         return False
     result = self.vca.login(password=password, org=org)
     if result:
         Log.debug(self.logger, 'logged in, org=%s' % self.vca.org)
         if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
             result = self.vca.vcloud_session.login(
                 token=self.vca.vcloud_session.token)
             assert result
         if save_password:
             self.password = password
         self.save_config(self.profile, self.profile_file)
     return result
Exemplo n.º 10
0
 def test_0001(self):
     """Identify vCloud Director Standalone"""
     vca = VCA(host='https://p1v21-vcd.vchs.vmware.com',
               username='', verify=True, log=True)
     assert vca is not None
     service_type = vca.get_service_type()
     assert service_type == VCA.VCA_SERVICE_TYPE_STANDALONE
Exemplo n.º 11
0
 def login_to_vcloud(self):
     """Login to vCloud VCA"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     self.instance = config['vcloud']['instance']
     self.vca = VCA(host=host, username=username, service_type='vca', version=version, verify=True, log=True)
     assert self.vca
     result = self.vca.login(password=password)
     assert result
Exemplo n.º 12
0
 def login_to_vcloud(self):
     """Login to vCloud"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     service_type = VCA.VCA_SERVICE_TYPE_STANDALONE
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     verify = config['vcloud']['verify']
     org = config['vcloud']['org']
     self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=verify,
                    log=True)
     assert self.vca
     result = self.vca.login(password=password, org=org)
     assert result
Exemplo n.º 13
0
 def login_to_vcloud(self):
     """Login to vCloud"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     service_type = config['vcloud']['service_type']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     org = config['vcloud']['org']
     service = config['vcloud']['service']
     instance = config['vcloud']['instance']
     self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
     assert self.vca
     if vcloudair.VCA_SERVICE_TYPE_STANDALONE == service_type:
         result = self.vca.login(password=password, org=org)
         assert result
         result = self.vca.login(token=self.vca.token, org=org, org_url=self.vca.vcloud_session.org_url)
         assert result
     elif vcloudair.VCA_SERVICE_TYPE_SUBSCRIPTION == service_type:
         result = self.vca.login(password=password)
         assert result
         result = self.vca.login(token=self.vca.token)
         assert result
         result = self.vca.login_to_org(service, org)
         assert result
     elif vcloudair.VCA_SERVICE_TYPE_ONDEMAND == service_type:
         result = self.vca.login(password=password)
         assert result
         result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
         assert result
         result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
         assert result
Exemplo n.º 14
0
    def setUp(self):
        config = {
            "admin_password": "******",
            "admin_username": "******",
            "nsx_user": "******",
            "nsx_password": "******",
            "nsx_manager": "https://test-nsx"
        }

        self.vca = VCA(host='test',
                       username='******',
                       service_type='standalone',
                       version='5.9',
                       verify=False,
                       log=False)

        self.session = VCS('https://test/api/session',
                           'test',
                           'test',
                           None,
                           'https://test/api/org/a93c',
                           'https://test/api/org/a93c',
                           version='5.9')

        self.vim = vimconnector(uuid='12354',
                                name='test',
                                tenant_id='abc1234',
                                tenant_name='test',
                                url='https://test',
                                config=config)
Exemplo n.º 15
0
 def login_to_vcloud(self):
     """Login to vCloud"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     service_type = config['vcloud']['service_type']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
     assert self.vca
     if vcloudair.VCA_SERVICE_TYPE_STANDALONE == service_type:
         raise Exception('not-supported')
     elif vcloudair.VCA_SERVICE_TYPE_SUBSCRIPTION == service_type:
         raise Exception('not-supported')
     elif vcloudair.VCA_SERVICE_TYPE_ONDEMAND == service_type:
         result = self.vca.login(password=password)
         assert result
Exemplo n.º 16
0
def _getVCA(profile='default'):
    vca = VCA()
    try:
        config = ConfigParser.RawConfigParser()
        config.read(os.path.expanduser('~/.vcarc'))
        section = 'Profile-%s' % profile
        if config.has_option(section, "host") and config.has_option(section, "token"):
            host = config.get(section, "host")
            token = config.get(section, "token")
            if vca.login(host, None, None, token):
                return vca
            else:
                print "token expired"
        else:
            print "please authenticate"
    except ConfigParser.Error:
        print "please authenticate"
    return None
Exemplo n.º 17
0
class TestVDC:

    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert self.vca
        if self.vca.VCA_SERVICE_TYPE_STANDALONE == service_type:
            raise Exception('not-supported')
        elif self.vca.VCA_SERVICE_TYPE_VCHS == service_type:
            raise Exception('not-supported')
        elif self.vca.VCA_SERVICE_TYPE_VCA == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
            assert result
            result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
            assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token


    def test_0002(self):
        """Get VDC Templates"""
        templates = self.vca.get_vdc_templates()
Exemplo n.º 18
0
def login(ctx, user, host, password):
    """Login to a vCloud service"""
    vca = VCA()
    result = vca.login(host, user, password, None)
    if result:
        click.echo(click.style('Login successful with profile \'%s\'' % ctx.obj['PROFILE'], fg='blue'))
        config = ConfigParser.RawConfigParser()  
        config.read(os.path.expanduser('~/.vcarc'))            
        section = 'Profile-%s' % ctx.obj['PROFILE']
        if not config.has_section(section):
            config.add_section(section)
        config.set(section, 'host', host)
        config.set(section, 'user', user)        
        config.set(section, 'token', vca.token)
        with open(os.path.expanduser('~/.vcarc'), 'w+') as configfile:
            config.write(configfile)        
    else:
        click.echo(click.style('login failed', fg='red'))    
    return result
Exemplo n.º 19
0
 def login_to_vcloud(self):
     """Login to vCloud VCA"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     self.instance = config['vcloud']['instance']
     self.vca = VCA(host=host, username=username, service_type='vca', version=version, verify=True, log=True)
     assert self.vca
     result = self.vca.login(password=password)
     assert result
Exemplo n.º 20
0
 def login_to_vcloud(self):
     """Login to vCloud VCA"""
     username = config["vcloud"]["username"]
     password = config["vcloud"]["password"]
     host = config["vcloud"]["host"]
     version = config["vcloud"]["version"]
     self.instance = config["vcloud"]["instance"]
     self.vca = VCA(host=host, username=username, service_type="vca", version=version, verify=True, log=True)
     assert self.vca
     result = self.vca.login(password=password)
     assert result
Exemplo n.º 21
0
 def _login_user_to_service(self, user, host, password, service_type,
                            service_version, service, org_name):
     vca = VCA(host, user, service_type, service_version)
     result = vca.login(password=password)
     if result:
         if service_type == 'subscription':
             if not service:
                 if org_name:
                     service = org_name
                 else:
                     services = vca.services.get_Service()
                     if not services:
                         return None
                     service = services[0].serviceId
             if not org_name:
                 org_name = vca.get_vdc_references(service)[0].name
             result = vca.login_to_org(service, org_name)
         if result:
             return vca
     return
Exemplo n.º 22
0
def vca_login(module):
    service_type = module.params.get('service_type')
    username = module.params.get('username')
    password = module.params.get('password')
    instance = module.params.get('instance_id')
    org = module.params.get('org')
    vdc_name = module.params.get('vdc_name')
    service = module.params.get('service_id')
    version = module.params.get('api_version')
    verify = module.params.get('validate_certs')

    _validate_module(module)

    if not vdc_name and service_type == 'vchs':
        vdc_name = module.params.get('service_id')

    if not org and service_type == 'vchs':
        org = vdc_name or service

    if service_type == 'vcd':
        host = module.params.get('host')
    else:
        host = LOGIN_HOST[service_type]

    username = os.environ.get('VCA_USER', username)
    password = os.environ.get('VCA_PASS', password)

    if not username or not password:
        msg = "Either the username or password is not set, please check args"
        module.fail_json(msg=msg)

    if service_type == 'vchs':
        version = '5.6'
    elif service_type == 'vcd' and not version:
        version = '5.6'

    vca = VCA(host=host,
              username=username,
              service_type=SERVICE_MAP[service_type],
              version=version,
              verify=verify)

    try:
        if service_type == 'vca':
            _vca_login(vca, password, instance)
        elif service_type == 'vchs':
            _vchs_login(vca, password, service, org)
        elif service_type == 'vcd':
            _vcd_login(vca, password, org)
    except VcaError as e:
        module.fail_json(msg=e.message, **e.kwargs)

    return vca
Exemplo n.º 23
0
 def login_to_vcloud(self):
     """Login to vCloud"""
     username = environ['VCLOUD_USERNAME']
     password = environ['VCLOUD_PASSWORD']
     service_type = config['vcloud']['service_type']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     self.vca = VCA(
         host=host,
         username=username,
         service_type=service_type,
         version=version,
         verify=True,
         log=True)
     assert self.vca
     if self.vca.VCA_SERVICE_TYPE_STANDALONE == service_type:
         raise Exception('not-supported')
     elif self.vca.VCA_SERVICE_TYPE_VCHS == service_type:
         raise Exception('not-supported')
     elif self.vca.VCA_SERVICE_TYPE_VCA == service_type:
         result = self.vca.login(password=password)
         assert result
Exemplo n.º 24
0
    def create_instance(self):
        service_type = self.params.get('service_type', DEFAULT_SERVICE_TYPE)
        host = self.params.get('host', LOGIN_HOST.get('service_type'))
        username = self.params['username']

        version = self.params.get('api_version')
        if service_type == 'vchs':
            version = '5.6'

        verify = self.params.get('verify_certs')

        return VCA(host=host, username=username,
                   service_type=SERVICE_MAP[service_type],
                   version=version, verify=verify)
Exemplo n.º 25
0
def vca_login(module=None):
    username = module.params.get('username')
    password = module.params.get('password')
    instance = module.params.get('instance_id')
    org = module.params.get('org')
    vdc_name = module.params.get('vdc_name')
    verify = module.params.get('verify_certs')
    version = module.params.get('api_version')

    host = module.params.get('host')

    if not username or not password:
        module.fail_json(
            msg="Either the username or password is not set, please check")

    if not version:
        version == '5.5'

    vca = VCA(host=host,
              username=username,
              service_type='vcd',
              version=version,
              verify=verify)

    if not vca.login(password=password, org=org):
        module.fail_json(
            msg=
            "Login Failed: Please check username or password or host parameters"
        )
    if not vca.login(password=password, org=org):
        module.fail_json(msg="Failed to get the token",
                         error=vca.response.content)
    if not vca.login(
            token=vca.token, org=org, org_url=vca.vcloud_session.org_url):
        module.fail_json(msg="Failed to login to org",
                         error=vca.response.content)
    return vca
Exemplo n.º 26
0
class TestVCAUser:


    def __init__(self):
        self.vca = None
        self.instance = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud VCA"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        self.instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type='vca', version=version, verify=True, log=True)
        assert self.vca
        result = self.vca.login(password=password)
        assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_002(self):
        """Get Users"""
        result = self.vca.get_users()
        assert result
        print str(result)
Exemplo n.º 27
0
 def login_to_vcloud(self):
     """Login to vCloud"""
     username = config['vcloud']['username']
     password = config['vcloud']['password']
     service_type = config['vcloud']['service_type']
     host = config['vcloud']['host']
     version = config['vcloud']['version']
     instance = config['vcloud']['instance']
     self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
     assert self.vca
     if self.vca.VCA_SERVICE_TYPE_STANDALONE == service_type:
         raise Exception('not-supported')
     elif self.vca.VCA_SERVICE_TYPE_VCHS == service_type:
         raise Exception('not-supported')
     elif self.vca.VCA_SERVICE_TYPE_VCA == service_type:
         result = self.vca.login(password=password)
         assert result
         result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
         assert result
         result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
         assert result
Exemplo n.º 28
0
 def login(self, host, username, password, instance, org, version,
           save_password=True):
     self.vca = VCA(host=host, username=username, version=version,
                    verify=self.verify, log=self.debug)
     service_type = self.vca.get_service_type()
     if service_type == VCA.VCA_SERVICE_TYPE_UNKNOWN:
         raise Exception('service type unknown')
     self.vca.service_type = service_type
     if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type and \
        org is None:
         self.error_message = 'Org can\'t be null'
         return False
     result = self.vca.login(password=password, org=org)
     if result:
         Log.debug(self.logger, 'logged in, org=%s' % self.vca.org)
         if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
             result = self.vca.vcloud_session.login(token=self.vca.
                                                    vcloud_session.token)
             assert result
         if save_password:
             self.password = password
         self.save_config(self.profile, self.profile_file)
     return result
Exemplo n.º 29
0
class TestExtensions:
    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = VCA.VCA_SERVICE_TYPE_STANDALONE
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        verify = config['vcloud']['verify']
        org = config['vcloud']['org']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=verify,
                       log=True)
        assert self.vca
        result = self.vca.login(password=password, org=org)
        assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print('logout')
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_0002(self):
        """List extensions"""
        system = System(session=self.vca.vcloud_session, verify=self.vca.verify, log=self.vca.log)
        extensions = system.get_extensions()
        assert extensions

    def test_0003(self):
        """Register extension"""
        name = config['vcloud']['ext_name']
        system = System(session=self.vca.vcloud_session, verify=self.vca.verify, log=self.vca.log)
        extension = system.register_extension(name, name, name, name)
        assert extension is not None
        assert name == extension.attrib['name']

    def test_0004(self):
        """Get extension"""
        system = System(session=self.vca.vcloud_session, verify=self.vca.verify, log=self.vca.log)
        extension = system.get_extension(config['vcloud']['ext_name'])
        assert extension is not None
        name = extension.attrib['name']
        assert name == config['vcloud']['ext_name']

    def test_0005(self):
        """Enable extension"""
        system = System(session=self.vca.vcloud_session, verify=self.vca.verify, log=self.vca.log)
        extension = system.get_extension(config['vcloud']['ext_name'])
        assert extension is not None
        name = extension.attrib['name']
        assert name == config['vcloud']['ext_name']
        result = system.enable_extension(name,
                                         extension.attrib['href'],
                                         enabled=True)
        extension = system.get_extension(config['vcloud']['ext_name'])
        assert extension is not None
        name = extension.attrib['name']
        assert name == config['vcloud']['ext_name']
        enabled = '****'
        for node in extension.findall('.//{http://www.vmware.com/vcloud/extension/v1.5}Enabled'):
            enabled = node.text
        assert enabled == 'true'

    def test_0006(self):
        """Disable extension"""
        system = System(session=self.vca.vcloud_session, verify=self.vca.verify, log=self.vca.log)
        extension = system.get_extension(config['vcloud']['ext_name'])
        assert extension is not None
        name = extension.attrib['name']
        assert name == config['vcloud']['ext_name']
        result = system.enable_extension(name,
                                         extension.attrib['href'],
                                         enabled=False)
        extension = system.get_extension(config['vcloud']['ext_name'])
        assert extension is not None
        name = extension.attrib['name']
        assert name == config['vcloud']['ext_name']
        enabled = '****'
        for node in extension.findall('.//{http://www.vmware.com/vcloud/extension/v1.5}Enabled'):
            enabled = node.text
        assert enabled == 'false'

    def test_0007(self):
        """Unregister extension"""
        system = System(session=self.vca.vcloud_session, verify=self.vca.verify, log=self.vca.log)
        extension = system.get_extension(config['vcloud']['ext_name'])
        assert extension is not None
        name = extension.attrib['name']
        assert name == config['vcloud']['ext_name']
        result = system.unregister_extension(config['vcloud']['ext_name'], extension.attrib['href'])
        extension = system.get_extension(config['vcloud']['ext_name'])
        assert extension is None
Exemplo n.º 30
0
        print(datetime.datetime.now(), the_vdc.get_name(),
              vca.vcloud_session.token)
        the_vdc = vca.get_vdc(vdc)
        if the_vdc: print(the_vdc.get_name(), vca.vcloud_session.token)
        else: print(False)
        the_vapp = vca.get_vapp(the_vdc, vapp)
        if the_vapp: print(the_vapp.me.name)
        else: print(False)
        time.sleep(2)


##############################
### vCloud Director standalone
##############################

host = 'vcore3-us01.oc.vmware.com'
username = '******'
password = os.environ['PASSWORD']
org = 'sandbox'
org_url = 'https://vcore3-us01.oc.vmware.com/cloud/org/sandbox'

vca = VCA(host=host,
          username=username,
          service_type='standalone',
          version='5.6',
          verify=True,
          log=True)

result = vca.login(password=password, org=org, org_url=org_url)
print_vca(vca)
Exemplo n.º 31
0
per_org['_total'] = n
print(json.dumps(per_org))

sys.exit(0)

host = sys.argv[1]
username = sys.argv[2]
org = sys.argv[3]
password = sys.argv[4]

org_url = 'https://%s/cloud' % host
verify = False
log = True
version = '27.0'
polling_interval = 5

if not verify:
    requests.packages.urllib3.disable_warnings()

vca_system = VCA(host=host, username=username, service_type='standalone', version=version, verify=verify, log=log)

result = vca_system.login(password=password, org=org, org_url=org_url)
result = vca_system.login(token=vca_system.token, org=org, org_url=vca_system.vcloud_session.org_url)
print('connected: %s' % result)

# while True:
#     print('querying pending and running tasks.')
#
#     time.sleep(polling_interval)
Exemplo n.º 32
0
def vca_login(module=None):
    service_type    = module.params.get('service_type')
    username        = module.params.get('username')
    password        = module.params.get('password')
    instance        = module.params.get('instance_id')
    org             = module.params.get('org')
    service         = module.params.get('service_id')
    vdc_name        = module.params.get('vdc_name')
    version         = module.params.get('api_version')
    verify          = module.params.get('verify_certs')
    if not vdc_name:
        if service_type == 'vchs':
            vdc_name = module.params.get('service_id')
    if not org:
        if service_type == 'vchs':
            if vdc_name:
                org = vdc_name
            else:
                org = service
    if service_type == 'vcd':
        host = module.params.get('host')
    else:
        host = LOGIN_HOST[service_type]

    if not username:
        if 'VCA_USER' in os.environ:
            username = os.environ['VCA_USER']
    if not password:
        if 'VCA_PASS' in os.environ:
            password = os.environ['VCA_PASS']
    if not username or not password:
        module.fail_json(msg = "Either the username or password is not set, please check")

    if service_type == 'vchs':
        version = '5.6'
    if service_type == 'vcd':
        if not version:
            version == '5.6'


    vca = VCA(host=host, username=username, service_type=SERVICE_MAP[service_type], version=version, verify=verify)

    if service_type == 'vca':
        if not vca.login(password=password):
            module.fail_json(msg = "Login Failed: Please check username or password", error=vca.response.content)
        if not vca.login_to_instance(password=password, instance=instance, token=None, org_url=None):
            s_json = serialize_instances(vca.instances)
            module.fail_json(msg = "Login to Instance failed: Seems like instance_id provided is wrong .. Please check",\
                                    valid_instances=s_json)
        if not vca.login_to_instance(instance=instance, password=None, token=vca.vcloud_session.token,
                                     org_url=vca.vcloud_session.org_url):
            module.fail_json(msg = "Error logging into org for the instance", error=vca.response.content)
        return vca

    if service_type == 'vchs':
        if not vca.login(password=password):
            module.fail_json(msg = "Login Failed: Please check username or password", error=vca.response.content)
        if not vca.login(token=vca.token):
            module.fail_json(msg = "Failed to get the token", error=vca.response.content)
        if not vca.login_to_org(service, org):
            module.fail_json(msg = "Failed to login to org, Please check the orgname", error=vca.response.content)
        return vca

    if service_type == 'vcd':
        if not vca.login(password=password, org=org):
            module.fail_json(msg = "Login Failed: Please check username or password or host parameters")
        if not vca.login(password=password, org=org):
            module.fail_json(msg = "Failed to get the token", error=vca.response.content)
        if not vca.login(token=vca.token, org=org, org_url=vca.vcloud_session.org_url):
            module.fail_json(msg = "Failed to login to org", error=vca.response.content)
        return vca
Exemplo n.º 33
0
host = 'vcd.cpsbu.eng.vmware.com'
username = '******'
password = os.environ['PASSWORD']
org = 'org1'
org_url = 'https://%s/cloud/org/org1' % host
verify = False
log = True
version = '27.0'
vdc = 'o1vdc1'
name = sys.argv[1]
key = sys.argv[2]

vca = VCA(host=host,
          username=username,
          service_type='vcd',
          version=version,
          verify=verify,
          log=log)

result = vca.login(password=password, org=org, org_url=org_url)
result = vca.login(token=vca.token,
                   org=org,
                   org_url=vca.vcloud_session.org_url)
print_vca(vca)
the_vdc = vca.get_vdc(vdc)
for entity in the_vdc.get_ResourceEntities().ResourceEntity:
    if entity.type_ == 'application/vnd.vmware.vcloud.vApp+xml':
        if entity.name == name:
            print(('name=%s, href=%s' % (entity.name, entity.href)))
            result = vca.del_vapp_metadata(entity.href, key)
            print(result)
Exemplo n.º 34
0
class TestVCA:


    def __init__(self):
        self.vca = None
        self.login_to_vcloud()


    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert self.vca
        if vcloudair.VCA_SERVICE_TYPE_STANDALONE == service_type:
            raise Exception('not-supported')
        elif vcloudair.VCA_SERVICE_TYPE_SUBSCRIPTION == service_type:
            raise Exception('not-supported')
        elif vcloudair.VCA_SERVICE_TYPE_ONDEMAND == service_type:
            result = self.vca.login(password=password)
            assert result


    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token


    def test_0002(self):
        """Get Service Groups"""
        service_groups = self.vca.get_service_groups()
        assert service_groups
        assert len(service_groups)>=0

    def test_0003(self):
        """Get Plans"""
        plans = self.vca.get_plans()
        assert plans
        assert len(plans)>=0

    def test_0004(self):
        """Get Instances"""
        instances = self.vca.get_instances()
        assert instances
        assert len(instances)>=0


    def test_0005(self):
        """Get Users"""
        users = self.vca.get_users()
        assert users
        assert len(users)>=0
Exemplo n.º 35
0
class CmdProc:
    crypto_key = 'l1ZLY5hYPu4s2IXkTVxtndJ-L_k16rP1odagwhP_DsY='
    DISK_SIZE = 1000000000

    def __init__(self, profile=None, profile_file=None,
                 json_output=False, xml_output=False,
                 debug=False, insecure=False, host_score=None):
        self.profile = profile
        self.profile_file = profile_file
        self.debug = debug
        self.verify = not insecure
        self.json_output = json_output
        self.xml_output = xml_output
        self.password = None
        self.config = ConfigParser.RawConfigParser()
        self.vca = None
        self.instance = None
        self.logger = _get_logger() if debug else None
        self.error_message = None
        self.vdc_name = None
        self.gateway = None
        self.host_score = host_score

    def load_config(self, profile=None, profile_file='~/.vcarc'):
        self.config.read(os.path.expanduser(profile_file))
        if profile is not None:
            self.profile = profile
        else:
            section = 'Global'
            if self.config.has_option(section, 'profile'):
                self.profile = self.config.get(section, 'profile')
            else:
                self.profile = 'default'
        host = 'vca.vmware.com'
        user = None
        password = None
        token = None
        service_type = None
        version = None
        section = 'Profile-%s' % self.profile
        instance = None
        org = None
        org_url = None
        session_token = None
        session_uri = None
        vdc = None
        gateway = None
        host_score = 'score.vca.io'
        if self.config.has_section(section):
            if self.config.has_option(section, 'host'):
                host = self.config.get(section, 'host')
            if self.config.has_option(section, 'user'):
                user = self.config.get(section, 'user')
            if self.config.has_option(section, 'password'):
                password = self.config.get(section, 'password')
                if len(password) > 0:
                    cipher_suite = Fernet(self.crypto_key)
                    password = cipher_suite.decrypt(password)
            if self.config.has_option(section, 'token'):
                token = self.config.get(section, 'token')
            if self.config.has_option(section, 'service_type'):
                service_type = self.config.get(section, 'service_type')
            if self.config.has_option(section, 'service_version'):
                version = self.config.get(section, 'service_version')
            if self.config.has_option(section, 'instance'):
                instance = self.config.get(section, 'instance')
            if self.config.has_option(section, 'org'):
                org = self.config.get(section, 'org')
            if self.config.has_option(section, 'org_url'):
                org_url = self.config.get(section, 'org_url')
            if self.config.has_option(section, 'session_token'):
                session_token = self.config.get(section, 'session_token')
            if self.config.has_option(section, 'session_uri'):
                session_uri = self.config.get(section, 'session_uri')
            if self.config.has_option(section, 'vdc'):
                vdc = self.config.get(section, 'vdc')
            if self.config.has_option(section, 'gateway'):
                gateway = self.config.get(section, 'gateway')
            if self.config.has_option(section, 'host_score'):
                host_score = self.config.get(section, 'host_score')
        self.host_score = host_score
        self.vca = VCA(host=host, username=user,
                       service_type=service_type, version=version,
                       verify=self.verify, log=self.debug)
        self.password = password
        self.vca.token = token
        self.vca.org = org
        self.instance = instance
        if session_token is not None:
            vcloud_session = VCS(url=session_uri,
                                 username=user,
                                 org=org,
                                 instance=instance,
                                 api_url=org_url,
                                 org_url=org_url,
                                 version=version,
                                 verify=self.verify,
                                 log=self.debug)
            vcloud_session.token = session_token
            self.vca.vcloud_session = vcloud_session
            self.vdc_name = vdc
            self.gateway = gateway
        Log.debug(self.logger, 'restored vca %s' % self.vca)
        if self.vca.vcloud_session is not None:
            Log.debug(self.logger, 'restored vcloud_session %s' %
                      self.vca.vcloud_session)
            Log.debug(self.logger, 'restored org=%s' % self.vca.org)
            if self.vca.vcloud_session.token is not None:
                Log.debug(self.logger, 'restored vcloud_session token %s' %
                          self.vca.vcloud_session.token)

    def print_profile_file(self):
        headers = ['Profile', 'Selected', 'Host', 'Type', 'User',
                   'Instance', 'Org', 'vdc']
        table = []
        for section in self.config.sections():
            if section.startswith('Profile-'):
                section_name = section.split('-')[1]
                selected = '*' if section_name == self.profile else ''
                host = self.config.get(section, 'host') \
                    if self.config.has_option(section, 'host') else ''
                service_type = self.config.get(section, 'service_type') \
                    if self.config.has_option(section, 'service_type') else ''
                user = self.config.get(section, 'user') \
                    if self.config.has_option(section, 'user') else ''
                instance = self.config.get(section, 'instance') \
                    if self.config.has_option(section, 'instance') else ''
                org = self.config.get(section, 'org') \
                    if self.config.has_option(section, 'org') else ''
                vdc = self.config.get(section, 'vdc') \
                    if self.config.has_option(section, 'vdc') else ''
                table.append([section_name,
                              selected,
                              host,
                              service_type,
                              user,
                              instance,
                              org,
                              vdc])
        utils.print_table('Profiles in file %s:' %
                          self.profile_file, headers, table, self)

    def save_current_config(self):
        self.save_config(self.profile, self.profile_file)

    def save_config(self, profile='default', profile_file='~/.vcarc'):
        section = 'Global'
        if not self.config.has_section(section):
            self.config.add_section(section)
        self.config.set(section, 'profile', profile)
        section = 'Profile-%s' % profile
        if not self.config.has_section(section):
            self.config.add_section(section)
        if self.vca is None or self.vca.host is None:
            self.config.remove_option(section, 'host')
        else:
            self.config.set(section, 'host', self.vca.host)
        if self.vca is None or self.vca.username is None:
            self.config.remove_option(section, 'user')
        else:
            self.config.set(section, 'user', self.vca.username)
        if self.vca is None or self.vca.service_type is None:
            self.config.remove_option(section, 'service_type')
        else:
            self.config.set(section, 'service_type', self.vca.service_type)
        if self.vca is None or self.vca.version is None:
            self.config.remove_option(section, 'service_version')
        else:
            self.config.set(section, 'service_version', self.vca.version)
        if self.vca is None or self.vca.token is None:
            self.config.remove_option(section, 'token')
        else:
            self.config.set(section, 'token', self.vca.token)
        if self.password is not None and len(self.password) > 0:
            cipher_suite = Fernet(self.crypto_key)
            cipher_text = cipher_suite.encrypt(self.password.encode('utf-8'))
            self.config.set(section, 'password', cipher_text)
        else:
            self.config.remove_option(section, 'password')
        if self.instance is None:
            self.config.remove_option(section, 'instance')
        else:
            self.config.set(section, 'instance', self.instance)
        if self.host_score is None:
            self.config.remove_option(section, 'host_score')
        else:
            self.config.set(section, 'host_score', self.host_score)
        if self.vca is None or self.vca.vcloud_session is None:
            self.config.remove_option(section, 'org')
            self.config.remove_option(section, 'org_url')
            self.config.remove_option(section, 'session_token')
            self.config.remove_option(section, 'session_uri')
            self.config.remove_option(section, 'vdc')
            self.config.remove_option(section, 'gateway')
        else:
            if self.vca.org is None:
                self.config.remove_option(section, 'org')
            else:
                self.config.set(section, 'org', self.vca.org)
            if self.vca.vcloud_session.url is None:
                self.config.remove_option(section, 'session_uri')
            else:
                self.config.set(section, 'session_uri',
                                self.vca.vcloud_session.url)
            if self.vca.vcloud_session.org_url is None:
                self.config.remove_option(section, 'org_url')
            else:
                self.config.set(section, 'org_url',
                                self.vca.vcloud_session.org_url)
            if self.vca.vcloud_session.token is None:
                self.config.remove_option(section, 'session_token')
            else:
                self.config.set(section, 'session_token',
                                self.vca.vcloud_session.token)
            if self.vdc_name is None:
                self.config.remove_option(section, 'vdc')
            else:
                self.config.set(section, 'vdc', self.vdc_name)
            if self.gateway is None:
                self.config.remove_option(section, 'gateway')
            else:
                self.config.set(section, 'gateway', self.gateway)
        with open(os.path.expanduser(profile_file), 'w+') as configfile:
            self.config.write(configfile)

    def login(self, host, username, password, instance, org, version,
              save_password=True):
        self.vca = VCA(host=host, username=username, version=version,
                       verify=self.verify, log=self.debug)
        service_type = self.vca.get_service_type()
        if service_type == VCA.VCA_SERVICE_TYPE_UNKNOWN:
            raise Exception('service type unknown')
        self.vca.service_type = service_type
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type and \
           org is None:
            self.error_message = 'Org can\'t be null'
            return False
        result = self.vca.login(password=password, org=org)
        if result:
            Log.debug(self.logger, 'logged in, org=%s' % self.vca.org)
            if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
                result = self.vca.vcloud_session.login(token=self.vca.
                                                       vcloud_session.token)
                assert result
            if save_password:
                self.password = password
            self.save_config(self.profile, self.profile_file)
        return result

    def re_login_vcloud_session(self):
        Log.debug(self.logger, 'about to re-login vcloud_session vca=%s' %
                  self.vca)
        if self.vca.vcloud_session is not None:
            Log.debug(self.logger, 'about to re-login vcloud_session=%s' %
                      self.vca.vcloud_session)
            if self.vca.vcloud_session.token is not None:
                Log.debug(self.logger,
                          'about to re-login vcloud_session token=%s' %
                          self.vca.vcloud_session.token)
        if self.vca.vcloud_session is not None and \
           self.vca.vcloud_session.token is not None:
            result = self.vca.vcloud_session.login(
                token=self.vca.vcloud_session.token)
            if not result:
                Log.debug(self.logger,
                          'vcloud session invalid, getting a new one')
                if self.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCHS,
                                             'subscription']:
                    result = self.vca.login_to_org(self.instance, self.vca.org)
                elif self.vca.service_type in [VCA.VCA_SERVICE_TYPE_VCA,
                                               'ondemand']:
                    result = self.vca.login_to_instance_sso(self.instance)
                if result:
                    Log.debug(self.logger,
                              'successfully retrieved a new vcloud session')
                else:
                    raise Exception("Couldn't retrieve a new vcloud session")
            else:
                Log.debug(self.logger, 'vcloud session is valid')

    def re_login(self):
        if self.vca is None or \
           (self.vca.token is None and self.password is None):
            return False
        result = False
        try:
            Log.debug(self.logger,
                      'about to re-login with ' +
                      'host=%s type=%s token=%s org=%s' %
                      (self.vca.host, self.vca.service_type,
                       self.vca.token, self.vca.org))
            org_url = None if self.vca.vcloud_session is None else \
                self.vca.vcloud_session.org_url
            result = self.vca.login(token=self.vca.token,
                                    org=self.vca.org,
                                    org_url=org_url)
            if result:
                Log.debug(self.logger, 'vca.login with token successful')
                self.re_login_vcloud_session()
            else:
                Log.debug(self.logger, 'vca.login with token failed %s' %
                          self.vca.response.content)
                raise Exception('login with token failed')
        except Exception as e:
            Log.error(self.logger, str(e))
            tb = traceback.format_exc()
            Log.error(self.logger, tb)
            if self.password is not None and len(self.password) > 0:
                try:
                    Log.debug(self.logger, 'about to re-login with password')
                    result = self.vca.login(password=self.password,
                                            org=self.vca.org)
                    if result:
                        Log.debug(self.logger,
                                  'about to re-login vcloud_session')
                        self.re_login_vcloud_session()
                        Log.debug(self.logger,
                                  'after re-login vcloud_session')
                    self.save_config(self.profile, self.profile_file)
                except Exception:
                    return False
        return result

    def logout(self):
        assert self.vca is not None
        self.vca.logout()
        self.vca = None
        self.password = None
        self.instance = None
        self.host = None
        self.service_type = None
        self.version = None
        self.session_uri = None
        self.host_score = None
        self.save_config(self.profile, self.profile_file)

    def org_to_table(self, vca):
        links = (vca.vcloud_session.organization.Link if
                 vca.vcloud_session.organization else [])
        org_name = (vca.vcloud_session.organization.name if
                    vca.vcloud_session.organization else [])
        org_id = (vca.vcloud_session.organization.id if
                  vca.vcloud_session.organization else [])
        table = [[details.get_type().split('.')[-1].split('+')[0],
                  details.get_name()] for details in
                 filter(lambda info: info.name, links)]
        table.append(['Org Id', org_id[org_id.rfind(':') + 1:]])
        table.append(['Org Name', org_name])
        sorted_table = sorted(
            table, key=operator.itemgetter(0), reverse=False)
        return sorted_table

    def vdc_to_table(self, vdc, gateways):
        table = []
        for entity in vdc.get_ResourceEntities().ResourceEntity:
            table.append([entity.type_.split('.')[-1].split('+')[0],
                         entity.name])
        for entity in vdc.get_AvailableNetworks().Network:
            table.append([entity.type_.split('.')[-1].split('+')[0],
                         entity.name])
        for entity in vdc.get_VdcStorageProfiles().VdcStorageProfile:
            table.append([entity.type_.split('.')[-1].split('+')[0],
                         entity.name])
        for gateway in gateways:
            table.append(['gateway', gateway.get_name()])
        sorted_table = sorted(table, key=operator.itemgetter(0), reverse=False)
        return sorted_table

    def vdc_resources_to_table(self, vdc):
        table = []
        computeCapacity = vdc.get_ComputeCapacity()
        cpu = computeCapacity.get_Cpu()
        memory = computeCapacity.get_Memory()
        # storageCapacity = vca.vdc.get_StorageCapacity()
        table.append(
            ['CPU (%s)' % cpu.get_Units(),
             cpu.get_Allocated(), cpu.get_Limit(),
             cpu.get_Reserved(), cpu.get_Used(),
             cpu.get_Overhead()])
        table.append(['Memory (%s)' % memory.get_Units(),
                      memory.get_Allocated(),
                      memory.get_Limit(), memory.get_Reserved(),
                      memory.get_Used(), memory.get_Overhead()])
        sorted_table = sorted(table, key=operator.itemgetter(0), reverse=False)
        return sorted_table

    def vapps_to_table(self, vdc):
        table = []
        if vdc is not None:
            for entity in vdc.get_ResourceEntities().ResourceEntity:
                if entity.type_ == 'application/vnd.vmware.vcloud.vApp+xml':
                    the_vapp = self.vca.get_vapp(vdc, entity.name)
                    vms = []
                    if the_vapp and the_vapp.me.Children:
                        for vm in the_vapp.me.Children.Vm:
                            vms.append(vm.name)
                    table.append([entity.name, utils.beautified(vms),
                                  self.vca.get_status(the_vapp.me.get_status()
                                                      ),
                                 'yes' if the_vapp.me.deployed
                                  else 'no', the_vapp.me.Description])
        sorted_table = sorted(table, key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def catalogs_to_table(self, catalogs):
        table = []
        for catalog in catalogs:
            if catalog.CatalogItems and catalog.CatalogItems.CatalogItem:
                for item in catalog.CatalogItems.CatalogItem:
                    table.append([catalog.name, item.name])
            else:
                table.append([catalog.name, ''])
        sorted_table = sorted(table, key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def vdc_template_to_table(self, templates):
        table = []
        if templates is None:
            return []
        for template in templates.get_VdcTemplate():
            table.append([template.get_name()])
        sorted_table = sorted(table, key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def vapp_details_to_table(self, vapp):
        table = []
        vms = []
        details = vapp.get_vms_details()
        for vm in details:
            vms.append(vm['name'])
        table.append(['vApp', 'name', vapp.name])
        table.append(['vApp', 'number of VMs', len(details)])
        table.append(['vApp', 'names of VMs', utils.beautified(vms)])

        for vm in details:
            for key in vm.keys():
                table.append(['VM', key, vm[key]])
        return table

    def disks_to_table(self, disks):
        table = []
        for disk in disks:
            if len(disk) > 0:
                table.append([disk[0].name,
                              int(disk[0].size) / self.DISK_SIZE,
                              disk[0].id,
                              disk[0].get_Owner().get_User()])
        sorted_table = sorted(table, key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def vms_to_table(self, vdc, vapp):
        table = []
        if vdc is not None:
            for entity in vdc.get_ResourceEntities().ResourceEntity:
                if entity.type_ == 'application/vnd.vmware.vcloud.vApp+xml':
                    if vapp is not None and \
                       vapp != '' and \
                       vapp != entity.name:
                        continue
                    the_vapp = self.vca.get_vapp(vdc, entity.name)
                    if (not the_vapp or not the_vapp.me or
                            not the_vapp.me.Children):
                        continue
                    for vm in the_vapp.me.Children.Vm:
                        owner = the_vapp.me.get_Owner().get_User().get_name()
                        vm_status = self.vca.get_status(vm.get_status())
                        sections = vm.get_Section()
                        virtualHardwareSection = (
                            filter(lambda section:
                                   section.__class__.__name__ ==
                                   "VirtualHardwareSection_Type",
                                   sections)[0])
                        items = virtualHardwareSection.get_Item()
                        cpu = (
                            filter(lambda item: item.get_Description().
                                   get_valueOf_() == "Number of Virtual CPUs",
                                   items)[0])
                        cpu_capacity = (
                            cpu.get_ElementName().get_valueOf_().
                            split(" virtual CPU(s)")[0])
                        memory = filter(lambda item: item.get_Description().
                                        get_valueOf_() == "Memory Size",
                                        items)[0]
                        memory_capacity = int(
                            memory.get_ElementName().get_valueOf_().
                            split(" MB of memory")[0]) / 1024
                        operatingSystemSection = (
                            filter(lambda section:
                                   section.__class__.__name__ ==
                                   "OperatingSystemSection_Type",
                                   sections)[0])
                        os = (operatingSystemSection.
                              get_Description().get_valueOf_())
                        ips = []
                        networks = []
                        cds = []
                        _url = '{http://www.vmware.com/vcloud/v1.5}ipAddress'
                        for item in items:
                            if item.Connection:
                                for c in item.Connection:
                                    networks.append(c.valueOf_)
                                    if c.anyAttributes_.get(
                                            _url):
                                        ips.append(c.anyAttributes_.get(
                                            _url))
                            elif (item.HostResource and
                                  item.ResourceSubType and
                                  item.ResourceSubType.valueOf_ ==
                                  'vmware.cdrom.iso'):
                                if len(item.HostResource[0].valueOf_) > 0:
                                    cds.append(item.HostResource[0].valueOf_)
                        table.append([vm.name, entity.name, vm_status,
                                      utils.beautified(ips),
                                      utils.beautified(networks),
                                      cpu_capacity,
                                      str(memory_capacity),
                                      utils.beautified(cds),
                                      os, owner])
        sorted_table = sorted(table, key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def select_default_gateway(self):
        gateways = self.vca.get_gateways(self.vdc_name)
        if len(gateways) > 0:
            self.gateway = gateways[0].get_name()
        else:
            self.gateway = None

    def gateways_to_table(self, gateways):
        table = []
        for gateway in gateways:
            interfaces = gateway.get_interfaces('uplink')
            ext_interface_table = []
            for interface in interfaces:
                ext_interface_table.append(interface.get_Name())
            interfaces = gateway.get_interfaces('internal')
            interface_table = []
            for interface in interfaces:
                interface_table.append(interface.get_Name())
            public_ips = gateway.get_public_ips()
            public_ips_value = public_ips
            if len(public_ips) > 2:
                public_ips_value = (
                    "vca gateway info - to list IPs (%d)"
                    % (len(public_ips)))
            table.append([
                gateway.get_name(),
                utils.beautified(str(public_ips_value)),
                'On' if gateway.is_dhcp_enabled() else 'Off',
                'On' if gateway.is_fw_enabled() else 'Off',
                'On' if gateway.is_nat_enabled() else 'Off',
                'On' if gateway.is_vpn_enabled() else 'Off',
                utils.beautified(interface_table),
                gateway.get_syslog_conf(),
                utils.beautified(ext_interface_table),
                '*' if gateway.get_name() == self.gateway else ' '
            ])
        sorted_table = sorted(table,
                              key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def gateway_to_table(self, gateway):
        table = []
        table.append(['Name', gateway.me.name])
        table.append(
            ['DCHP Service', 'On' if gateway.is_dhcp_enabled() else 'Off'])
        table.append(
            ['Firewall Service', 'On' if gateway.is_fw_enabled() else 'Off'])
        table.append(
            ['NAT Service', 'On' if gateway.is_nat_enabled() else 'Off'])
        table.append(
            ['VPN Service', 'On' if gateway.is_vpn_enabled() else 'Off'])
        table.append(
            ['Syslog', gateway.get_syslog_conf()])
        public_ips = gateway.get_public_ips()
        table.append(
            ['External IP #', len(public_ips)])
        if len(public_ips) > 6:
            table.append([
                'External IPs',
                utils.beautified(public_ips[0:6])])
            table.append([
                'External IPs',
                utils.beautified(public_ips[6:])])
        else:
            table.append([
                'External IPs',
                utils.beautified(public_ips)])
        interfaces = gateway.get_interfaces('uplink')
        ext_interface_table = []
        for interface in interfaces:
            ext_interface_table.append(interface.get_Name())
        table.append(
            ['Uplinks',
             utils.beautified(ext_interface_table)])
        return table

    def networks_to_table(self, networks):
        table = []
        for item in networks:
            dhcp_pools = []
            if item.get_ServiceConfig() and len(
                    item.get_ServiceConfig().get_NetworkService()) > 0:
                for service in item.get_ServiceConfig().get_NetworkService():
                    if service.original_tagname_ == 'GatewayDhcpService':
                        for p in service.get_Pool():
                            if p.get_IsEnabled():
                                dhcp_pools.append(p.get_LowIpAddress() +
                                                  '-' + p.get_HighIpAddress())
            config = item.get_Configuration()
            gateways = []
            netmasks = []
            ranges = []
            dns1 = []
            dns2 = []
            for scope in config.get_IpScopes().get_IpScope():
                gateways.append(scope.get_Gateway())
                netmasks.append(scope.get_Netmask())
                if scope.get_Dns1() is not None:
                    dns1.append(scope.get_Dns1())
                if scope.get_Dns2() is not None:
                    dns2.append(scope.get_Dns2())
                if scope.get_IpRanges() is not None:
                    for r in scope.get_IpRanges().get_IpRange():
                        ranges.append(r.get_StartAddress() + '-' +
                                      r.get_EndAddress())
            table.append([
                item.get_name(),
                config.get_FenceMode(),
                utils.beautified(gateways),
                utils.beautified(netmasks),
                utils.beautified(dns1),
                utils.beautified(dns2),
                utils.beautified(ranges)
            ])
        sorted_table = sorted(table,
                              key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def firewall_rules_to_table(self, gateway):
        def create_protocol_string(protocol):
            if protocol.get_Any():
                return 'any'
            protocols = []
            if protocol.get_Tcp():
                protocols.append('tcp')
            if protocol.get_Udp():
                protocols.append('udp')
            if protocol.get_Icmp():
                protocols.append('icmp')
            if protocol.get_Other():
                protocols.append('other')
            return utils.beautified(protocols)
        table = []
        for rule in gateway.get_fw_rules():
            table.append([rule.get_SourceIp(),
                          rule.get_SourcePortRange(),
                          rule.get_DestinationIp(),
                          rule.get_DestinationPortRange(),
                          create_protocol_string(rule.get_Protocols()),
                          'On' if rule.get_IsEnabled() == 1 else 'Off'])
        sorted_table = sorted(table,
                              key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def dhcp_to_table(self, gateway):
        table = []
        service = gateway.get_dhcp_service()
        if service is None:
            return table
        for pool in gateway.get_dhcp_pools():
            table.append([
                pool.get_Network().get_name(),
                pool.get_LowIpAddress(),
                pool.get_HighIpAddress(),
                'Yes' if pool.get_IsEnabled() == 1 else 'No',
                pool.get_DefaultLeaseTime(),
                pool.get_MaxLeaseTime()
            ])
        sorted_table = sorted(table,
                              key=operator.itemgetter(0),
                              reverse=False)
        return sorted_table

    def nat_rules_to_table(self, gateway):
        table = []
        rules = gateway.get_nat_rules()
        if rules is None:
            return table
        for natRule in rules:
            ruleId = natRule.get_Id()
            enable = natRule.get_IsEnabled()
            ruleType = natRule.get_RuleType()
            gatewayNatRule = natRule.get_GatewayNatRule()
            originalIp = gatewayNatRule.get_OriginalIp()
            originalPort = gatewayNatRule.get_OriginalPort()
            translatedIp = gatewayNatRule.get_TranslatedIp()
            translatedPort = gatewayNatRule.get_TranslatedPort()
            protocol = gatewayNatRule.get_Protocol()
            interface = gatewayNatRule.get_Interface().get_name()
            table.append([ruleId, str(enable), ruleType, originalIp,
                          "any" if not originalPort else originalPort,
                          translatedIp,
                          "any" if not translatedPort else translatedPort,
                          "any" if not protocol else protocol, interface])
        return table

    def vpn_endpoints_to_table(self, gateway):
        table = []
        service = gateway.get_vpn_service()
        if service is None:
            return table
        for endpoint in service.get_Endpoint():
            network = ''
            for interface in gateway.get_interfaces('uplink'):
                endpint_ref = endpoint.get_Network().get_href()
                if_ref = interface.get_Network().get_href()
                if endpint_ref == if_ref:
                    network = interface.get_Network().get_name()
            ip = endpoint.get_PublicIp()
            table.append([network, ip])
        return table

    def vpn_tunnels_to_table(self, gateway):
        table = []
        service = gateway.get_vpn_service()
        if service is None:
            return table
        for tunnel in service.get_Tunnel():
            local_networks = []
            for network in tunnel.get_LocalSubnet():
                local_networks.append(network.get_Name())
            peer_networks = []
            for network in tunnel.get_PeerSubnet():
                peer_networks.append(network.get_Name())
            table.append([tunnel.get_Name(),
                          tunnel.get_LocalIpAddress(),
                          utils.beautified(local_networks),
                          tunnel.get_PeerIpAddress(),
                          utils.beautified(peer_networks),
                          'Yes' if tunnel.get_IsEnabled() == 1 else 'No',
                          'Yes' if tunnel.get_IsOperational() == 1 else 'No'])
        return table

    def blueprints_to_table(self, blueprints):
        table = []
        for b in blueprints:
            table.append([b.get('id'), b.get('created_at')[:-7]])
        return table
Exemplo n.º 36
0
##############################
### Subscription
##############################

host='vchs.vmware.com'
username = os.environ['VCAUSER']
password = os.environ['PASSWORD']
service = '85-719'
org = 'AppServices'

vdc = 'AppServices'
vapp = 'cts'

#sample login sequence on vCloud Air Subscription
vca = VCA(host=host, username=username, service_type='subscription', version='5.6', verify=True)

#first login, with password
result = vca.login(password=password)
print_vca(vca)

#next login, with token, no password
#this tests the vca token
result = vca.login(token=vca.token)
print_vca(vca)

#uses vca.token to generate vca.vcloud_session.token
vca.login_to_org(service, org)
print_vca(vca)

#this tests the vcloud session token
Exemplo n.º 37
0
class TestCatalog:


    def __init__(self):
        self.vca = None
        self.login_to_vcloud()


    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert self.vca
        if vcloudair.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token, org=org, org_url=self.vca.vcloud_session.org_url)
            assert result
        elif vcloudair.VCA_SERVICE_TYPE_SUBSCRIPTION == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif vcloudair.VCA_SERVICE_TYPE_ONDEMAND == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
            assert result
            result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
            assert result


    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None


    def catalog_exists(self, catalog_name, catalogs):
        for catalog in catalogs:
            if catalog.name == catalog_name:
                return True
        return False


    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token


    def test_0002(self):
        """Get VDC"""
        vdc_name = config['vcloud']['vdc']
        the_vdc = self.vca.get_vdc(vdc_name)        
        assert the_vdc
        assert the_vdc.get_name() == vdc_name


    def test_0009(self):
        """Validate that catalog doesn't exist"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        catalogs = self.vca.get_catalogs()
        assert not self.catalog_exists(custom_catalog, catalogs)


    def test_0010(self):
        """Create Catalog"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.create_catalog(custom_catalog, custom_catalog)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        catalogs = self.vca.get_catalogs()
        assert self.catalog_exists(custom_catalog, catalogs)


    def test_0011(self):
        """Upload media file"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        media_file_name = config['vcloud']['media_file_name']
        media_name = config['vcloud']['media_name']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        result = self.vca.upload_media(custom_catalog, media_name, media_file_name, media_file_name, True)
        assert result
        #todo: assert that media is uploaded

    def test_0099(self):
        """Delete Catalog"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        deleted = self.vca.delete_catalog(custom_catalog)
        assert deleted
        the_vdc = self.vca.get_vdc(vdc_name)
        catalogs = self.vca.get_catalogs()
        assert not self.catalog_exists(custom_catalog, catalogs)
Exemplo n.º 38
0
 def test_0021(self):
     """Identify vCloud Air vca"""
     vca = VCA(host='https://iam.vchs.vmware.com', username='', verify=True, log=True)
     assert vca is not None
     service_type = vca.get_service_type()
     assert service_type == VCA.VCA_SERVICE_TYPE_VCA
Exemplo n.º 39
0
class TestNet:


    def __init__(self):
        self.vca = None
        self.login_to_vcloud()


    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert self.vca
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token, org=org, org_url=self.vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCHS == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCA == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
            assert result
            result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
            assert result


    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None


    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token


    def test_0003(self):
        """Get Networks"""
        print('')
        vdc_name = config['vcloud']['vdc']
        networks = self.vca.get_networks(vdc_name)
        for network in networks:
            print(network)


    def test_0004(self):
        """ Connect to Networks"""
        print('')
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network_name = config['vcloud']['network']
        network_name2 = config['vcloud']['network2']
        network_name3 = config['vcloud']['network3']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        
        print('disconnect vms')
        task = the_vapp.disconnect_vms()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        print('disconnect vapp')
        task = the_vapp.disconnect_from_networks()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

        index = 0
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        nets = filter(lambda n: n.name == network_name,
                      self.vca.get_networks(vdc_name))
        mode = 'POOL'
        if len(nets) == 1:
            print("connecting vApp to network"
                                " '%s' with mode '%s'" %
                                (network_name, mode))
            task = the_vapp.connect_to_network(
                nets[0].name, nets[0].href)
            assert task
            result = self.vca.block_until_completed(task)
            assert result
            the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
            ip=None
            task = the_vapp.connect_vms(
                nets[0].name,
                connection_index=index,
                connections_primary_index=0,
                ip_allocation_mode=mode.upper(),
                mac_address=None, ip_address=ip)
            assert task
            result = self.vca.block_until_completed(task)
            assert result

        index = index + 1
        nets = filter(lambda n: n.name == network_name2,
                      self.vca.get_networks(vdc_name))
        mode = 'POOL'
        if len(nets) == 1:
            print("connecting vApp to network"
                                " '%s' with mode '%s'" %
                                (network_name2, mode))
            task = the_vapp.connect_to_network(
                nets[0].name, nets[0].href)
            assert task
            result = self.vca.block_until_completed(task)
            assert result
            the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
            ip=None
            task = the_vapp.connect_vms(
                nets[0].name,
                connection_index=index,
                connections_primary_index=0,
                ip_allocation_mode=mode.upper(),
                mac_address=None, ip_address=ip)
            assert task
            result = self.vca.block_until_completed(task)
            assert result

        index = index + 1
        nets = filter(lambda n: n.name == network_name3,
                      self.vca.get_networks(vdc_name))
        mode = 'POOL'
        if len(nets) == 1:
            print("connecting vApp to network"
                                " '%s' with mode '%s'" %
                                (network_name3, mode))
            task = the_vapp.connect_to_network(
                nets[0].name, nets[0].href)
            assert task
            result = self.vca.block_until_completed(task)
            assert result
            the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
            ip=None
            task = the_vapp.connect_vms(
                nets[0].name,
                connection_index=index,
                connections_primary_index=0,
                ip_allocation_mode=mode.upper(),
                mac_address=None, ip_address=ip)
            assert task
            result = self.vca.block_until_completed(task)
            assert result

        print('status=%s' % the_vapp.me.get_status())
        if (4 == the_vapp.me.get_status()):
            print('undeploy vApp')
            task = the_vapp.undeploy()
            if task is not None:
                result = self.vca.block_until_completed(task)

        print('set guest customization')
        task = the_vapp.customize_guest_os(vm_name)
        assert task
        result = self.vca.block_until_completed(task)
        print('force customization')
        task = the_vapp.force_customization(vm_name)
        print task
        if task is not None:
            result = self.vca.block_until_completed(task)
        task = the_vapp.deploy()
        if task is not None:
            result = self.vca.block_until_completed(task)
Exemplo n.º 40
0
class TestVApp:


    def __init__(self):
        self.vca = None
        self.login_to_vcloud()


    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert self.vca
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token, org=org, org_url=self.vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCHS == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCA == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
            assert result
            result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
            assert result


    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None


    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token


    def test_0002(self):
        """Get VDC"""
        vdc_name = config['vcloud']['vdc']
        the_vdc = self.vca.get_vdc(vdc_name)        
        assert the_vdc
        assert the_vdc.get_name() == vdc_name


    def test_0003(self):
        """Create vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        cpu = config['vcloud']['cpus_new']
        memory = config['vcloud']['memory_new']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.create_vapp(vdc_name, vapp_name, template, catalog, 
                                    vm_name=vm_name,
                                    vm_cpus=cpu,
                                    vm_memory=memory)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vdc = self.vca.get_vdc(vdc_name)
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name


    def test_0004(self):
        """Validate vApp State is powered off (8)"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.me.get_status() == 8


    def test_0031(self):
        """Power On vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 8
        task = the_vapp.poweron()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp != None
        assert the_vapp.me.get_status() == 4


    def test_0032(self):
        """Power Off vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 4
        task = the_vapp.poweroff()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp != None
        assert the_vapp.me.get_status() == 8


    def test_0099(self):
        """Delete vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.delete_vapp(vdc_name, vapp_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp == None
Exemplo n.º 41
0

host = 'vcd.cpsbu.eng.vmware.com'
if len(sys.argv) > 0:
    host = sys.argv[1]
username = '******'
password = os.environ['PASSWORD']
org = 'System'
org_url = 'https://%s/cloud' % host
verify = False
log = True
version = '27.0'

vca_system = VCA(host=host,
                 username=username,
                 service_type='standalone',
                 version=version,
                 verify=verify,
                 log=log)

result = vca_system.login(password=password, org=org, org_url=org_url)
result = vca_system.login(token=vca_system.token,
                          org=org,
                          org_url=vca_system.vcloud_session.org_url)
print(result)

tenant_username = '******'
tenant_org = 'org1'
tenant_org_url = 'https://%s/cloud/org/%s' % (host, tenant_org)

vca_tenant = VCA(host=host,
                 username=tenant_username,
Exemplo n.º 42
0
class TestNet:
    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host,
                       username=username,
                       service_type=service_type,
                       version=version,
                       verify=True,
                       log=True)
        assert self.vca
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token,
                                    org=org,
                                    org_url=self.vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCHS == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCA == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password,
                                                instance=instance,
                                                token=None,
                                                org_url=None)
            assert result
            result = self.vca.login_to_instance(
                password=None,
                instance=instance,
                token=self.vca.vcloud_session.token,
                org_url=self.vca.vcloud_session.org_url)
            assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print('logout')
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_0003(self):
        """Get Networks"""
        print('')
        vdc_name = config['vcloud']['vdc']
        networks = self.vca.get_networks(vdc_name)
        for network in networks:
            print(network)

    def test_0004(self):
        """ Connect to Networks"""
        print('')
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network_name = config['vcloud']['network']
        network_name2 = config['vcloud']['network2']
        network_name3 = config['vcloud']['network3']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name

        print('disconnect vms')
        task = the_vapp.disconnect_vms()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        print('disconnect vapp')
        task = the_vapp.disconnect_from_networks()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

        index = 0
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        nets = [
            n for n in self.vca.get_networks(vdc_name)
            if n.name == network_name
        ]
        mode = 'POOL'
        if len(nets) == 1:
            print("connecting vApp to network"
                  " '%s' with mode '%s'" % (network_name, mode))
            task = the_vapp.connect_to_network(nets[0].name, nets[0].href)
            assert task
            result = self.vca.block_until_completed(task)
            assert result
            the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
            ip = None
            task = the_vapp.connect_vms(nets[0].name,
                                        connection_index=index,
                                        connections_primary_index=0,
                                        ip_allocation_mode=mode.upper(),
                                        mac_address=None,
                                        ip_address=ip)
            assert task
            result = self.vca.block_until_completed(task)
            assert result

        index = index + 1
        nets = [
            n for n in self.vca.get_networks(vdc_name)
            if n.name == network_name2
        ]
        mode = 'POOL'
        if len(nets) == 1:
            print("connecting vApp to network"
                  " '%s' with mode '%s'" % (network_name2, mode))
            task = the_vapp.connect_to_network(nets[0].name, nets[0].href)
            assert task
            result = self.vca.block_until_completed(task)
            assert result
            the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
            ip = None
            task = the_vapp.connect_vms(nets[0].name,
                                        connection_index=index,
                                        connections_primary_index=0,
                                        ip_allocation_mode=mode.upper(),
                                        mac_address=None,
                                        ip_address=ip)
            assert task
            result = self.vca.block_until_completed(task)
            assert result

        index = index + 1
        nets = [
            n for n in self.vca.get_networks(vdc_name)
            if n.name == network_name3
        ]
        mode = 'POOL'
        if len(nets) == 1:
            print("connecting vApp to network"
                  " '%s' with mode '%s'" % (network_name3, mode))
            task = the_vapp.connect_to_network(nets[0].name, nets[0].href)
            assert task
            result = self.vca.block_until_completed(task)
            assert result
            the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
            ip = None
            task = the_vapp.connect_vms(nets[0].name,
                                        connection_index=index,
                                        connections_primary_index=0,
                                        ip_allocation_mode=mode.upper(),
                                        mac_address=None,
                                        ip_address=ip)
            assert task
            result = self.vca.block_until_completed(task)
            assert result

        print('status=%s' % the_vapp.me.get_status())
        if (4 == the_vapp.me.get_status()):
            print('undeploy vApp')
            task = the_vapp.undeploy()
            if task is not None:
                result = self.vca.block_until_completed(task)

        print('set guest customization')
        task = the_vapp.customize_guest_os(vm_name)
        assert task
        result = self.vca.block_until_completed(task)
        print('force customization')
        task = the_vapp.force_customization(vm_name)
        print(task)
        if task is not None:
            result = self.vca.block_until_completed(task)
        task = the_vapp.deploy()
        if task is not None:
            result = self.vca.block_until_completed(task)
Exemplo n.º 43
0
 def test_0023(self):
     """Identify standalone is not vCloud Air vca"""
     vca = VCA(host='https://p1v21-vcd.vchs.vmware.com', username='', verify=True, log=True)
     assert vca is not None
     service_type = vca.get_service_type()
     assert service_type != VCA.VCA_SERVICE_TYPE_VCA
Exemplo n.º 44
0
def vca_login(module=None):
    service_type    = module.params.get('service_type')
    username        = module.params.get('username')
    password        = module.params.get('password')
    instance        = module.params.get('instance_id')
    org             = module.params.get('org')
    service         = module.params.get('service_id')
    vdc_name        = module.params.get('vdc_name')
    version         = module.params.get('api_version')
    verify          = module.params.get('verify_certs')
    if not vdc_name:
        if service_type == 'vchs':
            vdc_name = module.params.get('service_id')
    if not org:
        if service_type == 'vchs':
            if vdc_name:
                org = vdc_name
            else:
                org = service
    if service_type == 'vcd':
        host = module.params.get('host')
    else:
        host = LOGIN_HOST[service_type]

    if not username:
        if 'VCA_USER' in os.environ:
            username = os.environ['VCA_USER']
    if not password:
        if 'VCA_PASS' in os.environ:
            password = os.environ['VCA_PASS']
    if not username or not password:
        module.fail_json(msg = "Either the username or password is not set, please check")

    if service_type == 'vchs':
        version = '5.6'
    if service_type == 'vcd':
        if not version:
            version == '5.6'


    vca = VCA(host=host, username=username, service_type=SERVICE_MAP[service_type], version=version, verify=verify)

    if service_type == 'vca':
        if not vca.login(password=password):
            module.fail_json(msg = "Login Failed: Please check username or password", error=vca.response.content)
        if not vca.login_to_instance(password=password, instance=instance, token=None, org_url=None):
            s_json = serialize_instances(vca.instances)
            module.fail_json(msg = "Login to Instance failed: Seems like instance_id provided is wrong .. Please check",\
                                    valid_instances=s_json)
        if not vca.login_to_instance(instance=instance, password=None, token=vca.vcloud_session.token,
                                     org_url=vca.vcloud_session.org_url):
            module.fail_json(msg = "Error logging into org for the instance", error=vca.response.content)
        return vca

    if service_type == 'vchs':
        if not vca.login(password=password):
            module.fail_json(msg = "Login Failed: Please check username or password", error=vca.response.content)
        if not vca.login(token=vca.token):
            module.fail_json(msg = "Failed to get the token", error=vca.response.content)
        if not vca.login_to_org(service, org):
            module.fail_json(msg = "Failed to login to org, Please check the orgname", error=vca.response.content)
        return vca

    if service_type == 'vcd':
        if not vca.login(password=password, org=org):
            module.fail_json(msg = "Login Failed: Please check username or password or host parameters")
        if not vca.login(password=password, org=org):
            module.fail_json(msg = "Failed to get the token", error=vca.response.content)
        if not vca.login(token=vca.token, org=org, org_url=vca.vcloud_session.org_url):
            module.fail_json(msg = "Failed to login to org", error=vca.response.content)
        return vca
Exemplo n.º 45
0
class TestVApp:
    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host,
                       username=username,
                       service_type=service_type,
                       version=version,
                       verify=True,
                       log=True)
        assert self.vca
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token,
                                    org=org,
                                    org_url=self.vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCHS == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCA == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password,
                                                instance=instance,
                                                token=None,
                                                org_url=None)
            assert result
            result = self.vca.login_to_instance(
                password=None,
                instance=instance,
                token=self.vca.vcloud_session.token,
                org_url=self.vca.vcloud_session.org_url)
            assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print('logout')
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_0002(self):
        """Get VDC"""
        vdc_name = config['vcloud']['vdc']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name

    def test_0003(self):
        """Create vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        cpu = config['vcloud']['cpus_new']
        memory = config['vcloud']['memory_new']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.create_vapp(vdc_name,
                                    vapp_name,
                                    template,
                                    catalog,
                                    vm_name=vm_name,
                                    vm_cpus=cpu,
                                    vm_memory=memory)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vdc = self.vca.get_vdc(vdc_name)
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name

    def test_0004(self):
        """Validate vApp State is powered off (8)"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.me.get_status() == 8

    def test_0031(self):
        """Power On vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 8
        task = the_vapp.poweron()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is not None
        assert the_vapp.me.get_status() == 4

    def test_0032(self):
        """Power Off vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 4
        task = the_vapp.poweroff()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is not None
        assert the_vapp.me.get_status() == 8

    def test_0099(self):
        """Delete vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.delete_vapp(vdc_name, vapp_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is None
Exemplo n.º 46
0
 def test_0001(self):
     """Identify vCloud Director Standalone"""
     vca = VCA(host='https://p1v21-vcd.vchs.vmware.com', username='', verify=True, log=True)
     assert vca is not None
     service_type = vca.get_service_type()
     assert service_type == VCA.VCA_SERVICE_TYPE_STANDALONE
Exemplo n.º 47
0
import os
from pyvcloud import vcloudair
from pyvcloud.vcloudair import VCA

username = os.environ['VCAUSER']
password = os.environ['VCAPASS']
service_type = VCA.VCA_SERVICE_TYPE_VCHS
host = 'vchs.vmware.com'
version = '5.6'
vca = VCA(host=host,
          username=username,
          service_type=service_type,
          version=version,
          verify=True,
          log=True)
assert vca
result = vca.login(password=password)
assert result
assert vca.token
service = 'M684216431-4470'
org = 'M684216431-4470'
result = vca.login_to_org(service, org)
assert result
vdc = 'M684216431-4470'
the_vdc = vca.get_vdc(vdc)
assert the_vdc
print('vdc name: ' + the_vdc.get_name())
print('catalogs: ')
for catalog in vca.get_catalogs():
    print('  - ' + catalog.get_name())
Exemplo n.º 48
0
class TestVApp:


    def __init__(self):
        self.vca = None
        self.login_to_vcloud()


    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert self.vca
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token, org=org, org_url=self.vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCHS == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCA == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
            assert result
            result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
            assert result


    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None


    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token


    def test_0002(self):
        """Get VDC"""
        vdc_name = config['vcloud']['vdc']
        the_vdc = self.vca.get_vdc(vdc_name)        
        assert the_vdc
        assert the_vdc.get_name() == vdc_name


    def test_0003(self):
        """Create vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.create_vapp(vdc_name, vapp_name, template, catalog, vm_name=vm_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vdc = self.vca.get_vdc(vdc_name)
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name


    def test_0004(self):
        """Validate vApp State is powered off (8)"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.me.get_status() == 8


    def test_0009(self):
        """Disconnect VM from pre-defined networks"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.disconnect_vms()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        vm_info = the_vapp.get_vms_network_info()
        print vm_info
        assert vm_info
        assert len(vm_info) == 1
        assert len(vm_info[0]) == 0


    def test_0010(self):
        """Disconnect vApp from pre-defined networks"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.disconnect_from_networks()
        assert task
        result = self.vca.block_until_completed(task)
        assert result


    def test_0012(self):
        """Connect vApp to network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_to_network(nets[0].name, nets[0].href)
        result = self.vca.block_until_completed(task)
        assert result


    def test_0013(self):
        """Connect VM to network - MANUAL static IP mode"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        ip_address = config['vcloud']['ip_address']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_vms(nets[0].name, connection_index=0, ip_allocation_mode='MANUAL', ip_address=ip_address)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        vm_info = the_vapp.get_vms_network_info()
        print vm_info
        assert vm_info
        assert len(vm_info) == 1
        assert len(vm_info[0]) == 1
        assert vm_info[0][0].get('network_name') == network
        assert vm_info[0][0].get('allocation_mode') == 'MANUAL'
        assert vm_info[0][0].get('ip') == ip_address

    def test_0014(self):
        """Disconnect VM from network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.disconnect_vms(nets[0].name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        vm_info = the_vapp.get_vms_network_info()
        assert vm_info
        assert len(vm_info) == 1
        assert len(vm_info[0]) == 0


    def test_0015(self):
        """Connect VM to network - POOL mode"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_vms(nets[0].name, connection_index=0, ip_allocation_mode='POOL')
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        vm_info = the_vapp.get_vms_network_info()
        print vm_info
        assert vm_info
        assert len(vm_info) == 1
        assert len(vm_info[0]) == 1
        assert vm_info[0][0].get('network_name') == network
        assert vm_info[0][0].get('allocation_mode') == 'POOL'

    def test_0016(self):
        """Disconnect VM from network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.disconnect_vms(nets[0].name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        vm_info = the_vapp.get_vms_network_info()
        assert vm_info
        assert len(vm_info) == 1
        assert len(vm_info[0]) == 0


    def test_0017(self):
        """Connect VM to network - DHCP mode"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_vms(nets[0].name, connection_index=0, ip_allocation_mode='DHCP')
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        vm_info = the_vapp.get_vms_network_info()
        print vm_info
        assert vm_info
        assert len(vm_info) == 1
        assert len(vm_info[0]) == 1
        assert vm_info[0][0].get('network_name') == network
        assert vm_info[0][0].get('allocation_mode') == 'DHCP'

    def test_0018(self):
        """Disconnect VM from network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.disconnect_vms(nets[0].name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        vm_info = the_vapp.get_vms_network_info()
        assert vm_info
        assert len(vm_info) == 1
        assert len(vm_info[0]) == 0


    def test_0030(self):
        """Validate vApp State is powered off (8)"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.me.get_status() == 8


    def test_0031(self):
        """Power On vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 8
        task = the_vapp.poweron()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp != None
        assert the_vapp.me.get_status() == 4


    def test_0032(self):
        """Power Off vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 4
        task = the_vapp.poweroff()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp != None
        assert the_vapp.me.get_status() == 8


    def test_0099(self):
        """Delete vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.delete_vapp(vdc_name, vapp_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp == None
Exemplo n.º 49
0
class TestVCloud:

    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host, username=username, service_type=service_type, version=version, verify=True, log=True)
        assert self.vca
        if vcloudair.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token, org=org, org_url=self.vca.vcloud_session.org_url)
            assert result
        elif vcloudair.VCA_SERVICE_TYPE_SUBSCRIPTION == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif vcloudair.VCA_SERVICE_TYPE_ONDEMAND == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password, instance=instance, token=None, org_url=None)
            assert result
            result = self.vca.login_to_instance(password=None, instance=instance, token=self.vca.vcloud_session.token, org_url=self.vca.vcloud_session.org_url)
            assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_0002(self):
        """Get VDC"""
        vdc_name = config['vcloud']['vdc']
        the_vdc = self.vca.get_vdc(vdc_name)        
        assert the_vdc
        assert the_vdc.get_name() == vdc_name

    def test_0003(self):
        """Create vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.create_vapp(vdc_name, vapp_name, template, catalog, vm_name=vm_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vdc = self.vca.get_vdc(vdc_name)
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name

    def test_0004(self):
        """Disconnect vApp from pre-defined networks"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.disconnect_from_networks()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

    def test_0005(self):
        """Connect vApp to network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_to_network(nets[0].name, nets[0].href)
        result = self.vca.block_until_completed(task)
        assert result

    def test_0006(self):
        """Connect VM to network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network, self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_vms(nets[0].name, connection_index=0, ip_allocation_mode=mode.upper())
        result = self.vca.block_until_completed(task)
        assert result

    def test_0007(self):
        """Change vApp/VM Memory"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        memory = config['vcloud']['memory']
        memory_new = config['vcloud']['memory_new']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('memory_mb') == memory
        task = the_vapp.modify_vm_memory(vm_name, memory_new)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('memory_mb') == memory_new

    def test_0008(self):
        """Change vApp/VM CPU"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        cpus = config['vcloud']['cpus']
        cpus_new = config['vcloud']['cpus_new']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('cpus') == cpus
        task = the_vapp.modify_vm_cpu(vm_name, cpus_new)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('cpus') == cpus_new

    def test_0009(self):
        """Add NAT rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        rule_type = config['vcloud']['nat_rule_type']
        original_ip = config['vcloud']['nat_original_ip']
        original_port = config['vcloud']['nat_original_port']
        translated_ip = config['vcloud']['nat_translated_ip']
        translated_port = config['vcloud']['nat_translated_port']
        protocol = config['vcloud']['nat_protocol']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.add_nat_rule(rule_type, original_ip, original_port, translated_ip, translated_port, protocol)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

    def test_0010(self):
        """Get NAT rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        rule_type = config['vcloud']['nat_rule_type']
        original_ip = config['vcloud']['nat_original_ip']
        original_port = str(config['vcloud']['nat_original_port'])
        translated_ip = config['vcloud']['nat_translated_ip']
        translated_port = str(config['vcloud']['nat_translated_port'])
        protocol = config['vcloud']['nat_protocol']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        nat_rules = the_gateway.get_nat_rules()
        found_rule = False
        for natRule in nat_rules:
            ruleId = natRule.get_Id()
            if rule_type == natRule.get_RuleType():
                gatewayNatRule = natRule.get_GatewayNatRule()
                gateway_original_ip = gatewayNatRule.get_OriginalIp() if gatewayNatRule.get_OriginalIp() else 'any'
                gateway_original_port = gatewayNatRule.get_OriginalPort() if gatewayNatRule.get_OriginalPort() else 'any'
                gateway_translated_ip = gatewayNatRule.get_TranslatedIp() if gatewayNatRule.get_TranslatedIp() else 'any'
                gateway_translated_port = gatewayNatRule.get_TranslatedPort() if gatewayNatRule.get_TranslatedPort() else 'any'
                gateway_protocol = gatewayNatRule.get_Protocol() if gatewayNatRule.get_Protocol() else 'any'
                if original_ip == gateway_original_ip and \
                   original_port == gateway_original_port and \
                   translated_ip == gateway_translated_ip and \
                   translated_port == gateway_translated_port and \
                   protocol == gateway_protocol:
                    found_rule = True
        assert found_rule

    def test_0011(self):
        """Delete NAT rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        rule_type = config['vcloud']['nat_rule_type']
        original_ip = config['vcloud']['nat_original_ip']
        original_port = str(config['vcloud']['nat_original_port'])
        translated_ip = config['vcloud']['nat_translated_ip']
        translated_port = str(config['vcloud']['nat_translated_port'])
        protocol = config['vcloud']['nat_protocol']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        found_rule = the_gateway.del_nat_rule(rule_type, original_ip, original_port, translated_ip, translated_port, protocol)
        assert found_rule
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        nat_rules = the_gateway.get_nat_rules()
        found_rule = False
        for natRule in nat_rules:
            ruleId = natRule.get_Id()
            if rule_type == natRule.get_RuleType():
                gatewayNatRule = natRule.get_GatewayNatRule()
                gateway_original_ip = gatewayNatRule.get_OriginalIp() if gatewayNatRule.get_OriginalIp() else 'any'
                gateway_original_port = gatewayNatRule.get_OriginalPort() if gatewayNatRule.get_OriginalPort() else 'any'
                gateway_translated_ip = gatewayNatRule.get_TranslatedIp() if gatewayNatRule.get_TranslatedIp() else 'any'
                gateway_translated_port = gatewayNatRule.get_TranslatedPort() if gatewayNatRule.get_TranslatedPort() else 'any'
                gateway_protocol = gatewayNatRule.get_Protocol() if gatewayNatRule.get_Protocol() else 'any'
                if original_ip == gateway_original_ip and \
                   original_port == gateway_original_port and \
                   translated_ip == gateway_translated_ip and \
                   translated_port == gateway_translated_port and \
                   protocol == gateway_protocol:
                    found_rule = True
                    break
        assert found_rule == False

    def test_0012(self):
        """Enable Firewall service"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.enable_fw(True)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        assert the_gateway.is_fw_enabled()

    def test_0013(self):
        """Add Firewall rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        is_enable = config['vcloud']['fw_is_enable']
        description = config['vcloud']['fw_description']
        policy = config['vcloud']['fw_policy']
        dest_ip = config['vcloud']['fw_dest_port']
        dest_port = config['vcloud']['fw_dest_ip']
        protocol = config['vcloud']['fw_protocol']
        source_ip = config['vcloud']['fw_source_ip']
        source_port = config['vcloud']['fw_source_port']
        enable_logging = config['vcloud']['fw_enable_logging']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.add_fw_rule(is_enable, description, policy, protocol, dest_port, dest_ip, source_port, source_ip, enable_logging)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

    def _create_protocols_type(self, protocol):
        all_protocols = {"Tcp": None, "Udp": None, "Icmp": None, "Any": None}
        all_protocols[protocol] = True
        return ProtocolsType(**all_protocols)

    def test_0014(self):
        """Get Firewall rule"""
        def create_protocol_list(protocol):
            plist = []
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Any())
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Udp())
            plist.append(protocol.get_Icmp())
            plist.append(protocol.get_Other())
            return plist

        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        is_enable = config['vcloud']['fw_is_enable']
        description = config['vcloud']['fw_description']
        policy = config['vcloud']['fw_policy']
        dest_ip = config['vcloud']['fw_dest_port']
        dest_port = config['vcloud']['fw_dest_ip']
        protocol = config['vcloud']['fw_protocol']
        source_ip = config['vcloud']['fw_source_ip']
        source_port = config['vcloud']['fw_source_port']
        enable_logging = config['vcloud']['fw_enable_logging']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        rules = the_gateway.get_fw_rules()
        to_find_trait = (create_protocol_list(self._create_protocols_type(protocol)),
                           dest_port, dest_ip,
                           source_port, source_ip)
        rule_found = False
        for rule in rules:
            current_trait = (create_protocol_list(rule.get_Protocols()),
                             rule.get_DestinationPortRange(),
                             rule.get_DestinationIp(),
                             rule.get_SourcePortRange(),
                             rule.get_SourceIp())
            if current_trait == to_find_trait:
                rule_found = True
                break
        assert rule_found

    def test_0015(self):
        """Delete Firewall rule"""
        def create_protocol_list(protocol):
            plist = []
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Any())
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Udp())
            plist.append(protocol.get_Icmp())
            plist.append(protocol.get_Other())
            return plist
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        is_enable = config['vcloud']['fw_is_enable']
        description = config['vcloud']['fw_description']
        policy = config['vcloud']['fw_policy']
        dest_ip = config['vcloud']['fw_dest_port']
        dest_port = config['vcloud']['fw_dest_ip']
        protocol = config['vcloud']['fw_protocol']
        source_ip = config['vcloud']['fw_source_ip']
        source_port = config['vcloud']['fw_source_port']
        enable_logging = config['vcloud']['fw_enable_logging']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.delete_fw_rule(protocol, dest_port, dest_ip, source_port, source_ip)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        rules = the_gateway.get_fw_rules()
        to_find_trait = (create_protocol_list(self._create_protocols_type(protocol)),
                           dest_port, dest_ip,
                           source_port, source_ip)
        rule_found = False
        for rule in rules:
            current_trait = (create_protocol_list(rule.get_Protocols()),
                             rule.get_DestinationPortRange(),
                             rule.get_DestinationIp(),
                             rule.get_SourcePortRange(),
                             rule.get_SourceIp())
            if current_trait == to_find_trait:
                rule_found = True
                break
        assert rule_found == False

    def test_0020(self):
        """Power On vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 8
        task = the_vapp.poweron()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp != None
        assert the_vapp.me.get_status() == 4

    def test_0022(self):
        """Power Off vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 4
        task = the_vapp.poweroff()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp != None
        assert the_vapp.me.get_status() == 8

    def test_0099(self):
        """Delete vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.delete_vapp(vdc_name, vapp_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp == None
Exemplo n.º 50
0
 def load_config(self, profile=None, profile_file='~/.vcarc'):
     self.config.read(os.path.expanduser(profile_file))
     if profile is not None:
         self.profile = profile
     else:
         section = 'Global'
         if self.config.has_option(section, 'profile'):
             self.profile = self.config.get(section, 'profile')
         else:
             self.profile = 'default'
     host = 'vca.vmware.com'
     user = None
     password = None
     token = None
     service_type = None
     version = None
     section = 'Profile-%s' % self.profile
     instance = None
     org = None
     org_url = None
     session_token = None
     session_uri = None
     vdc = None
     gateway = None
     host_score = 'score.vca.io'
     if self.config.has_section(section):
         if self.config.has_option(section, 'host'):
             host = self.config.get(section, 'host')
         if self.config.has_option(section, 'user'):
             user = self.config.get(section, 'user')
         if self.config.has_option(section, 'password'):
             password = self.config.get(section, 'password')
             if len(password) > 0:
                 cipher_suite = Fernet(self.crypto_key)
                 password = cipher_suite.decrypt(password)
         if self.config.has_option(section, 'token'):
             token = self.config.get(section, 'token')
         if self.config.has_option(section, 'service_type'):
             service_type = self.config.get(section, 'service_type')
         if self.config.has_option(section, 'service_version'):
             version = self.config.get(section, 'service_version')
         if self.config.has_option(section, 'instance'):
             instance = self.config.get(section, 'instance')
         if self.config.has_option(section, 'org'):
             org = self.config.get(section, 'org')
         if self.config.has_option(section, 'org_url'):
             org_url = self.config.get(section, 'org_url')
         if self.config.has_option(section, 'session_token'):
             session_token = self.config.get(section, 'session_token')
         if self.config.has_option(section, 'session_uri'):
             session_uri = self.config.get(section, 'session_uri')
         if self.config.has_option(section, 'vdc'):
             vdc = self.config.get(section, 'vdc')
         if self.config.has_option(section, 'gateway'):
             gateway = self.config.get(section, 'gateway')
         if self.config.has_option(section, 'host_score'):
             host_score = self.config.get(section, 'host_score')
     self.host_score = host_score
     self.vca = VCA(host=host, username=user,
                    service_type=service_type, version=version,
                    verify=self.verify, log=self.debug)
     self.password = password
     self.vca.token = token
     self.vca.org = org
     self.instance = instance
     if session_token is not None:
         vcloud_session = VCS(url=session_uri,
                              username=user,
                              org=org,
                              instance=instance,
                              api_url=org_url,
                              org_url=org_url,
                              version=version,
                              verify=self.verify,
                              log=self.debug)
         vcloud_session.token = session_token
         self.vca.vcloud_session = vcloud_session
         self.vdc_name = vdc
         self.gateway = gateway
     Log.debug(self.logger, 'restored vca %s' % self.vca)
     if self.vca.vcloud_session is not None:
         Log.debug(self.logger, 'restored vcloud_session %s' %
                   self.vca.vcloud_session)
         Log.debug(self.logger, 'restored org=%s' % self.vca.org)
         if self.vca.vcloud_session.token is not None:
             Log.debug(self.logger, 'restored vcloud_session token %s' %
                       self.vca.vcloud_session.token)
Exemplo n.º 51
0
class TestVCloud:
    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host,
                       username=username,
                       service_type=service_type,
                       version=version,
                       verify=True,
                       log=True)
        assert self.vca
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token,
                                    org=org,
                                    org_url=self.vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCHS == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif VCA.VCA_SERVICE_TYPE_VCA == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password,
                                                instance=instance,
                                                token=None,
                                                org_url=None)
            assert result
            result = self.vca.login_to_instance(
                password=None,
                instance=instance,
                token=self.vca.vcloud_session.token,
                org_url=self.vca.vcloud_session.org_url)
            assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        self.vca.logout()
        self.vca = None
        assert self.vca is None

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_0002(self):
        """Get VDC"""
        vdc_name = config['vcloud']['vdc']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name

    def test_0003(self):
        """Create vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.create_vapp(vdc_name,
                                    vapp_name,
                                    template,
                                    catalog,
                                    vm_name=vm_name,
                                    network_name=network)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vdc = self.vca.get_vdc(vdc_name)
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name

    def test_0004(self):
        """Clone vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.clone_vapp(vdc_name, vapp_name, vdc_name,
                                   vapp_name + '_clone')
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vdc = self.vca.get_vdc(vdc_name)
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name + '_clone')
        assert the_vapp
        assert the_vapp.name == vapp_name + '_clone'

    def test_0005(self):
        """Disconnect vApp from pre-defined networks"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.disconnect_from_networks()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

    def test_0006(self):
        """Connect vApp to network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network,
                      self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_to_network(nets[0].name, nets[0].href)
        result = self.vca.block_until_completed(task)
        assert result

    def test_0007(self):
        """Connect VM to network"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        nets = filter(lambda n: n.name == network,
                      self.vca.get_networks(vdc_name))
        assert len(nets) == 1
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        task = the_vapp.connect_vms(nets[0].name,
                                    connection_index=0,
                                    ip_allocation_mode=mode.upper())
        result = self.vca.block_until_completed(task)
        assert result

    def test_0008(self):
        """Change vApp/VM Memory"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        memory = config['vcloud']['memory']
        memory_new = config['vcloud']['memory_new']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('memory_mb') == memory
        task = the_vapp.modify_vm_memory(vm_name, memory_new)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('memory_mb') == memory_new

    def test_0009(self):
        """Change vApp/VM CPU"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        cpus = config['vcloud']['cpus']
        cpus_new = config['vcloud']['cpus_new']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('cpus') == cpus
        task = the_vapp.modify_vm_cpu(vm_name, cpus_new)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        assert details[0].get('cpus') == cpus_new

    def test_0010(self):
        """Add NAT rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        rule_type = config['vcloud']['nat_rule_type']
        original_ip = config['vcloud']['nat_original_ip']
        original_port = config['vcloud']['nat_original_port']
        translated_ip = config['vcloud']['nat_translated_ip']
        translated_port = config['vcloud']['nat_translated_port']
        protocol = config['vcloud']['nat_protocol']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.add_nat_rule(rule_type, original_ip, original_port,
                                 translated_ip, translated_port, protocol)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

    def test_0011(self):
        """Get NAT rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        rule_type = config['vcloud']['nat_rule_type']
        original_ip = config['vcloud']['nat_original_ip']
        original_port = str(config['vcloud']['nat_original_port'])
        translated_ip = config['vcloud']['nat_translated_ip']
        translated_port = str(config['vcloud']['nat_translated_port'])
        protocol = config['vcloud']['nat_protocol']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        nat_rules = the_gateway.get_nat_rules()
        found_rule = False
        for natRule in nat_rules:
            ruleId = natRule.get_Id()
            if rule_type == natRule.get_RuleType():
                gatewayNatRule = natRule.get_GatewayNatRule()
                gateway_original_ip = gatewayNatRule.get_OriginalIp(
                ) if gatewayNatRule.get_OriginalIp() else 'any'
                gateway_original_port = gatewayNatRule.get_OriginalPort(
                ) if gatewayNatRule.get_OriginalPort() else 'any'
                gateway_translated_ip = gatewayNatRule.get_TranslatedIp(
                ) if gatewayNatRule.get_TranslatedIp() else 'any'
                gateway_translated_port = gatewayNatRule.get_TranslatedPort(
                ) if gatewayNatRule.get_TranslatedPort() else 'any'
                gateway_protocol = gatewayNatRule.get_Protocol(
                ) if gatewayNatRule.get_Protocol() else 'any'
                if original_ip == gateway_original_ip and \
                   original_port == gateway_original_port and \
                   translated_ip == gateway_translated_ip and \
                   translated_port == gateway_translated_port and \
                   protocol == gateway_protocol:
                    found_rule = True
        assert found_rule

    def test_0012(self):
        """Delete NAT rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        rule_type = config['vcloud']['nat_rule_type']
        original_ip = config['vcloud']['nat_original_ip']
        original_port = str(config['vcloud']['nat_original_port'])
        translated_ip = config['vcloud']['nat_translated_ip']
        translated_port = str(config['vcloud']['nat_translated_port'])
        protocol = config['vcloud']['nat_protocol']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        details = the_vapp.get_vms_details()
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        found_rule = the_gateway.del_nat_rule(rule_type, original_ip,
                                              original_port, translated_ip,
                                              translated_port, protocol)
        assert found_rule
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        nat_rules = the_gateway.get_nat_rules()
        found_rule = False
        for natRule in nat_rules:
            ruleId = natRule.get_Id()
            if rule_type == natRule.get_RuleType():
                gatewayNatRule = natRule.get_GatewayNatRule()
                gateway_original_ip = gatewayNatRule.get_OriginalIp(
                ) if gatewayNatRule.get_OriginalIp() else 'any'
                gateway_original_port = gatewayNatRule.get_OriginalPort(
                ) if gatewayNatRule.get_OriginalPort() else 'any'
                gateway_translated_ip = gatewayNatRule.get_TranslatedIp(
                ) if gatewayNatRule.get_TranslatedIp() else 'any'
                gateway_translated_port = gatewayNatRule.get_TranslatedPort(
                ) if gatewayNatRule.get_TranslatedPort() else 'any'
                gateway_protocol = gatewayNatRule.get_Protocol(
                ) if gatewayNatRule.get_Protocol() else 'any'
                if original_ip == gateway_original_ip and \
                   original_port == gateway_original_port and \
                   translated_ip == gateway_translated_ip and \
                   translated_port == gateway_translated_port and \
                   protocol == gateway_protocol:
                    found_rule = True
                    break
        assert found_rule == False

    def test_0013(self):
        """Enable Firewall service"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.enable_fw(True)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        assert the_gateway.is_fw_enabled()

    def test_0014(self):
        """Add Firewall rule"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        is_enable = config['vcloud']['fw_is_enable']
        description = config['vcloud']['fw_description']
        policy = config['vcloud']['fw_policy']
        dest_ip = config['vcloud']['fw_dest_port']
        dest_port = config['vcloud']['fw_dest_ip']
        protocol = config['vcloud']['fw_protocol']
        source_ip = config['vcloud']['fw_source_ip']
        source_port = config['vcloud']['fw_source_port']
        enable_logging = config['vcloud']['fw_enable_logging']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.add_fw_rule(is_enable, description, policy, protocol,
                                dest_port, dest_ip, source_port, source_ip,
                                enable_logging)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result

    def _create_protocols_type(self, protocol):
        all_protocols = {"Tcp": None, "Udp": None, "Icmp": None, "Any": None}
        all_protocols[protocol] = True
        return ProtocolsType(**all_protocols)

    def test_0015(self):
        """Get Firewall rule"""
        def create_protocol_list(protocol):
            plist = []
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Any())
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Udp())
            plist.append(protocol.get_Icmp())
            plist.append(protocol.get_Other())
            return plist

        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        is_enable = config['vcloud']['fw_is_enable']
        description = config['vcloud']['fw_description']
        policy = config['vcloud']['fw_policy']
        dest_ip = config['vcloud']['fw_dest_port']
        dest_port = config['vcloud']['fw_dest_ip']
        protocol = config['vcloud']['fw_protocol']
        source_ip = config['vcloud']['fw_source_ip']
        source_port = config['vcloud']['fw_source_port']
        enable_logging = config['vcloud']['fw_enable_logging']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        rules = the_gateway.get_fw_rules()
        to_find_trait = (create_protocol_list(
            self._create_protocols_type(protocol)), dest_port, dest_ip,
                         source_port, source_ip)
        rule_found = False
        for rule in rules:
            current_trait = (create_protocol_list(rule.get_Protocols()),
                             rule.get_DestinationPortRange(),
                             rule.get_DestinationIp(),
                             rule.get_SourcePortRange(), rule.get_SourceIp())
            if current_trait == to_find_trait:
                rule_found = True
                break
        assert rule_found

    def test_0016(self):
        """Delete Firewall rule"""
        def create_protocol_list(protocol):
            plist = []
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Any())
            plist.append(protocol.get_Tcp())
            plist.append(protocol.get_Udp())
            plist.append(protocol.get_Icmp())
            plist.append(protocol.get_Other())
            return plist

        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        gateway_name = config['vcloud']['gateway']
        is_enable = config['vcloud']['fw_is_enable']
        description = config['vcloud']['fw_description']
        policy = config['vcloud']['fw_policy']
        dest_ip = config['vcloud']['fw_dest_port']
        dest_port = config['vcloud']['fw_dest_ip']
        protocol = config['vcloud']['fw_protocol']
        source_ip = config['vcloud']['fw_source_ip']
        source_port = config['vcloud']['fw_source_port']
        enable_logging = config['vcloud']['fw_enable_logging']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        the_gateway.delete_fw_rule(protocol, dest_port, dest_ip, source_port,
                                   source_ip)
        task = the_gateway.save_services_configuration()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_gateway = self.vca.get_gateway(vdc_name, gateway_name)
        assert the_gateway
        assert the_gateway.get_name() == gateway_name
        rules = the_gateway.get_fw_rules()
        to_find_trait = (create_protocol_list(
            self._create_protocols_type(protocol)), dest_port, dest_ip,
                         source_port, source_ip)
        rule_found = False
        for rule in rules:
            current_trait = (create_protocol_list(rule.get_Protocols()),
                             rule.get_DestinationPortRange(),
                             rule.get_DestinationIp(),
                             rule.get_SourcePortRange(), rule.get_SourceIp())
            if current_trait == to_find_trait:
                rule_found = True
                break
        assert rule_found == False

    def test_0020(self):
        """Power On vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 8
        task = the_vapp.poweron()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is not None
        assert the_vapp.me.get_status() == 4

    def test_0021(self):
        """Delete vApp Clone"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp'] + '_clone'
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.delete_vapp(vdc_name, vapp_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is None

    def test_0022(self):
        """Power Off vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name
        assert the_vapp.me.get_status() == 4
        task = the_vapp.poweroff()
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is not None
        assert the_vapp.me.get_status() == 8

    def test_0023(self):
        """Delete vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.delete_vapp(vdc_name, vapp_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is None

    def test_0024(self):
        """Compose vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        storage_profile = config['vcloud']['storage_profile']

        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        vm_specs = [{
            'template': template,
            'catalog': catalog,
            'name': vm_name,
            'cpus': 3,
            'memory': 4096,
            'storage_profile': storage_profile
        }]
        task = self.vca.compose_vapp(vdc_name,
                                     vapp_name,
                                     network_name=network,
                                     vm_specs=vm_specs)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vdc = self.vca.get_vdc(vdc_name)
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        assert the_vapp.name == vapp_name

    def test_0025(self):
        """Recompose vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        the_vdc = self.vca.get_vdc(vdc_name)
        storage_profile = config['vcloud']['storage_profile']

        add_vm_specs = [{
            'template': template,
            'catalog': catalog,
            'name': vm_name + '_recompose',
            'cpus': 1,
            'memory': 1024,
            'storage_profile': storage_profile
        }]
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp
        task = self.vca.recompose_vapp(vdc_name,
                                       vapp_name,
                                       add_vm_specs=add_vm_specs,
                                       del_vm_specs=[vm_name])
        assert task
        result = self.vca.block_until_completed(task)
        assert result

    def test_0099(self):
        """Delete vApp"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        catalog = config['vcloud']['catalog']
        template = config['vcloud']['template']
        network = config['vcloud']['network']
        mode = config['vcloud']['mode']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.delete_vapp(vdc_name, vapp_name)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        the_vapp = self.vca.get_vapp(the_vdc, vapp_name)
        assert the_vapp is None
Exemplo n.º 52
0

host = 'https://vcd02-2848639.mv.rackspace.com'
username = "******"
password = "******"
# instance = '28149a83-0d23-4f03-85e1-eb8be013e4ff'
# org = 'System'
org = 'dvc02-2848639'
# vdc = 'bf54d657-0158-4a6b-8c4f-19e96451bebc'
vdc_name = 'dvc02-2848639'
template_name = 'RHEL_6.5_Managed'
catalog = 'Rackspace Catalog'
vapp = ''
api = "https://vcd02-2848639.mv.rackspace.com/api/sessions"
#sample login sequence on vCloud Air On Demand
vca = VCA(host=host, username=username, service_type='vcd', version='5.5', verify=False)

#first login, with password
result = vca.login(password=password, org=org)

# print_vca(vca)

vca_2 = VCA(host=host, username=username, service_type='vcd', version='5.5', verify=False)
vca_2.login(password=password, token=vca.vcloud_session.token, org=vca.vcloud_session.org, org_url=vca.vcloud_session.org_url)


net_href = vca_2.get_network(vdc_name, network_name="ExNet-TenDot-vlan1653").get_href()
net_href_2 = vca_2.get_network(vdc_name, network_name="ExNet-Inside-VLAN1470").get_href()
ser_href = vca_2.get_network(vdc_name, network_name="ServiceNet-Inside-VLAN3082").get_href()

# vdc = vca_2.get_vdc(vdc_name)
Exemplo n.º 53
0
log = True
version = '27.0'

tenant_username = '******'
tenant_org = 'org1'
tenant_org_url = 'https://%s/cloud/org/%s' % (host, tenant_org)
tenant_vdc = 'o1vdc1'
network = 'odnet4'
mode = 'pool'

vm_name = sys.argv[1]
root_password = sys.argv[2]

vca_tenant = VCA(host=host,
                 username=tenant_username,
                 service_type='standalone',
                 version=version,
                 verify=verify,
                 log=log)

result = vca_tenant.login(password=password,
                          org=tenant_org,
                          org_url=tenant_org_url)
assert (result)
user_id = vca_tenant.vcloud_session.session.get_userId().split(':')[-1]
user_name = vca_tenant.vcloud_session.username
result = vca_tenant.login(token=vca_tenant.token,
                          org=tenant_org,
                          org_url=vca_tenant.vcloud_session.org_url)
assert (result)
task = Task(session=vca_tenant.vcloud_session, verify=verify, log=log)
assert (task)
Exemplo n.º 54
0
    def __init__(self):
        self.user           = None
        self.password       = None
        self.version        = None
        self.host           = None
        self.verify         = None

        self.results = {}
        self.meta    = dict(hostvars={})

        self.config = ConfigParser.SafeConfigParser()
        if os.environ.get('VCA_INI', ''):
            config_files = [os.environ['VCA_INI']]
        else:
            config_files =  [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vca.ini']
        for config_file in config_files:
            if os.path.exists(config_file):
                self.config.read(config_file)
                break
        
        self.user = os.environ.get('VCA_USER')
        if not self.user and self.config.has_option('auth', 'user'):
            self.user = self.config.get('auth', 'user')
        self.password = os.environ.get('VCA_PASS')
        if not self.password and self.config.has_option('auth', 'password'):
            self.password = self.config.get('auth', 'password')
        if self.config.has_option('auth', 'service_type'):
            service_type_temp = self.config.get('auth', 'service_type') 
            self.service_type = SERVICE_MAP[service_type_temp]
        if not self.config.has_option('auth', 'service_type'):
            self.service_type = 'vca'
        if self.config.has_option('auth', 'api_version'):
            self.version = self.config.get('auth', 'api_version') 
        if not self.config.has_option('auth', 'api_version'):
            self.version = '5.7'
        if self.config.has_option('auth', 'verify'):
            self.verify = self.config.get('auth', 'verify') 
        if not self.config.has_option('auth', 'verify'):
            self.verify = True
        if self.service_type == 'ondemand':
            self.host = 'vca.vmware.com'
        if self.service_type == 'subscription':
            self.host = 'vchs.vmware.com'
            self.version = '5.6'
        
        if not self.config.has_option('defaults', 'set_ssh_host'):
            self.set_ssh_host = True
        else:
            self.set_ssh_host = self.config.get('defaults', 'set_ssh_host')
        if self.service_type == 'vcd':
            if not self.config.has_option('auth', 'host'):
                sys.stdout.write("host config is needed when serivice type is vcd")
                sys.exit(1)
            self.host = self.config.get('auth', 'host') 
            if not self.config.has_option('auth', 'org'):
                sys.stdout.write("org config is needed when serivice type is vcd")
                sys.exit(1)
            self.org = self.config.get('auth', 'org')

        if self.verify in ['true', 'True', 'yes', 'Yes']:
            self.verify = True
        else:
            self.verify = False

        self.vca = VCA(host=self.host, username=self.user, service_type=self.service_type,\
                       version=self.version, verify=self.verify)
Exemplo n.º 55
0
class TestCatalog:
    def __init__(self):
        self.vca = None
        self.login_to_vcloud()

    def login_to_vcloud(self):
        """Login to vCloud"""
        username = config['vcloud']['username']
        password = config['vcloud']['password']
        service_type = config['vcloud']['service_type']
        host = config['vcloud']['host']
        version = config['vcloud']['version']
        org = config['vcloud']['org']
        service = config['vcloud']['service']
        instance = config['vcloud']['instance']
        self.vca = VCA(host=host,
                       username=username,
                       service_type=service_type,
                       version=version,
                       verify=True,
                       log=True)
        assert self.vca
        if VCA.VCA_SERVICE_TYPE_STANDALONE == service_type:
            result = self.vca.login(password=password, org=org)
            assert result
            result = self.vca.login(token=self.vca.token,
                                    org=org,
                                    org_url=self.vca.vcloud_session.org_url)
            assert result
        elif VCA.VCA_SERVICE_TYPE_SUBSCRIPTION == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login(token=self.vca.token)
            assert result
            result = self.vca.login_to_org(service, org)
            assert result
        elif VCA.VCA_SERVICE_TYPE_ONDEMAND == service_type:
            result = self.vca.login(password=password)
            assert result
            result = self.vca.login_to_instance(password=password,
                                                instance=instance,
                                                token=None,
                                                org_url=None)
            assert result
            result = self.vca.login_to_instance(
                password=None,
                instance=instance,
                token=self.vca.vcloud_session.token,
                org_url=self.vca.vcloud_session.org_url)
            assert result

    def logout_from_vcloud(self):
        """Logout from vCloud"""
        print 'logout'
        selfl.vca.logout()
        self.vca = None
        assert self.vca is None

    def catalog_exists(self, catalog_name, catalogs):
        for catalog in catalogs:
            if catalog.name == catalog_name:
                return True
        return False

    def test_0001(self):
        """Loggin in to vCloud"""
        assert self.vca.token

    def test_0002(self):
        """Get VDC"""
        vdc_name = config['vcloud']['vdc']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name

    def test_0009(self):
        """Validate that catalog doesn't exist"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        catalogs = self.vca.get_catalogs()
        assert not self.catalog_exists(custom_catalog, catalogs)

    def test_0010(self):
        """Create Catalog"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        task = self.vca.create_catalog(custom_catalog, custom_catalog)
        assert task
        result = self.vca.block_until_completed(task)
        assert result
        catalogs = self.vca.get_catalogs()
        assert self.catalog_exists(custom_catalog, catalogs)

    def test_0011(self):
        """Upload media file"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        media_file_name = config['vcloud']['media_file_name']
        media_name = config['vcloud']['media_name']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        result = self.vca.upload_media(custom_catalog, media_name,
                                       media_file_name, media_file_name, True)
        assert result
        # todo: assert that media is uploaded

    def test_0099(self):
        """Delete Catalog"""
        vdc_name = config['vcloud']['vdc']
        vapp_name = config['vcloud']['vapp']
        vm_name = config['vcloud']['vm']
        custom_catalog = config['vcloud']['custom_catalog']
        the_vdc = self.vca.get_vdc(vdc_name)
        assert the_vdc
        assert the_vdc.get_name() == vdc_name
        deleted = self.vca.delete_catalog(custom_catalog)
        assert deleted
        the_vdc = self.vca.get_vdc(vdc_name)
        catalogs = self.vca.get_catalogs()
        assert not self.catalog_exists(custom_catalog, catalogs)
Exemplo n.º 56
0
class VCAInventory(object):

    def __init__(self):
        self.user           = None
        self.password       = None
        self.version        = None
        self.host           = None
        self.verify         = None

        self.results = {}
        self.meta    = dict(hostvars={})

        self.config = ConfigParser.SafeConfigParser()
        if os.environ.get('VCA_INI', ''):
            config_files = [os.environ['VCA_INI']]
        else:
            config_files =  [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vca.ini']
        for config_file in config_files:
            if os.path.exists(config_file):
                self.config.read(config_file)
                break
        
        self.user = os.environ.get('VCA_USER')
        if not self.user and self.config.has_option('auth', 'user'):
            self.user = self.config.get('auth', 'user')
        self.password = os.environ.get('VCA_PASS')
        if not self.password and self.config.has_option('auth', 'password'):
            self.password = self.config.get('auth', 'password')
        if self.config.has_option('auth', 'service_type'):
            service_type_temp = self.config.get('auth', 'service_type') 
            self.service_type = SERVICE_MAP[service_type_temp]
        if not self.config.has_option('auth', 'service_type'):
            self.service_type = 'vca'
        if self.config.has_option('auth', 'api_version'):
            self.version = self.config.get('auth', 'api_version') 
        if not self.config.has_option('auth', 'api_version'):
            self.version = '5.7'
        if self.config.has_option('auth', 'verify'):
            self.verify = self.config.get('auth', 'verify') 
        if not self.config.has_option('auth', 'verify'):
            self.verify = True
        if self.service_type == 'ondemand':
            self.host = 'vca.vmware.com'
        if self.service_type == 'subscription':
            self.host = 'vchs.vmware.com'
            self.version = '5.6'
        
        if not self.config.has_option('defaults', 'set_ssh_host'):
            self.set_ssh_host = True
        else:
            self.set_ssh_host = self.config.get('defaults', 'set_ssh_host')
        if self.service_type == 'vcd':
            if not self.config.has_option('auth', 'host'):
                sys.stdout.write("host config is needed when serivice type is vcd")
                sys.exit(1)
            self.host = self.config.get('auth', 'host') 
            if not self.config.has_option('auth', 'org'):
                sys.stdout.write("org config is needed when serivice type is vcd")
                sys.exit(1)
            self.org = self.config.get('auth', 'org')

        if self.verify in ['true', 'True', 'yes', 'Yes']:
            self.verify = True
        else:
            self.verify = False

        self.vca = VCA(host=self.host, username=self.user, service_type=self.service_type,\
                       version=self.version, verify=self.verify)
    
    def _put_cache(self, name, value):
        if self.config.has_option('defaults', 'cache_dir'):
            cache_dir = self.config.get('defaults', 'cache_dir')
            if not os.path.exists(os.path.expanduser(cache_dir)):
                os.makedirs(os.path.expanduser(cache_dir))
            cache_file = os.path.join(cache_dir, name)
            with open(cache_file, 'w') as cache:
                json.dump(value, cache) 
            cache.close()

    def _get_cache(self, name, default=None):
        if self.config.has_option('defaults', 'cache_dir'):
            cache_dir = self.config.get('defaults', 'cache_dir')
            cache_file = os.path.join(cache_dir, name)
            if os.path.exists(cache_file):
                if self.config.has_option('defaults', 'cache_max_age'):
                    cache_max_age = self.config.getint('defaults', 'cache_max_age')
                else:
                    cache_max_age = 0
                cache_stat = os.stat(cache_file)
                if (cache_stat.st_mtime + cache_max_age) < time.time():
                    with open(cache_file) as cache:
                        return json.load(cache)
        return default
   
    def to_safe(self, word):
        return re.sub("[^A-Za-z0-9\_]", "_", word)

    def vm_details(self, vm_name=None, vapp=None):
        table = {}
        networks = []
        vms = filter(lambda vm: vm['name'] == vm_name, vapp.get_vms_details())
        networks = vapp.get_vms_network_info()
        if len(networks[0]) > 0:
            table.update(vms[0]) 
            table.update(networks[0][0])
            if 'ip' in networks[0][0] and self.set_ssh_host:
                table['ansible_ssh_host'] = networks[0][0]['ip']
        else:
            table.update(vms[0]) 
            table.update(networks[0])
        return table
    
    
    def get_vdcs(self, vca=None):
        links = vca.vcloud_session.organization.Link if vca.vcloud_session.organization else []
        vdcs = filter(lambda info: info.type_ == 'application/vnd.vmware.vcloud.vdc+xml', links)
        return vdcs
    
    def get_vapps(self, vca=None, vdc_name=None):
        table1 = []
        the_vdc = vca.get_vdc(vdc_name)
        if the_vdc:
            table1 = []
            for entity in the_vdc.get_ResourceEntities().ResourceEntity:
                if entity.type_ == 'application/vnd.vmware.vcloud.vApp+xml':
                    the_vapp = vca.get_vapp(the_vdc, entity.name)
                    vms = []
                    if the_vapp and the_vapp.me.Children:
                        for vm in the_vapp.me.Children.Vm:
                            vms.append(vm.name)
                            hostvars = self.vm_details(vm.name, the_vapp)
                            self.meta['hostvars'][vm.name] = hostvars
                    table1.append(dict(vapp_name=vdc_name + '_' + entity.name, vms=vms, status=the_vapp.me.get_status(),\
                                   Deployed= 'yes' if the_vapp.me.deployed else 'no', desciption = the_vapp.me.Description)) 
        return table1
    
    def get_inventory_vcd(self):
        if not self.vca.login(password=self.password, org=self.org):
            sys.stdout.write("Login Failed: Please check username or password or your api version")
        if not self.vca.login(token=self.vca.token, org=self.org, org_url=self.vca.vcloud_session.org_url):
            sys.stdout.write("Failed to login to org")
	vdcs = self.get_vdcs(self.vca)
        org_children = []
	for j in vdcs:
            actual_vdc = j.name
            j.name = self.to_safe(j.name)
	    self.results[j.name] = dict(children=[])
	    org_children.append(j.name)
	    vapps = self.get_vapps(self.vca, j.name) 
	    for k in vapps:
                k['vapp_name'] = self.to_safe(k['vapp_name'])
	        self.results[j.name]['children'].append(k['vapp_name'])
	        self.results[k['vapp_name']] = k['vms']
	self.results[self.org] = dict(children=org_children)
	self.results['_meta'] = self.meta
        cache_name = '__inventory_all__' + self.service_type
        self._put_cache(cache_name, self.results)
        return self.results

    def get_inventory_vca(self):

        if not self.vca.login(password=self.password):
            sys.stdout.write("Login Failed: Please check username or password")
            sys.exit(1)
	instances_dict = self.vca.get_instances()
	for i in instances_dict:
	    instance = i['id']
#	    region   = i['id']
	    region   = i['region']
            region   = self.to_safe(region.split('.')[0])
	    region_children = []
	    if len(instance) != 36:
	        continue
	    if not self.vca.login_to_instance(password=self.password, instance=instance, token=None, org_url=None):
	        sys.stdout.write( "Login to Instance failed: Seems like instance provided is wrong .. Please check")
	        sys.exit(1)
	    if not self.vca.login_to_instance(instance=instance, password=None, token=self.vca.vcloud_session.token, 
	                                 org_url=self.vca.vcloud_session.org_url):
	        sys.stdout.write("Error logging into org for the instance %s" %instance)
	    vdcs = self.get_vdcs(self.vca)
	    for j in vdcs:
                j.name = self.to_safe(j.name)
	        self.results[region + '_' + j.name] = dict(children=[])
	        region_children.append(region + '_' + j.name)
	        vapps = self.get_vapps(self.vca, j.name) 
	        for k in vapps:
                    k['vapp_name'] = self.to_safe(k['vapp_name'])
	            self.results[region + '_' + j.name]['children'].append(region + '_' + j.name + '_' + k['vapp_name'])
	            self.results[region + '_' + j.name + '_' + k['vapp_name']] = k['vms']
	    self.results[region] = dict(children=region_children)
	
	self.results['_meta'] = self.meta
        cache_name = '__inventory_all__' + self.service_type
        self._put_cache(cache_name, self.results)
        return self.results
    
    def get_inventory_vchs(self):
        
        if not self.vca.login(password=self.password):
            sys.stdout.write("Login Failed: Please check username or password, errors: %s" %(self.vca.response))
            sys.exit(1)
        
        if not self.vca.login(token=self.vca.token):
            sys.stdout.write("Failed to get the token")
            sys.exit(1)

        if self.vca.services:
            table = []
            for s in self.vca.services.get_Service():
                for vdc in self.vca.get_vdc_references(s.serviceId):
                    table.append(dict(service=s.serviceId, service_type=s.serviceType, region=s.region,\
                                      vdc=vdc.name, status=vdc.status))  
            for i in table:
                if i['service'] != i['vdc']:
                    self.results[i['service']] = dict(children=[i['vdc']])
                region = i['vdc']
                region = self.to_safe(region)
                self.results[region] = dict(children=[])
                if not self.vca.login_to_org(i['service'], i['vdc']):
                    sys.stdout.write("Failed to login to org, Please check the orgname")
	        vapps = self.get_vapps(self.vca, i['vdc']) 
	        for k in vapps:
                    k['vapp_name'] = self.to_safe(k['vapp_name'])
	            self.results[region]['children'].append(region + '_' + k['vapp_name'])
	            self.results[region + '_' + k['vapp_name']] = k['vms']

	self.results['_meta'] = self.meta
        cache_name = '__inventory_all__' + self.service_type
        self._put_cache(cache_name, self.results)
        return self.results
	

    def get_inventory(self):
        cache_name = '__inventory_all__' + self.service_type
        inv = self._get_cache(cache_name, None)
        if inv is not None:
            return inv
        if self.service_type == 'ondemand':
            return self.get_inventory_vca()
        if self.service_type == 'subscription':
            return self.get_inventory_vchs()
        if self.service_type == 'vcd':
            return self.get_inventory_vcd()