Пример #1
0
    def testDefaultPath_MultiPathsInEnv(self):
        env_path1 = os.path.join(file_utils.GetHomeDir(), 'one_kubeconfig')
        os.environ['KUBECONFIG'] = env_path1
        self.assertEqual(kconfig.Kubeconfig.DefaultPath(), env_path1)

        env_path2 = os.path.join(file_utils.GetHomeDir(), 'another_kubeconfig')
        os.environ['KUBECONFIG'] = os.pathsep.join([env_path2, env_path1])
        self.assertEqual(kconfig.Kubeconfig.DefaultPath(), env_path2)
Пример #2
0
def _GetUserHomeDir():
    if platforms.OperatingSystem.Current(
    ) == platforms.OperatingSystem.WINDOWS:
        # %HOME% has precedence over %USERPROFILE% for files.GetHomeDir().
        # The Docker config resides under %USERPROFILE% on Windows
        return encoding.Decode(os.path.expandvars('%USERPROFILE%'))
    else:
        return files.GetHomeDir()
Пример #3
0
def _get_docker_config(*unused_args, **kwargs):
    force_new = kwargs.get('force_new', False)
    home = files.GetHomeDir()
    new_path = os.path.join(home, '.docker', 'config.json')
    old_path = os.path.join(home, '.dockercfg')
    if os.path.exists(new_path) or force_new:
        return new_path, True
    return old_path, False
Пример #4
0
    def _HandleFileWriteImpl(self,
                             is_binary,
                             path,
                             private=False,
                             append=False,
                             create_path=False):
        """Intercept calls to write files."""
        abs_path = os.path.abspath(path)

        cwd = os.path.abspath(os.getcwd())
        config_dir = os.path.abspath(config.Paths().global_config_dir)
        home_dir = os.path.abspath(files.GetHomeDir())
        is_known_location = (abs_path.startswith(cwd)
                             or abs_path.startswith(home_dir)
                             or abs_path.startswith(config_dir))
        # We have to do this because under tests, all the above are actually under
        # the temp directory because they are mocked out.
        temp_dir = os.path.abspath(tempfile.gettempdir())
        is_temp = abs_path.startswith(temp_dir) and not is_known_location
        is_compute_ssh_hosts_file = path.endswith(
            os.path.join('.ssh', 'google_compute_known_hosts'))

        if not (is_known_location or is_temp or is_compute_ssh_hosts_file):
            raise Error(
                'Command is attempting to write file outside of current '
                'working directory: [{}]'.format(abs_path))

        # Pass through the write like normal
        if is_binary:
            with self._orig_binary_file_writer(path,
                                               private=private,
                                               create_path=create_path) as fw:
                yield fw
        else:
            with self._orig_file_writer(path,
                                        private=private,
                                        append=append,
                                        create_path=create_path) as fw:
                yield fw

        # After they close it, capture what happened.
        if abs_path.startswith(config_dir) or is_temp:
            # Ignore any files written to config or tmp for assertion purposes.
            return

        current_event = self._GetOrCreateNextEvent(
            events_lib.EventType.FILE_WRITTEN)
        if is_binary:
            contents = files.ReadBinaryFileContents(path)
        else:
            contents = files.ReadFileContents(path)

        if abs_path.startswith(home_dir):
            path = '~' + abs_path[len(home_dir):]

        self._Handle(current_event, path, contents, private)
Пример #5
0
 def __init__(self):
     cfg_paths = config.Paths()
     # Ordered list of replacements. First match wins, more specific paths should
     # be placed before more general ones.
     self._replacements = [
         (re.escape(os.path.normpath(cfg_paths.global_config_dir)),
          '${CLOUDSDK_CONFIG}'),
         (re.escape(file_utils.GetHomeDir()), '${HOME}'),
         (re.escape(getpass.getuser()), '${USER}')
     ]
     if cfg_paths.sdk_root:
         self._replacements.append(
             (re.escape(os.path.normpath(cfg_paths.sdk_root)),
              '${SDK_ROOT}'))
Пример #6
0
 def testKubeconfigEnvvar(self):
     default_path = kconfig.Kubeconfig.DefaultPath()
     env_path = os.path.join(file_utils.GetHomeDir(), 'other_kubeconfig')
     file_utils.MakeDir(os.path.dirname(default_path))
     with open(default_path, 'w') as fp:
         fp.write(_EXISTING_KUBECONFIG)
     kubeconfig = kconfig.Kubeconfig.Default()
     self.assertEqual(kubeconfig.current_context, 'existing-context')
     # We overwrite $HOME in base.UnitTestBase.SetUp
     os.environ['KUBECONFIG'] = env_path
     kubeconfig = kconfig.Kubeconfig.Default()
     self.assertEqual(kubeconfig.current_context, '')
     with open(default_path, 'r') as fp:
         self.assertEqual(fp.read(), _EXISTING_KUBECONFIG)
     with open(env_path, 'r') as fp:
         self.assertEqual(fp.read(), _EMPTY_KUBECONFIG)
Пример #7
0
def _GetGlobalConfigDir():
  """Returns the path to the user's global config area.

  Returns:
    str: The path to the user's global config area.
  """
  # Name of the directory that roots a cloud SDK workspace.
  global_config_dir = encoding.GetEncodedValue(os.environ, CLOUDSDK_CONFIG)
  if global_config_dir:
    return global_config_dir
  if platforms.OperatingSystem.Current() != platforms.OperatingSystem.WINDOWS:
    return os.path.join(file_utils.GetHomeDir(), '.config',
                        _CLOUDSDK_GLOBAL_CONFIG_DIR_NAME)
  appdata = encoding.GetEncodedValue(os.environ, 'APPDATA')
  if appdata:
    return os.path.join(appdata, _CLOUDSDK_GLOBAL_CONFIG_DIR_NAME)
  # This shouldn't happen unless someone is really messing with things.
  drive = encoding.GetEncodedValue(os.environ, 'SystemDrive', 'C:')
  return os.path.join(drive, os.path.sep, _CLOUDSDK_GLOBAL_CONFIG_DIR_NAME)
Пример #8
0
def _GetAndUpdateRcPath(completion_update, path_update, rc_path, host_os):
    """Returns an rc path based on the default rc path or user input.

  Gets default rc path based on environment. If prompts are enabled,
  allows user to update to preferred file path. Otherwise, prints a warning
  that the default rc path will be updated.

  Args:
    completion_update: bool, Whether or not to do command completion.
    path_update: bool, Whether or not to update PATH.
    rc_path: str, the rc path given by the user, from --rc-path arg.
    host_os: str, The host os identification string.

  Returns:
    str, A path to the rc file to update.
  """
    # If we aren't updating the RC file for either completions or PATH, there's
    # no point.
    if not (completion_update or path_update):
        return None
    if rc_path:
        return rc_path
    # A first guess at user preferred shell.
    preferred_shell = _GetPreferredShell(
        encoding.GetEncodedValue(os.environ, 'SHELL', '/bin/sh'))
    default_rc_path = os.path.join(
        files.GetHomeDir(), _GetShellRcFileName(preferred_shell, host_os))
    # If in quiet mode, we'll use default path.
    if not console_io.CanPrompt():
        _TraceAction(
            'You specified that you wanted to update your rc file. The '
            'default file will be updated: [{rc_path}]'.format(
                rc_path=default_rc_path))
        return default_rc_path
    rc_path_update = console_io.PromptResponse(
        ('The Google Cloud SDK installer will now prompt you to update an rc '
         'file to bring the Google Cloud CLIs into your environment.\n\n'
         'Enter a path to an rc file to update, or leave blank to use '
         '[{rc_path}]:  ').format(rc_path=default_rc_path))
    return (files.ExpandHomeDir(rc_path_update)
            if rc_path_update else default_rc_path)
Пример #9
0
def _DockerRunOptions(enable_gpu=False,
                      container_home_to_mount=None,
                      extra_run_opts=None):
    """Returns a list of 'docker run' options.

  Args:
    enable_gpu: (bool) using GPU or not
    container_home_to_mount: (str) $HOME directory in the container
    extra_run_opts: (List[str]) other custom docker run options
  """
    if extra_run_opts is None:
        extra_run_opts = []

    runtime = ["--runtime", "nvidia"] if enable_gpu else []

    mount = []
    if container_home_to_mount is not None:
        mount = [
            "-v", "{}:{}".format(files.GetHomeDir(), container_home_to_mount)
        ]

    return ["--rm"] + runtime + mount + ["--ipc", "host"] + extra_run_opts
Пример #10
0
 def testProcessHomeFileURI(self):
   self.assertEqual(
       'file://${HOME}',
       self.anonymizer.ProcessURL('file://' + file_utils.GetHomeDir()))
Пример #11
0
def _ParameterizePath(path):
    """Return path with $HOME prefix replaced by ~."""
    home = files.GetHomeDir() + os.path.sep
    if path.startswith(home):
        return '~' + os.path.sep + path[len(home):]
    return path
CONTEXT_AWARE_ACCESS_DENIED_ERROR = 'access_denied'
CONTEXT_AWARE_ACCESS_DENIED_ERROR_DESCRIPTION = 'Account restricted'
CONTEXT_AWARE_ACCESS_HELP_MSG = (
    'Access was blocked due to an organization policy, please contact your '
    'admin to gain access.'
)


def IsContextAwareAccessDeniedError(exc):
  exc_text = six.text_type(exc)
  return (CONTEXT_AWARE_ACCESS_DENIED_ERROR in exc_text and
          CONTEXT_AWARE_ACCESS_DENIED_ERROR_DESCRIPTION in exc_text)


DEFAULT_AUTO_DISCOVERY_FILE_PATH = os.path.join(
    files.GetHomeDir(), '.secureConnect', 'context_aware_metadata.json')


def _AutoDiscoveryFilePath():
  """Return the file path of the context aware configuration file."""
  # auto_discovery_file_path is an override used for testing purposes.
  cfg_file = properties.VALUES.context_aware.auto_discovery_file_path.Get()
  if cfg_file is not None:
    return cfg_file
  return DEFAULT_AUTO_DISCOVERY_FILE_PATH


class ConfigException(exceptions.Error):

  def __init__(self):
    super(ConfigException, self).__init__(
Пример #13
0
from __future__ import division
from __future__ import unicode_literals

import atexit
import io
import json
import os

from googlecloudsdk.core import config
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import execution_utils
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.util import files

DEFAULT_AUTO_DISCOVERY_FILE_PATH = os.path.join(files.GetHomeDir(),
                                                '.secureConnect',
                                                'context_aware_metadata.json')


def _AutoDiscoveryFilePath():
    """Return the file path of the context aware configuration file."""
    # auto_discovery_file_path is an override used for testing purposes.
    cfg_file = properties.VALUES.context_aware.auto_discovery_file_path.Get()
    if cfg_file is not None:
        return cfg_file
    return DEFAULT_AUTO_DISCOVERY_FILE_PATH


def _SplitPemIntoSections(contents):
    """Returns dict with {name: section} by parsing contents in PEM format.
Пример #14
0
 def testProcessFakeHomePath(self):
   home_path = file_utils.GetHomeDir() + '_other'
   self.assertEqual('${HOME}_other', self.anonymizer.ProcessPath(home_path))
Пример #15
0
 def testProcessHomePath(self):
   self.assertEqual(
       '${HOME}',
       self.anonymizer.ProcessPath(file_utils.GetHomeDir()))
Пример #16
0
 def testProcessFakeHomeFileURI(self):
   home_uri = 'file://' + file_utils.GetHomeDir() + '_other'
   self.assertEqual(
       'file://${HOME}_other',
       self.anonymizer.ProcessURL(home_uri))
Пример #17
0
 def testProcessHomePath_NonNormalized(self):
   self.assertEqual(
       '${HOME}',
       self.anonymizer.ProcessPath(
           os.path.join(file_utils.GetHomeDir(), 'tmp', '..')))
Пример #18
0
 def testProcessHomeFileURI_NonNormalized(self):
   self.assertEqual(
       'file://${HOME}',
       self.anonymizer.ProcessURL(
           os.path.join('file://' + file_utils.GetHomeDir(), 'tmp', '..')))
Пример #19
0
 def SetUp(self):
     self.boto_path = os.path.join(files.GetHomeDir(), '.boto')
     self._CleanupBotoConfig()