Uses the OpenNebula cloud provider configurations to connect to the
    OpenNebula API.

    Returns the server connection created as well as the user and password
    values from the cloud provider config file used to make the connection.
177863
def _get_xml_rpc():
    '''
    
    '''
    vm_ = get_configured_provider()

    xml_rpc = config.get_cloud_config_value(
        'xml_rpc', vm_, __opts__, search_global=False
    )

    user = config.get_cloud_config_value(
        'user', vm_, __opts__, search_global=False
    )

    password = config.get_cloud_config_value(
        'password', vm_, __opts__, search_global=False
    )

    server = salt.ext.six.moves.xmlrpc_client.ServerProxy(xml_rpc)

    return server, user, password
312078
def get_conn():
    '''
    
    '''
    certificate_path = config.get_cloud_config_value(
        'certificate_path',
        get_configured_provider(), __opts__, search_global=False
    )
    subscription_id = salt.utils.stringutils.to_str(
        config.get_cloud_config_value(
            'subscription_id',
            get_configured_provider(), __opts__, search_global=False
        )
    )
    management_host = config.get_cloud_config_value(
        'management_host',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default='management.core.windows.net'
    )
    return azure.servicemanagement.ServiceManagementService(
        subscription_id, certificate_path, management_host
    )
1118796
def _create_connection(self):
        
        transport = SSL if self.ssl else TCP
        return transport(self.server, self.port)
782568
def establish_rabbitmq_connection(rabbitmq_uri):
    
    userid, password, host, port, virtual_host, ssl = translate_rabbitmq_url(rabbitmq_uri)

    connection = Connection(userid=userid,
                            password=password,
                            host=host,
                            port=port,
                            virtual_host=virtual_host,
                            ssl=False)

    return connection
1250605
def create(provider, count=1, name=None, **kwargs):
    
    '''
    count = int(count)
    provider = provider_by_name(provider)
    options = provider.create_server_defaults
    options.update(kwargs)
    names = [name] * count
    provider.validate_create_options(**options)
    return provider.create_servers(count, names, **options)
617431
def _connect(self):
        
        # check for existing connection
        if self._ec2_connection:
            return self._ec2_connection

        try:
            log.debug("Connecting to EC2 endpoint %s", self._ec2host)

            # connect to webservice
            ec2_connection = boto.ec2.connect_to_region(
                self._region_name,
                aws_access_key_id=self._access_key,
                aws_secret_access_key=self._secret_key,
                is_secure=self._secure,
                host=self._ec2host,
                port=self._ec2port,
                path=self._ec2path,
            )
            # With the loose setting `BOTO_USE_ENDPOINT_HEURISTICS`
            # which is necessary to work around issue #592, Boto will
            # now accept *any* string as an AWS region name;
            # furthermore, it *always* returns a connection object --
            # so the only way to check that we are not going to run
            # into trouble is to check that there *is* a valid host
            # name on the other end of the connection.
            if ec2_connection.host:
                log.debug("EC2 connection has been successful.")
            else:
                raise CloudProviderError(
                    "Cannot establish connection to EC2 region {0}"
                    .format(self._region_name))

            if not self._vpc:
                vpc_connection = None
                self._vpc_id = None
            else:
                vpc_connection, self._vpc_id = self._find_vpc_by_name(self._vpc)

        except Exception as err:
            log.error("Error connecting to EC2: %s", err)
            raise

        self._ec2_connection, self._vpc_connection = (
            ec2_connection, vpc_connection)
        return self._ec2_connection
296838
public static function connect()
  {
    try
    {
        /**
         * Check if the APP_ENV variable is set. If not found or it has a value of 'local'
         * then load variable values from app's .env file. Else load server server environment variables.
         */
        if (! getenv('APP_ENV') || getenv('APP_ENV')=="local") {
            $dotenv = new Dotenv($_SERVER['DOCUMENT_ROOT']);
            $dotenv->load();
        }

        $host = getenv('DB_HOST');
        $db = getenv('DB_NAME');
        $username = getenv('DB_USERNAME');
        $password = getenv('DB_PASSWORD');
        $driver = getenv('DB_DRIVER');

        return new PDO($driver.':host='.$host.';dbname='.$db, $username, $password);
    }
    catch (PDOException $e)
    {
        return $e->getMessage();
    }
  }
1216012
def authenticate_user(self):
        
        cloud_config = os_client_config.OpenStackConfig().get_one_cloud(
            cloud=self.options.os_cloud, argparse=self.options,
            network_api_version=self.api_version,
            verify=not self.options.insecure)
        verify, cert = cloud_config.get_requests_verify_args()

        # TODO(singhj): Remove dependancy on HTTPClient
        # for the case of token-endpoint authentication

        # When using token-endpoint authentication legacy
        # HTTPClient will be used, otherwise SessionClient
        # will be used.
        if self.options.os_token and self.options.os_url:
            auth = None
            auth_session = None
        else:
            auth = cloud_config.get_auth()

            auth_session = session.Session(
                auth=auth, verify=verify, cert=cert,
                timeout=self.options.http_timeout)

        interface = self.options.os_endpoint_type or self.endpoint_type
        if interface.endswith('URL'):
            interface = interface[:-3]
        self.client_manager = clientmanager.ClientManager(
            retries=self.options.retries,
            raise_errors=False,
            session=auth_session,
            url=self.options.os_url,
            token=self.options.os_token,
            region_name=cloud_config.get_region_name(),
            api_version=cloud_config.get_api_version('network'),
            service_type=cloud_config.get_service_type('network'),
            service_name=cloud_config.get_service_name('network'),
            endpoint_type=interface,
            auth=auth,
            insecure=not verify,
            log_credentials=True)
        return
59047
function Connection(options) {
	
	if (!(this instanceof Connection)){
		return new Connection(options);
	}
	
	
	this.prefixCounter = 0;
	this.serverMessages = {};
	this._options = {
		username: options.username || options.user || '',
		password: options.password || '',
		host: options.host || 'localhost',
		port: options.port || 143,
		secure: options.secure === true ? { // secure = true means default behavior
			rejectUnauthorized: false // Force pre-node-0.9.2 behavior
		} : (options.secure || false),
		timeout: options.timeout || 10000, // connection timeout in msecs
		xoauth: options.xoauth,
		xoauth2: options.xoauth2
	};
	
	this._messages = {};
	this._messages = {};
	
	if (options.debug===true){
		this.debug = function(msg){
			console.log(msg);
		}
	}
	
		
	if (options.chainDebug===true){
		this.chainDebug = function(msg){
			console.log(msg);
		}
	}
	
	this.socket = null;
	
	this._messages_prefix_key={};
	this._messages_key_prefix={};
	this._messages={};
	
	
	this._msg_buffer = '';
	this._resetChainCommands();
}
1058959
def apply_cloud_providers_config(overrides, defaults=None):
    '''
    
    '''
    if defaults is None:
        defaults = PROVIDER_CONFIG_DEFAULTS

    config = defaults.copy()
    if overrides:
        config.update(overrides)

    # Is the user still using the old format in the new configuration file?!
    for name, settings in six.iteritems(config.copy()):
        if '.' in name:
            log.warning(
                'Please switch to the new providers configuration syntax'
            )

            # Let's help out and migrate the data
            config = old_to_new(config)

            # old_to_new will migrate the old data into the 'providers' key of
            # the config dictionary. Let's map it correctly
            for prov_name, prov_settings in six.iteritems(config.pop('providers')):
                config[prov_name] = prov_settings
            break

    providers = {}
    ext_count = 0
    for key, val in six.iteritems(config):
        if key in ('conf_file', 'include', 'default_include', 'user'):
            continue

        if not isinstance(val, (list, tuple)):
            val = [val]
        else:
            # Need to check for duplicate cloud provider entries per "alias" or
            # we won't be able to properly reference it.
            handled_providers = set()
            for details in val:
                if 'driver' not in details:
                    if 'extends' not in details:
                        log.error(
                            'Please check your cloud providers configuration. '
                            'There\'s no \'driver\' nor \'extends\' definition '
                            'referenced.'
                        )
                    continue

                if details['driver'] in handled_providers:
                    log.error(
                        'You can only have one entry per cloud provider. For '
                        'example, if you have a cloud provider configuration '
                        'section named, \'production\', you can only have a '
                        'single entry for EC2, Joyent, Openstack, and so '
                        'forth.'
                    )
                    raise salt.exceptions.SaltCloudConfigError(
                        'The cloud provider alias \'{0}\' has multiple entries '
                        'for the \'{1[driver]}\' driver.'.format(key, details)
                    )
                handled_providers.add(details['driver'])

        for entry in val:

            if 'driver' not in entry:
                entry['driver'] = '-only-extendable-{0}'.format(ext_count)
                ext_count += 1

            if key not in providers:
                providers[key] = {}

            provider = entry['driver']
            if provider not in providers[key]:
                providers[key][provider] = entry

    # Is any provider extending data!?
    while True:
        keep_looping = False
        for provider_alias, entries in six.iteritems(providers.copy()):
            for driver, details in six.iteritems(entries):
                # Set a holder for the defined profiles
                providers[provider_alias][driver]['profiles'] = {}

                if 'extends' not in details:
                    continue

                extends = details.pop('extends')

                if ':' in extends:
                    alias, provider = extends.split(':')
                    if alias not in providers:
                        raise salt.exceptions.SaltCloudConfigError(
                            'The \'{0}\' cloud provider entry in \'{1}\' is '
                            'trying to extend data from \'{2}\' though '
                            '\'{2}\' is not defined in the salt cloud '
                            'providers loaded data.'.format(
                                details['driver'],
                                provider_alias,
                                alias
                            )
                        )

                    if provider not in providers.get(alias):
                        raise salt.exceptions.SaltCloudConfigError(
                            'The \'{0}\' cloud provider entry in \'{1}\' is '
                            'trying to extend data from \'{2}:{3}\' though '
                            '\'{3}\' is not defined in \'{1}\''.format(
                                details['driver'],
                                provider_alias,
                                alias,
                                provider
                            )
                        )
                    details['extends'] = '{0}:{1}'.format(alias, provider)
                    # change provider details '-only-extendable-' to extended
                    # provider name
                    details['driver'] = provider
                elif providers.get(extends):
                    raise salt.exceptions.SaltCloudConfigError(
                        'The \'{0}\' cloud provider entry in \'{1}\' is '
                        'trying to extend from \'{2}\' and no provider was '
                        'specified. Not extending!'.format(
                            details['driver'], provider_alias, extends
                        )
                    )
                elif extends not in providers:
                    raise salt.exceptions.SaltCloudConfigError(
                        'The \'{0}\' cloud provider entry in \'{1}\' is '
                        'trying to extend data from \'{2}\' though \'{2}\' '
                        'is not defined in the salt cloud providers loaded '
                        'data.'.format(
                            details['driver'], provider_alias, extends
                        )
                    )
                else:
                    if driver in providers.get(extends):
                        details['extends'] = '{0}:{1}'.format(extends, driver)
                    elif '-only-extendable-' in providers.get(extends):
                        details['extends'] = '{0}:{1}'.format(
                            extends, '-only-extendable-{0}'.format(ext_count)
                        )
                    else:
                        # We're still not aware of what we're trying to extend
                        # from. Let's try on next iteration
                        details['extends'] = extends
                        keep_looping = True
        if not keep_looping:
            break

    while True:
        # Merge provided extends
        keep_looping = False
        for alias, entries in six.iteritems(providers.copy()):
            for driver, details in six.iteritems(entries):

                if 'extends' not in details:
                    # Extends resolved or non existing, continue!
                    continue

                if 'extends' in details['extends']:
                    # Since there's a nested extends, resolve this one in the
                    # next iteration
                    keep_looping = True
                    continue

                # Let's get a reference to what we're supposed to extend
                extends = details.pop('extends')
                # Split the setting in (alias, driver)
                ext_alias, ext_driver = extends.split(':')
                # Grab a copy of what should be extended
                extended = providers.get(ext_alias).get(ext_driver).copy()
                # Merge the data to extend with the details
                extended = salt.utils.dictupdate.update(extended, details)
                # Update the providers dictionary with the merged data
                providers[alias][driver] = extended
                # Update name of the driver, now that it's populated with extended information
                if driver.startswith('-only-extendable-'):
                    providers[alias][ext_driver] = providers[alias][driver]
                    # Delete driver with old name to maintain dictionary size
                    del providers[alias][driver]

        if not keep_looping:
            break

    # Now clean up any providers entry that was just used to be a data tree to
    # extend from
    for provider_alias, entries in six.iteritems(providers.copy()):
        for driver, details in six.iteritems(entries.copy()):
            if not driver.startswith('-only-extendable-'):
                continue

            log.info(
                "There's at least one cloud driver under the '%s' "
                'cloud provider alias which does not have the required '
                "'driver' setting. Removing it from the available "
                'providers listing.', provider_alias
            )
            providers[provider_alias].pop(driver)

        if not providers[provider_alias]:
            providers.pop(provider_alias)

    return providers
1165141
def initialise_api(
    debug=False,
    host=None,
    key=None,
    proxy=None,
    user_agent=None,
    headers=None,
    rate_limit=True,
    rate_limit_callback=None,
    error_retry_max=None,
    error_retry_backoff=None,
    error_retry_codes=None,
):
    """"""
    config = cloudsmith_api.Configuration()
    config.debug = debug
    config.host = host if host else config.host
    config.proxy = proxy if proxy else config.proxy
    config.user_agent = user_agent
    config.headers = headers
    config.rate_limit = rate_limit
    config.rate_limit_callback = rate_limit_callback
    config.error_retry_max = error_retry_max
    config.error_retry_backoff = error_retry_backoff
    config.error_retry_codes = error_retry_codes

    if headers:
        if "Authorization" in config.headers:
            encoded = config.headers["Authorization"].split(" ")[1]
            decoded = base64.b64decode(encoded)
            values = decoded.decode("utf-8")
            config.username, config.password = values.split(":")

    set_api_key(config, key)
    return config
851635
def setup_connection():
    

    # get connection parameters, first from environment variables if they are
    # defined, otherwise from .nipaprc
    try:
        con_params = {
            'username': os.getenv('NIPAP_USERNAME') or cfg.get('global', 'username'),
            'password': os.getenv('NIPAP_PASSWORD') or cfg.get('global', 'password'),
            'hostname': os.getenv('NIPAP_HOST') or cfg.get('global', 'hostname'),
            'port'    : os.getenv('NIPAP_PORT') or cfg.get('global', 'port')
        }
    except (configparser.NoOptionError, configparser.NoSectionError) as exc:
        print("ERROR:", str(exc), file=sys.stderr)
        print("HINT: Please define the username, password, hostname and port in your .nipaprc under the section 'global' or provide them through the environment variables NIPAP_HOST, NIPAP_PORT, NIPAP_USERNAME and NIPAP_PASSWORD.", file=sys.stderr)
        sys.exit(1)

    # if we haven't got a password (from env var or config) we interactively
    # prompt for one
    if con_params['password'] is None:
        import getpass
        con_params['password'] = getpass.getpass()

    # build XML-RPC URI
    pynipap.xmlrpc_uri = "http://%(username)s:%(password)s@%(hostname)s:%(port)s" % con_params

    ao = pynipap.AuthOptions({
        'authoritative_source': 'nipap',
        'username': os.getenv('NIPAP_IMPERSONATE_USERNAME') or con_params['username'],
        'full_name': os.getenv('NIPAP_IMPERSONATE_FULL_NAME'),
        })
532808
def server(self, ):
        
        c = connection.ServerConnection3(self)
        with self.mutex:
            self.connections.append(c)
        return c
1111321
def get_providers(self):
        
        if self.providers:
            return self.providers

        providers = dict()
        for provider in self.config:
            configurator = provider.lower() + '_config'
            if not hasattr(self, configurator):
                err = 'Provider [{}] not recognized'.format(provider)
                raise ValueError(err)

            provider_config = self.config[provider]
            configurator = getattr(self, configurator)
            providers[provider] = configurator(
                id=provider_config.get('id'),
                secret=provider_config.get('secret'),
                scope=provider_config.get('scope'),
                offline=provider_config.get('offline')
            )

        self.providers = providers
        return self.providers
1291785
public function createUserService()
    {
        $config = $this->container->get('cca.legacy_dic.contao_config');
        // Work around the fact that \Contao\Database::getInstance() always creates an instance,
        // even when no driver is configured (Database and Config are being imported into the user class and there-
        // fore causing an fatal error).
        if (!$config->get('dbDatabase')) {
            throw new \RuntimeException('Contao Database is not properly configured.');
        }

        $matcher = $this->container->get('contao.routing.scope_matcher');
        $request = $this->container->get('request_stack')->getCurrentRequest();

        // NULL request => CLI mode.
        if ((null === $request) || $matcher->isBackendRequest($request)) {
            return $this->container->get('contao.framework')->createInstance(BackendUser::class);
        }

        if ($matcher->isFrontendRequest($request)) {
            return $this->container->get('contao.framework')->createInstance(FrontendUser::class);
        }

        throw new \RuntimeException('Unknown TL_MODE encountered', 1);
    }
366546
def get_user_data_configuration():
    
    from cloud_inquisitor import get_local_aws_session, app_config

    kms_region = app_config.kms_region
    session = get_local_aws_session()

    if session.get_credentials().method == 'iam-role':
        kms = session.client('kms', region_name=kms_region)
    else:
        sts = session.client('sts')
        audit_role = sts.assume_role(RoleArn=app_config.aws_api.instance_role_arn, RoleSessionName='cloud_inquisitor')
        kms = boto3.session.Session(
            audit_role['Credentials']['AccessKeyId'],
            audit_role['Credentials']['SecretAccessKey'],
            audit_role['Credentials']['SessionToken'],
        ).client('kms', region_name=kms_region)

    user_data_url = app_config.user_data_url
    res = requests.get(user_data_url)

    if res.status_code == 200:
        data = kms.decrypt(CiphertextBlob=b64decode(res.content))
        kms_config = json.loads(zlib.decompress(data['Plaintext']).decode('utf-8'))

        app_config.database_uri = kms_config['db_uri']
    else:
        raise RuntimeError('Failed loading user-data, cannot continue: {}: {}'.format(res.status_code, res.content))
709437
def getUser(cls, cloud):
        
        try:
            config = d = ConfigDict("cloudmesh.yaml")

            d = ConfigDict("cloudmesh.yaml")

            #
            # bug: cloud is none when adding a group
            #

            config = d["cloudmesh"]["clouds"][cloud]
            credentials = config["credentials"]
            cloud_type = config["cm_type"]

            if cloud_type == "openstack":
                return credentials["OS_USERNAME"]
            else:
                raise ValueError("getUser for this cloud type not yet "
                                 "supported: {}".format(cloud))
        except Exception as ex:
            Console.error("problem getting user")