Exemple #1
0
    def ReadFromDisk(cls, path=None):
        """Reads configuration file and meta-data from default Docker location.

    Reads configuration file and meta-data from default Docker location. Returns
    a Configuration object containing the full contents of the configuration
    file, and the configuration file path.

    Args:
      path: string, path to look for the Docker config file. If empty will
      attempt to read from the new config location (default).

    Returns:
      A Configuration object

    Raises:
      ValueError: path or is_new_format are not set.
      InvalidDockerConfigError: config file could not be read as JSON.
    """
        path = path or client_utils.GetDockerConfigPath(True)[0]
        try:
            content = client_utils.ReadConfigurationFile(path)
        except (ValueError, client_utils.DockerError) as err:
            raise client_utils.InvalidDockerConfigError(
                ('Docker configuration file [{}] could not be read as JSON: {}'
                 ).format(path, str(err)))

        return cls(content, path)
 def WriteNewDockerConfig(self, contents):
     new_cfg, unused_true = client_lib.GetDockerConfigPath(force_new=True)
     directory = os.path.dirname(new_cfg)
     if not os.path.exists(directory):
         os.makedirs(directory)
     files.WriteFileContents(new_cfg, contents, private=True)
     return new_cfg
 def TearDown(self):
     for new_path in [True, False]:
         dcfg, unused_new_file = client_lib.GetDockerConfigPath(new_path)
         # If we created .dockercfg and/or .docker/config.json,
         # clear it to reset for the next test.
         if os.path.exists(dcfg):
             os.remove(dcfg)
 def TouchOldDockerConfig(self):
     cfg, new_format = client_lib.GetDockerConfigPath(force_new=False)
     self.assertFalse(new_format)
     directory = os.path.dirname(cfg)
     if not os.path.exists(directory):
         os.makedirs(directory)
     files.WriteFileContents(cfg, '{}', private=True)
     return cfg
 def WriteNewDockerConfig(self, full_cfg):
     new_cfg, unused_true = client_lib.GetDockerConfigPath(force_new=True)
     directory = os.path.dirname(new_cfg)
     if not os.path.exists(directory):
         os.makedirs(directory)
     files.WriteFileContents(new_cfg,
                             encoding.Decode(json.dumps(full_cfg)),
                             private=True)
Exemple #6
0
def ReadDockerAuthConfig():
    """Retrieve the contents of the Docker authorization entry.

  NOTE: This is public only to facilitate testing.

  Returns:
    The map of authorizations used by docker.
  """
    # Not using DockerConfigInfo here to be backward compatible with
    # UpdateDockerCredentials which should still work if Docker is not installed
    path, new_format = client_lib.GetDockerConfigPath()
    structure = client_lib.ReadConfigurationFile(path)
    if new_format:
        return structure['auths'] if 'auths' in structure else {}
    else:
        return structure
Exemple #7
0
def WriteDockerAuthConfig(structure):
    """Write out a complete set of Docker authorization entries.

  This is public only to facilitate testing.

  Args:
    structure: The dict of authorization mappings to write to the
               Docker configuration file.
  """
    # Not using DockerConfigInfo here to be backward compatible with
    # UpdateDockerCredentials which should still work if Docker is not installed
    path, is_new_format = client_lib.GetDockerConfigPath()
    contents = client_lib.ReadConfigurationFile(path)
    if is_new_format:
        full_cfg = contents
        full_cfg['auths'] = structure
        file_contents = json.dumps(full_cfg, indent=2)
    else:
        file_contents = json.dumps(structure, indent=2)
    files.WriteFileAtomically(path, file_contents)
    def testGetDockerConfigPathReturnsCorrectDockerHomePath(self):
        # This test verifies that we locate the user's 'home directory' in the same
        # way as the Docker client:
        # https://docs.docker.com/engine/reference/commandline/login/

        dockercfg_path, _ = client_lib.GetDockerConfigPath(True)

        # The user's 'home directory' should be the temp folder that our mocks
        # return.
        self.assertTrue(dockercfg_path.startswith(self.home_path))

        if self.IsOnWindows():
            self.assertTrue(self.mock_expandvars.called)
            self.assertFalse(self.mock_get_home_path.called)
            self.mock_expandvars.assert_called_with('%USERPROFILE%')
        else:
            # Every platform aside from Windows should use files.GetHomeDir
            # to locate the user's home directory.
            self.assertTrue(self.mock_get_home_path.called)
            self.assertFalse(self.mock_expandvars.called)
Exemple #9
0
def _GCRCredHelperConfigured():
    """Returns True if docker-credential-gcr is the docker credential store.

  Returns:
    True if docker-credential-gcr is specified in the docker config.
    False if the config file does not exist, does not contain a
    'credsStore' key, or if the credstore is not docker-credential-gcr.
  """
    try:
        # Not using DockerConfigInfo here to be backward compatible with
        # UpdateDockerCredentials which should still work if Docker is not installed
        path, is_new_format = client_lib.GetDockerConfigPath()
        contents = client_lib.ReadConfigurationFile(path)
        if is_new_format and (_CREDENTIAL_STORE_KEY in contents):
            return contents[_CREDENTIAL_STORE_KEY] == 'gcr'
        else:
            # Docker <1.7.0 (no credential store support) or credsStore == null
            return False
    except IOError:
        # Config file doesn't exist or can't be parsed.
        return False
Exemple #10
0
def _CredentialStoreConfigured():
    """Returns True if a credential store is specified in the docker config.

  Returns:
    True if a credential store is specified in the docker config.
    False if the config file does not exist or does not contain a
    'credsStore' key.
  """
    try:
        # Not Using DockerConfigInfo here to be backward compatiable with
        # UpdateDockerCredentials which should still work if Docker is not installed
        path, is_new_format = client_lib.GetDockerConfigPath()
        contents = client_lib.ReadConfigurationFile(path)
        if is_new_format:
            return _CREDENTIAL_STORE_KEY in contents
        else:
            # The old format is for Docker <1.7.0.
            # Older Docker clients (<1.11.0) don't support credential helpers.
            return False
    except IOError:
        # Config file doesn't exist.
        return False
    def testGetDockerConfigPathRespectsDockerConfigEnvVar(self):
        self.StartEnvPatch({'DOCKER_CONFIG': 'custom_directory'})
        dockercfg_path, _ = client_lib.GetDockerConfigPath(True)

        self.assertEqual(os.path.join('custom_directory', 'config.json'),
                         dockercfg_path)
 def testGetDockerConfigPathOldPath(self):
     self.StartEnvPatch({'DOCKER_CONFIG': ''})
     dockercfg_path, is_new_path = client_lib.GetDockerConfigPath()
     self.assertFalse(is_new_path)
     self.assertTrue('.dockercfg' in dockercfg_path)