コード例 #1
0
ファイル: rhevm.py プロジェクト: san7ket/satellite6-upgrade
def get_rhevm_client():
    """Creates and returns a client for rhevm.

    The following environment variables affect this command:

    RHEV_USER
        The username of a rhevm project to login.
    RHEV_PASSWD
        The password of a rhevm project to login.
    RHEV_URL
        An url to API of rhevm project.
    """
    username = os.environ.get('RHEV_USER')
    if username is None:
        logger.warning('The RHEV_USER environment variable should be defined.')
    password = os.environ.get('RHEV_PASSWD')
    if password is None:
        logger.warning(
            'The RHEV_PASSWD environment variable should be defined.')
    api_url = os.environ.get('RHEV_URL')
    if api_url is None:
        logger.warning('An RHEV_URL environment variable should be defined.')
    try:
        return API(url=api_url,
                   username=username,
                   password=password,
                   insecure=True)
    except errors.RequestError:
        logger.warning('Invalid Credentials provided for RHEVM.')
        sys.exit(1)
コード例 #2
0
def conn(url, user, password):
    api = API(url=url, username=user, password=password, insecure=True)
    try:
        value = api.test()
    except Exception:
        raise Exception("error connecting to the oVirt API")
    return api
コード例 #3
0
ファイル: oVirtClient.py プロジェクト: aiminickwong/openuds
    def __getApi(self):
        '''
        Gets the api connection.

        Again, due to the fact that ovirtsdk don't allow (at this moment, but it's on the "TODO" list) concurrent access to
        more than one server, we keep only one opened connection.

        Must be accesed "locked", so we can safely alter cached_api and cached_api_key
        '''
        global cached_api, cached_api_key
        aKey = self.__getKey('o-host')
        # if cached_api_key == aKey:
        #    return cached_api

        if cached_api is not None:
            try:
                cached_api.disconnect()
            except:
                # Nothing happens, may it was already disconnected
                pass
        try:
            cached_api_key = aKey
            cached_api = API(url='https://' + self._host + '/api',
                             username=self._username,
                             password=self._password,
                             timeout=self._timeout,
                             insecure=True,
                             debug=False)
            return cached_api
        except:
            logger.exception('Exception connection ovirt at {0}'.format(
                self._host))
            cached_api_key = None
            raise Exception("Can't connet to server at {0}".format(self._host))
            return None
コード例 #4
0
ファイル: ovirt.py プロジェクト: zhengxiang93/avocado-vt
def connect(params):
    """
    Connect ovirt manager API.
    """
    url = params.get('ovirt_engine_url')
    username = params.get('ovirt_engine_user')
    password = params.get('ovirt_engine_password')
    version = params.get('ovirt_engine_version')

    if not all([url, username, password]):
        logging.error('ovirt_engine[url|user|password] are necessary!!')

    if version is None:
        version = param.Version(major='3', minor='6')
    else:
        version = param.Version(version)

    global _api, _connected

    try:
        # Try to connect oVirt API if connection doesn't exist,
        # otherwise, directly return existing API connection.
        if not _connected:
            _api = API(url, username, password, insecure=True)
            _connected = True
            return (_api, version)
        else:
            return (_api, version)
    except Exception as e:
        logging.error('Failed to connect: %s\n' % str(e))
    else:
        logging.info('Succeed to connect oVirt/Rhevm manager\n')
コード例 #5
0
def get_all_vm_endpoints(pattern='*', provider='perf-rhevm'):
    """
    Takes in a pattern and returns all VM ip addresses and names.

    @pattern: Appliance(VM) Name pattern.
            Example: 'Infra*'
    @provider: Provider Name as per 'providers:' in cfme_performance[local].yml
            Default is 'perf-rhevm'.
    """
    provider = cfme_performance.providers[provider]
    ip_address = provider.ip_address
    username = provider.credentials.username
    password = provider.credentials.password

    api = API(
        url='https://%s' % ip_address,
        username=username,
        password=password,
        insecure=True
    )
    vmlist = api.vms.list(name=pattern)

    results = {}
    for vm in vmlist:
        addresses = []
        if vm.guest_info is not None:
            ips = vm.guest_info.get_ips()
            for ip in ips.get_ip():
                addresses.append(ip.get_address())
        results[vm.name] = addresses

    api.disconnect()

    return results
コード例 #6
0
def apilogin(url,
             username,
             password,
             insecure=True,
             persistent_auth=True,
             session_timeout=36000):
    """
    @param url: URL for RHEV-M  / Ovirt
    @param username: username to use
    @param password: password for username
    @param insecure: if True, do not validate SSL cert
    @param persistent_auth: Use persistent authentication
    @param session_timeout: Session timeout for non-persistent authentication
    @return:
    """
    api = None

    try:
        api = API(url=url,
                  username=username,
                  password=password,
                  insecure=insecure,
                  persistent_auth=persistent_auth,
                  session_timeout=session_timeout)
    except:
        print(
            "Error while logging in with supplied credentials, please check and try again"
        )
        sys.exit(1)

    return api
コード例 #7
0
def connect_to_rhev():
    try:
        with open(my_json_file) as data_file:
            data = json.load(data_file)
        my_url = data["rhevapiconnection"]["url"]
        my_username = data["rhevapiconnection"]["username"]
        my_password = data["rhevapiconnection"]["password"]
        my_ca_cert = data["rhevapiconnection"]["ca_cert"]
    except IOError as ex:
        syslog.syslog(
            syslog.LOG_CRIT,
            'Could not load json file, error was: %s . Script will now end' %
            (ex))
        sys.exit()
    try:
        api = API(url=my_url,
                  username=my_username,
                  password=my_password,
                  ca_file=my_ca_cert)
        return api
    except ovirtsdk.infrastructure.errors.ConnectionError as ex:
        syslog.syslog(
            syslog.LOG_CRIT,
            'Failed to connect to rhev, error was: %s . Script will now end' %
            (ex))
        sys.exit()
コード例 #8
0
 def _init_api(self):
     self.log.debug("Doing blocking acquire() on global RHEVM API connection lock")
     self.api_connections_lock.acquire()
     self.log.debug("Got global RHEVM API connection lock")
     url = self.api_details['url']
     username = self.api_details['username']
     password = self.api_details['password']
     self.api = API(url=url, username=username, password=password, insecure=True)
コード例 #9
0
def conn(url, user, password):
    api = API(url=url, username=user, password=password, insecure=True)
    try:
        value = api.test()
    except:
        print "error connecting to the oVirt API"
        sys.exit(1)
    return api
コード例 #10
0
def connect(ovirt_api_url, ovirt_username, ovirt_password):
    VERSION = params.Version(major='4', minor='0')
    ovirt_api = API(url=ovirt_api_url,
                    username=ovirt_username,
                    password=ovirt_password,
                    insecure=True)

    return ovirt_api
コード例 #11
0
 def login(self, username, password):
     global api
     try:
         api = API(url=self.baseUrl, username=username, password=password, filter=True,insecure=True)
     except RequestError as reqErr:
         return False, "Login error"
     except ConnectionError as conErr:
         return False, "Bad URL"
     return True, ''
コード例 #12
0
def connect():
    url = 'http://localhost:8080/ovirt-engine/api'
    username = '******'
    password = '******'

    print 'Connecting to', url, 'as', username
    api = API(url=url, username=username, password=password)

    print 'Connected'
    return api
コード例 #13
0
 def connect(self, args):
     try:
         self._api = API(args.url,
                         args.username,
                         args.password,
                         insecure=True)
     except Exception, e:
         print "Failed to connect to: %s" % args.url
         print e
         sys.exit(1)
コード例 #14
0
 def __init__(self, ohost, oport, ouser, opassword, ossl):
     if ossl:
         url = "https://%s:%s/api" % (ohost, oport)
     else:
         url = "http://%s:%s/api" % (ohost, oport)
     self.api = API(url=url,
                    username=ouser,
                    password=opassword,
                    insecure=True)
     self.macaddr = []
コード例 #15
0
def main():
    url = 'https://vm-rhevm01.infoplus-ot.ris:443/api'
    username = '******'
    password = getpass.getpass("Supply password for user %s: " % username)

    api = API(url=url, username=username, password=password, insecure=True)
    vm_list = api.vms.list()
    for vm in vm_list:
        print vm.name
    api.disconnect()
コード例 #16
0
def conn(url, username, password, ca_file):
    """ define connection RHEV-M api"""
    try:
        api = API(url=url,
                  username=username,
                  password=password,
                  ca_file=ca_file)
        return api
    except Exception as ex:
        print "Unexpected error: %s" % ex
コード例 #17
0
 def connect(self):
     """Connect to oVirt/RHEV API"""
     try:
         self.api = API(url=self.url,
                        username=self.user,
                        password=self.password,
                        insecure='True')
         return self.api
     except RequestError as err:
         print("Error: {} Reason: {}".format(err.status, err.reason))
         exit(1)
コード例 #18
0
def rhevm_create_api(url, username, password):
    """Creates rhevm api endpoint.

    Args:
        url: URL to rhevm provider
        username: username used to log in into rhevm
        password: password used to log in into rhevm
    """
    apiurl = 'https://%s:443/api' % url
    return API(url=apiurl, username=username, password=password, insecure=True,
               persistent_auth=False)
コード例 #19
0
    def __init__(self, hostname, username, password, **kwargs):
        # generate URL from hostname

        if 'port' in kwargs:
            url = 'https://%s:%s/api' % (hostname, kwargs['port'])
        else:
            url = 'https://%s/api' % hostname

        self.api = API(url=url,
                       username=username,
                       password=password,
                       insecure=True)
コード例 #20
0
 def login(self, url, username, password, ca_file):
     global api
     try:
         api = API(url=url,
                   username=username,
                   password=password,
                   ca_file=ca_file)
     except RequestError as reqErr:
         return False, "Login error"
     except ConnectionError as conErr:
         return False, "Bad URL"
     return True, ''
コード例 #21
0
ファイル: RHEV.py プロジェクト: autto91/py_stuff
    def __entrypoint(self):
        try:
            url = 'https://rhevserver.com'
            api = API(url=url,
                      username=self._username,
                      password=self._password,
                      ca_file='ca.crt')

            return api

        except Exception as ex:
            print('Error: %s' % ex)
コード例 #22
0
def initAPI():
    global controller
    logging.debug("Initiating the API object")

    URL = API_OBJECT_PATH % (controller.CONF["HOST_FQDN"],
                             controller.CONF["HTTPS_PORT"])
    USERNAME = '******'
    try:
        controller.CONF["API_OBJECT"] = API(
            url=URL, username=USERNAME, password=controller.CONF['AUTH_PASS'])
    except:
        logging.error(traceback.format_exc())
        raise Exception(ERROR_CREATE_API_OBJECT)
コード例 #23
0
    def _get_connection(self):
        #open a connection to the rest api
        connection = None
        try:
            connection = API(url='http://localhost:8080',
                             username='******',
                             password='******')
        except BaseException as ex:
            #letting the external proxy know there was an error
            print >> sys.stderr, ex
            return None

        return connection
コード例 #24
0
    def _get_connection(self):
        #open a connection to the rest api
        connection = None
        try:
            connection = API(url='http://host:port',
                             username='******',
                             password='')
        except BaseException as ex:
            #letting the external proxy know there was an error
            print >> sys.stderr, ex
            return None

        return connection
コード例 #25
0
def connect():
    api_url = "https://manager/ovirt-engine/api"
    api_user = "******"
    api_password = "******"
    api_ca = "/path/to/my.cer"

    try:
        api = API(url=api_url,
                  username=api_user,
                  password=api_password,
                  ca_file=api_ca)
        return api
    except Exception as e:
        sys.exit("api connection failed: %s" % e)
コード例 #26
0
def get_engine_api():
    api = None
    eac_data = ta_info_xml.get_engine_api_conf()
    if eac_data == {}:
        return
    try:
        #         print eac_data['url'], eac_data['username'], eac_data['password'], eac_data['ca_file']
        api = API(url=eac_data['url'],
                  username=eac_data['username'],
                  password=eac_data['password'],
                  ca_file=eac_data['ca_file'])
    except Exception as e:
        pass

    return api
コード例 #27
0
    def __init__(self,
                 url,
                 cluster_name,
                 ca_file,
                 username=None,
                 password=None,
                 kerberos=None,
                 verbose=0,
                 **kwargs):
        super(RHEVM, self).__init__()

        self.url = url
        self.username = username
        self.password = password
        self.cluster = cluster_name
        self.ca_file = ca_file
        self.kerberos = kerberos
        self.verbose = verbose
        self.debug = verbose > 1

        if self.kerberos:
            if self.verbose:
                show("Using Kerberos authentication")
            self.api = API(url=self.url,
                           kerberos=True,
                           ca_file=self.ca_file,
                           filter=True,
                           debug=self.debug)
        else:
            if self.verbose:
                show("Using username and password: %s" % self.username)
            self.api = API(url=self.url,
                           username=self.username,
                           password=self.password,
                           ca_file=self.ca_file,
                           debug=self.debug)
コード例 #28
0
ファイル: dispatcher.py プロジェクト: oVirt/samples-portals
 def login(self, url, username, password, ca_file):
     global api
     try:
         api = API(url=url,
                   username=username,
                   password=password,
                   ca_file=ca_file)
     except RequestError as reqErr:
         return False, "Login error"
     except ConnectionError as conErr:
         return False, "Bad URL"
     except NoCertificatesError as certErr:
         return False, "SSL error. Use 'http(s)://'"
     except Exception as e:
         return False, str(e)
     return True, ''
コード例 #29
0
    def _connect(self, system):
        """ General function to retrive the info from the RHEV system
		"""
        try:
            if self.debug:
                print "Getting information from %s with url %s" % (
                    system, self.config.get(system, 'url'))
            # Initialize api_instance sith login creadentials
            self.api = API(url=self.config.get(system, 'url'),
                           username=self.config.get(system, 'username'),
                           password=self.config.get(system, 'password'),
                           ca_file=self.config.get(system, 'ca_file'))
            if self.debug: print "-Connected successfully-"
        except Exception as ex:
            print "WARNING - %s in config file" % str(ex)
            sys.exit(1)
コード例 #30
0
def ovirt_create_storage(module):

    name = module.params['name']
    datacenter = module.params['datacenter']
    host = module.params['host']
    path = module.params['path']
    type = module.params['type']
    storage_type = module.params['storage_type']
    storage_url = module.params['storage_url']
    username = module.params['username']
    password = module.params['password']
    url = module.params['url']

    try:
        api = API(url=url,
                  username=username,
                  password=password,
                  insecure=True,
                  session_timeout=60)
    except Exception as ex:
        module.fail_json(msg='could not connect to ovirt api')

    isoParams = params.StorageDomain(
        name=name,
        data_center=api.datacenters.get(datacenter),
        type_=storage_type,
        host=api.hosts.get(host),
        storage=params.Storage(
            type_=type,
            address=storage_url,
            path=path,
        ))

    if api.datacenters.get(datacenter).storagedomains.get(name):
        module.exit_json(changed=False)

    if module.check_mode:
        module.exit_json(changed=True)

    try:
        sd = api.storagedomains.add(isoParams)
        api.datacenters.get(datacenter).storagedomains.add(
            api.storagedomains.get(name))
    except Exception as ex:
        module.fail_json(msg='Adding storage domain failed' + str(ex))

    module.exit_json(changed=True)