Пример #1
0
def WriteToFileOrStdout(path,
                        content,
                        overwrite=True,
                        binary=False,
                        private=False):
    """Writes content to the specified file or stdout if path is '-'.

  Args:
    path: str, The path of the file to write.
    content: str, The content to write to the file.
    overwrite: bool, Whether or not to overwrite the file if it exists.
    binary: bool, True to open the file in binary mode.
    private: bool, Whether to write the file in private mode.

  Raises:
    Error: If the file cannot be written.
  """
    if path == '-':
        if binary:
            files.WriteStreamBytes(sys.stdout, content)
        else:
            out.write(content)
    elif binary:
        files.WriteBinaryFileContents(path,
                                      content,
                                      overwrite=overwrite,
                                      private=private)
    else:
        files.WriteFileContents(path,
                                content,
                                overwrite=overwrite,
                                private=private)
Пример #2
0
def ClusterConnectionInfo(cluster_ref):
    """Get the info we need to use to connect to a GKE cluster.

  Arguments:
    cluster_ref: reference to the cluster to connect to.
  Yields:
    A tuple of (endpoint, ca_certs), where endpoint is the ip address
    of the GKE main, and ca_certs is the absolute path of a temporary file
    (lasting the life of the python process) holding the ca_certs to connect to
    the GKE cluster.
  Raises:
    NoCaCertError: if the cluster is missing certificate authority data.
  """
    with _DisableUserProjectQuota():
        adapter = api_adapter.NewAPIAdapter('v1')
        cluster = adapter.GetCluster(cluster_ref)
    auth = cluster.mainAuth
    if auth and auth.clusterCaCertificate:
        ca_data = auth.clusterCaCertificate
    else:
        # This should not happen unless the cluster is in an unusual error
        # state.
        raise NoCaCertError('Cluster is missing certificate authority data.')
    fd, filename = tempfile.mkstemp()
    os.close(fd)
    files.WriteBinaryFileContents(filename,
                                  base64.b64decode(ca_data),
                                  private=True)
    try:
        yield cluster.endpoint, filename
    finally:
        os.remove(filename)
Пример #3
0
  def _LoadClusterDetails(self):
    """Get the current cluster and its connection info from the kubeconfig.

    Yields:
      A tuple of (endpoint, ca_certs), where endpoint is the ip address
      of the GKE main, and ca_certs is the absolute path of a temporary file
      (lasting the life of the python process) holding the ca_certs to connect
      to the GKE cluster.
    Raises:
      flags.KubeconfigError: if the config file has missing keys or values.
    """
    try:
      curr_ctx = self.kubeconfig.contexts[self.kubeconfig.current_context]
      self.cluster = self.kubeconfig.clusters[curr_ctx['context']['cluster']]
      ca_data = self.cluster['cluster']['certificate-authority-data']
      parsed_server = urlparse.urlparse(self.cluster['cluster']['server'])
      endpoint = parsed_server.hostname
    except KeyError as e:
      raise flags.KubeconfigError('Missing key `{}` in kubeconfig.'.format(
          e.args[0]))

    fd, filename = tempfile.mkstemp()
    os.close(fd)
    files.WriteBinaryFileContents(
        filename, base64.b64decode(ca_data), private=True)
    try:
      yield endpoint, filename
    finally:
      os.remove(filename)
Пример #4
0
 def _createSingleTestInitialStateFile(self, file_name, suffix):
     # create a temporary file in self.dir, set the content equals to file_name.
     path = os.path.join(self.dir.path, file_name.decode('utf-8') + suffix)
     file_utils.WriteBinaryFileContents(path,
                                        _FILE_CONTENT,
                                        overwrite=False)
     return path
Пример #5
0
 def Execute(self, scenario_context):
     full_path = os.path.join(os.getcwd(), self._path)
     files.MakeDir(os.path.dirname(full_path))
     if self._binary_contents:
         files.WriteBinaryFileContents(full_path, self._binary_contents)
     else:
         rrr = scenario_context.resource_ref_resolver
         files.WriteFileContents(full_path, rrr.Resolve(self._contents))
 def _GenerateHtmlNav(self, directory, cli, hidden, restrict):
   """Generates html nav files in directory."""
   tree = CommandTreeGenerator(cli).Walk(hidden, restrict)
   with files.FileWriter(os.path.join(directory, '_menu_.html')) as out:
     self.WriteHtmlMenu(tree, out)
   for file_name in _HELP_HTML_DATA_FILES:
     file_contents = pkg_resources.GetResource(
         'googlecloudsdk.api_lib.meta.help_html_data.', file_name)
     files.WriteBinaryFileContents(os.path.join(directory, file_name),
                                   file_contents)
 def GenerateHtmlNav(directory):
     """Generates html nav files in directory."""
     tree = walker_util.CommandTreeGenerator(
         self._cli_power_users_only).Walk(args.hidden, args.restrict)
     with files.FileWriter(os.path.join(directory,
                                        '_menu_.html')) as out:
         WriteHtmlMenu(tree, out)
     for file_name in _HELP_HTML_DATA_FILES:
         file_contents = pkg_resources.GetResource(
             'googlecloudsdk.api_lib.meta.help_html_data.', file_name)
         files.WriteBinaryFileContents(
             os.path.join(directory, file_name), file_contents)
Пример #8
0
    def WriteTemplate(self):
        """Write the credential file."""

        # General credentials used by bq and gsutil.
        if self.credentials_type != creds.CredentialType.P12_SERVICE_ACCOUNT:
            SaveCredentialsAsADC(self.credentials, self._adc_path)

            if self.credentials_type == creds.CredentialType.USER_ACCOUNT:
                # We create a small .boto file for gsutil, to be put in BOTO_PATH.
                # Our client_id and client_secret should accompany our refresh token;
                # if a user loaded any other .boto files that specified a different
                # id and secret, those would override our id and secret, causing any
                # attempts to obtain an access token with our refresh token to fail.
                self._WriteFileContents(
                    self._gsutil_path, '\n'.join([
                        '[OAuth2]',
                        'client_id = {cid}',
                        'client_secret = {secret}',
                        '',
                        '[Credentials]',
                        'gs_oauth2_refresh_token = {token}',
                    ]).format(cid=config.CLOUDSDK_CLIENT_ID,
                              secret=config.CLOUDSDK_CLIENT_NOTSOSECRET,
                              token=self.credentials.refresh_token))
            elif self.credentials_type == creds.CredentialType.SERVICE_ACCOUNT:
                self._WriteFileContents(
                    self._gsutil_path, '\n'.join([
                        '[Credentials]',
                        'gs_service_key_file = {key_file}',
                    ]).format(key_file=self._adc_path))
            else:
                raise CredentialFileSaveError(
                    'Unsupported credentials type {0}'.format(
                        type(self.credentials)))
        else:  # P12 service account
            cred = self.credentials
            key = cred._private_key_pkcs12  # pylint: disable=protected-access
            password = cred._private_key_password  # pylint: disable=protected-access
            files.WriteBinaryFileContents(self._p12_key_path,
                                          key,
                                          private=True)

            # the .boto file gets some different fields
            self._WriteFileContents(
                self._gsutil_path, '\n'.join([
                    '[Credentials]',
                    'gs_service_client_id = {account}',
                    'gs_service_key_file = {key_file}',
                    'gs_service_key_file_password = {key_password}',
                ]).format(account=self.credentials.service_account_email,
                          key_file=self._p12_key_path,
                          key_password=password))
Пример #9
0
 def _WriteDataIfNoFile(self, f, d):
   if f:
     yield f
   elif d:
     fd, f = tempfile.mkstemp()
     os.close(fd)
     try:
       files.WriteBinaryFileContents(f, base64.b64decode(d), private=True)
       yield f
     finally:
       os.remove(f)
   else:
     yield None
Пример #10
0
    def _LoadClusterDetails(self):
        """Get the current cluster and its connection info from the kubeconfig.

    Yields:
      A tuple of (endpoint, ca_certs), where endpoint is the ip address
      of the GKE master, and ca_certs is the absolute path of a temporary file
      (lasting the life of the python process) holding the ca_certs to connect
      to the GKE cluster.
    Raises:
      flags.KubeconfigError: if the config file has missing keys or values.
    """
        try:
            if self.context:
                curr_ctx_name = self.context
            else:
                curr_ctx_name = self.config['current-context']
            curr_ctx = next((c for c in self.config['contexts']
                             if c['name'] == curr_ctx_name), None)
            if not curr_ctx:
                raise flags.KubeconfigError(
                    'Count not find context [{}] in kubeconfig.'.format(
                        curr_ctx_name))

            self.cluster = next(
                (c for c in self.config['clusters']
                 if c['name'] == curr_ctx['context']['cluster']), None)
            if not self.cluster:
                raise flags.KubeconfigError(
                    'Could not find cluster [{}] specified by context [{}] in '
                    'kubeconfig.'.format(curr_ctx['context']['cluster'],
                                         curr_ctx_name))

            ca_data = self.cluster['cluster']['certificate-authority-data']
            endpoint = self.cluster['cluster']['server'].replace(
                'https://', '')
        except KeyError as e:
            raise flags.KubeconfigError(
                'Missing key `{}` in kubeconfig.'.format(e.args[0]))

        fd, filename = tempfile.mkstemp()
        os.close(fd)
        files.WriteBinaryFileContents(filename,
                                      base64.b64decode(ca_data),
                                      private=True)
        try:
            yield endpoint, filename
        finally:
            os.remove(filename)
Пример #11
0
 def Run(self, args):
     if args.devsite_dir:
         walker_util.DevSiteGenerator(self._cli_power_users_only,
                                      args.devsite_dir).Walk(
                                          args.hidden, args.restrict)
     if args.help_text_dir:
         walker_util.HelpTextGenerator(self._cli_power_users_only,
                                       args.help_text_dir).Walk(
                                           args.hidden, args.restrict)
     if args.html_dir:
         walker_util.HtmlGenerator(self._cli_power_users_only,
                                   args.html_dir).Walk(
                                       args.hidden, args.restrict)
         tree = walker_util.CommandTreeGenerator(
             self._cli_power_users_only).Walk(args.hidden, args.restrict)
         with files.FileWriter(os.path.join(args.html_dir,
                                            '_menu_.html')) as out:
             WriteHtmlMenu(tree, out)
         for file_name in _HELP_HTML_DATA_FILES:
             file_contents = pkg_resources.GetResource(
                 'googlecloudsdk.api_lib.meta.help_html_data.', file_name)
             files.WriteBinaryFileContents(
                 os.path.join(args.html_dir, file_name), file_contents)
     if args.manpage_dir:
         walker_util.ManPageGenerator(self._cli_power_users_only,
                                      args.manpage_dir).Walk(
                                          args.hidden, args.restrict)
     if args.update_help_text_dir:
         # The help text golden files are always ascii.
         console_attr.ResetConsoleAttr(encoding='ascii')
         changes = help_util.HelpTextUpdater(self._cli_power_users_only,
                                             args.update_help_text_dir,
                                             test=args.test).Update(
                                                 args.restrict)
         if changes and args.test:
             raise HelpTextOutOfDateError(
                 'Help text files must be updated.')