Return a dict of environment variables required to run a service under faketime.
552164
def get_environment_vars(filename):
    """"""
    if sys.platform == "linux" or sys.platform == "linux2":
        return {
            'LD_PRELOAD': path.join(LIBFAKETIME_DIR, "libfaketime.so.1"),
            'FAKETIME_SKIP_CMDS': 'nodejs',     # node doesn't seem to work in the current version.
            'FAKETIME_TIMESTAMP_FILE': filename,
        }
    elif sys.platform == "darwin":
        return {
            'DYLD_INSERT_LIBRARIES': path.join(LIBFAKETIME_DIR, "libfaketime.1.dylib"),
            'DYLD_FORCE_FLAT_NAMESPACE': '1',
            'FAKETIME_TIMESTAMP_FILE': filename,
        }
    else:
        raise RuntimeError("libfaketime does not support '{}' platform".format(sys.platform))
588695
def to_envvars(self):
        
        export = {}
        for prop_name in self.profile_properties:
            prop = self._get_prop(prop_name)
            value = self[prop_name]
            if value is not None:
                export[prop.get_envvar(self)] = prop.to_str(self, value)
        if self._profile_parent_name:
            export[
                f"{self._envvar_prefix}PARENT_PROFILE".upper()
            ] = self._profile_parent_name
        return export
863779
def _required_envs(env_vars):
    
    envs = {
        key: os.environ.get(key)
        for key in env_vars
    }

    # Check for missing keys
    missing = [key for key, val in list(envs.items()) if val is None]
    if missing:
        msg = (
            u"These environment variables must be set: " + u", ".join(missing)
        )
        raise BrowserConfigError(msg)

    # Check that we support this browser
    if envs['SELENIUM_BROWSER'] not in BROWSERS:
        msg = u"Unsuppported browser: {0}".format(envs['SELENIUM_BROWSER'])
        raise BrowserConfigError(msg)

    return envs
738772
def from_env_vars(self) -> None:
        """"""
        for key, value in os.environ.items():
            if key.startswith('KUYRUK_'):
                key = key[7:]
                if hasattr(Config, key):
                    try:
                        value = ast.literal_eval(value)
                    except (ValueError, SyntaxError):
                        pass

                    self._setattr(key, value)
1252417
def get_settings_from_environment(environ):
    ''''''
    settings = {}
    for name, value in environ.items():
        if not name.startswith('DJANGO_'):
            continue
        name = name.replace('DJANGO_', '', 1)
        if _ignore_setting(name):
            continue
        try:
            settings[name] = ast.literal_eval(value)
        except (SyntaxError, ValueError) as err:
            LOGGER.warn("Unable to parse setting %s=%s (%s)", name, value, err)
    return settings
793744
def check_environment(provider_conf):
    """"""
    session = get_session()
    image_id = check_glance(session, provider_conf.image)
    flavor_to_id, id_to_flavor = check_flavors(session)
    ext_net, network, subnet = check_network(
        session,
        provider_conf.configure_network,
        provider_conf.network,
        subnet=provider_conf.subnet,
        dns_nameservers=provider_conf.dns_nameservers,
        allocation_pool=provider_conf.allocation_pool)

    return {
        'session': session,
        'image_id': image_id,
        'flavor_to_id': flavor_to_id,
        'id_to_flavor': id_to_flavor,
        'ext_net': ext_net,
        'network': network,
        'subnet': subnet
    }
392301
def get_environ(self):
        """"""
        ssl_environ = {
            'HTTPS': 'on',
            # pyOpenSSL doesn't provide access to any of these AFAICT
            # 'SSL_PROTOCOL': 'SSLv2',
            # SSL_CIPHER    string  The cipher specification name
            # SSL_VERSION_INTERFACE     string  The mod_ssl program version
            # SSL_VERSION_LIBRARY   string  The OpenSSL program version
        }

        if self.certificate:
            # Server certificate attributes
            cert = open(self.certificate, 'rb').read()
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
            ssl_environ.update({
                'SSL_SERVER_M_VERSION': cert.get_version(),
                'SSL_SERVER_M_SERIAL': cert.get_serial_number(),
                # 'SSL_SERVER_V_START':
                #   Validity of server's certificate (start time),
                # 'SSL_SERVER_V_END':
                #   Validity of server's certificate (end time),
            })

            for prefix, dn in [
                ('I', cert.get_issuer()),
                ('S', cert.get_subject()),
            ]:
                # X509Name objects don't seem to have a way to get the
                # complete DN string. Use str() and slice it instead,
                # because str(dn) == "<X509Name object '/C=US/ST=...'>"
                dnstr = str(dn)[18:-2]

                wsgikey = 'SSL_SERVER_%s_DN' % prefix
                ssl_environ[wsgikey] = dnstr

                # The DN should be of the form: /k1=v1/k2=v2, but we must allow
                # for any value to contain slashes itself (in a URL).
                while dnstr:
                    pos = dnstr.rfind('=')
                    dnstr, value = dnstr[:pos], dnstr[pos + 1:]
                    pos = dnstr.rfind('/')
                    dnstr, key = dnstr[:pos], dnstr[pos + 1:]
                    if key and value:
                        wsgikey = 'SSL_SERVER_%s_DN_%s' % (prefix, key)
                        ssl_environ[wsgikey] = value

        return ssl_environ
324742
def jinja_env(self):
        """"""
        if self._jinja_env is None:
            self._jinja_env = SandboxedEnvironment(
                extensions=[
                    'jinja2.ext.autoescape', 'jinja2.ext.with_', ],
                autoescape=True,
            )
            self._jinja_env.globals['url_for'] = url_for
            # Load whitelisted configuration variables.
            for var in self.app.config['PAGES_WHITELIST_CONFIG_KEYS']:
                self._jinja_env.globals[var] = self.app.config.get(var)
        return self._jinja_env
1129024
def valid_envs(self, service_name):
    
    service_record = self.service_record(service_name)
    if service_record is None:
      raise RuntimeError("service registry doesn't have service: {}".format(service_name))

    # Return empty list if service has no "environments" section
    if not (service_record.has_key("environments")):
      return []
    # Otherwise gather up the envs
    service_record_envs = service_record["environments"]
    result = []
    for service_env in service_record_envs:
      if service_env not in EFConfig.PROTECTED_ENVS and service_env in EFConfig.EPHEMERAL_ENVS:
        result.extend((lambda env=service_env: [env + str(x) for x in range(EFConfig.EPHEMERAL_ENVS[env])])())
      else:
        result.append(service_env)
    return result
128247
def get_environ(self):
        """"""
        req = self.req
        env_10 = WSGIGateway_10.get_environ(self)
        env = dict([(k.decode('ISO-8859-1'), v) for k, v in env_10.iteritems()])
        env[u'wsgi.version'] = ('u', 0)
        
        # Request-URI
        env.setdefault(u'wsgi.url_encoding', u'utf-8')
        try:
            for key in [u"PATH_INFO", u"SCRIPT_NAME", u"QUERY_STRING"]:
                env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
        except UnicodeDecodeError:
            # Fall back to latin 1 so apps can transcode if needed.
            env[u'wsgi.url_encoding'] = u'ISO-8859-1'
            for key in [u"PATH_INFO", u"SCRIPT_NAME", u"QUERY_STRING"]:
                env[key] = env_10[str(key)].decode(env[u'wsgi.url_encoding'])
        
        for k, v in sorted(env.items()):
            if isinstance(v, str) and k not in ('REQUEST_URI', 'wsgi.input'):
                env[k] = v.decode('ISO-8859-1')
        
        return env
723131
def get_service_env_value(self, key):
        
        service_key = predix.config.get_env_key(self, key)
        value = os.environ[service_key]
        if not value:
            raise ValueError("%s env unset" % key)
        return value
1371546
def get_environ(self, sock):
        """"""
        cipher = sock.cipher()
        ssl_environ = {
            'wsgi.url_scheme': 'https',
            'HTTPS': 'on',
            'SSL_PROTOCOL': cipher[1],
            'SSL_CIPHER': cipher[0],
            # SSL_VERSION_INTERFACE     string  The mod_ssl program version
            # SSL_VERSION_LIBRARY   string  The OpenSSL program version
        }

        if self.context and self.context.verify_mode != ssl.CERT_NONE:
            client_cert = sock.getpeercert()
            if client_cert:
                for cert_key, env_var in self.CERT_KEY_TO_ENV.items():
                    ssl_environ.update(
                        self.env_dn_dict(env_var, client_cert.get(cert_key)),
                    )

        return ssl_environ
351759
def _build_environ(self) -> Dict[str, Optional[str]]:
        
        d: Dict[str, Optional[str]] = {}

        if self.__config__.case_insensitive:
            env_vars = {k.lower(): v for k, v in os.environ.items()}
        else:
            env_vars = cast(Dict[str, str], os.environ)

        for field in self.__fields__.values():
            if field.has_alias:
                env_name = field.alias
            else:
                env_name = self.__config__.env_prefix + field.name.upper()

            env_name_ = env_name.lower() if self.__config__.case_insensitive else env_name
            env_val = env_vars.get(env_name_, None)

            if env_val:
                if field.is_complex():
                    try:
                        env_val = json.loads(env_val)
                    except ValueError as e:
                        raise SettingsError(f'error parsing JSON for "{env_name}"') from e
                d[field.alias] = env_val
        return d
1322346
def _get_service_config(self):
        
        # Should work for windows, osx, and linux environments
        if not os.path.exists(self.config_path):
            try:
                os.makedirs(os.path.dirname(self.config_path))
            except OSError as exc:
                if exc.errno != errno.EEXIST:
                    raise

            return {}

        with open(self.config_path, 'r') as data:
            return json.load(data)
754277
def _parse_service_env_vars(self, env_vars):
        
        env = {}
        for var in env_vars:
            # Yeah yeah.. it's less performant.. splitting twice.. who cares.
            k, v = var.split('=')
            env.update({k: v})
        return env
440067
def _get_explicit_environ_credentials():
    """"""
    explicit_file = os.environ.get(environment_vars.CREDENTIALS)

    if explicit_file is not None:
        credentials, project_id = _load_credentials_from_file(
            os.environ[environment_vars.CREDENTIALS])

        return credentials, project_id

    else:
        return None, None
1071405
def _optional_envs():
    
    envs = {
        key: os.environ.get(key)
        for key in OPTIONAL_ENV_VARS
        if key in os.environ
    }

    # If we're using Jenkins, check that we have all the required info
    if 'JOB_NAME' in envs and 'BUILD_NUMBER' not in envs:
        raise BrowserConfigError("Missing BUILD_NUMBER environment var")

    if 'BUILD_NUMBER' in envs and 'JOB_NAME' not in envs:
        raise BrowserConfigError("Missing JOB_NAME environment var")

    return envs