def WriteAuthorizedSshKeysFile(
      self, authorized_keys_file, ssh_keys, uid, gid):
    """Update the authorized_keys_file to contain the given ssh_keys.

    Arguments:
      authorized_keys_file: The name of the authorized keys file.
      ssh_keys: The google added ssh keys for the file.
      uid: The uid for the user.
      gid: The gid for the user.
    """
    # Create a temp file to store the new keys.
    with self.system.CreateTempFile(delete=False) as keys_file:
      new_keys_path = keys_file.name
      # Read all the ssh keys in the original key file if it exists.
      if self.os.path.exists(authorized_keys_file):
        with self.system.OpenFile(authorized_keys_file, 'r') as original_keys:
          original_keys.seek(0)
          lines = original_keys.readlines()
      else:
        lines = []

      # Pull out the # Added by Google lines.
      google_added_ixs = [i for i in range(len(lines) - 1) if
                          lines[i].startswith('# Added by Google')]
      google_added_ixs += [i + 1 for i in google_added_ixs]

      user_lines = [
          lines[i] for i in range(len(lines)) if i not in google_added_ixs]

      # First write user's entries.
      for user_line in user_lines:
        keys_file.write(EnsureTrailingNewline(user_line))

      # Put google entries at the end, each preceeded by Added by Google.
      for ssh_key in ssh_keys:
        keys_file.write('# Added by Google\n')
        keys_file.write(EnsureTrailingNewline(ssh_key))

      # Check that we have enough disk space to move the file.
      stat = self.os.statvfs(self.os.path.dirname(authorized_keys_file))
      available_space = stat.f_bavail * stat.f_bsize
      required_space = self.os.path.getsize(new_keys_path) + 1024 * 1024
      logging.debug('Writing keys file: %s bytes required; %s available.',
                    required_space, available_space)
      if available_space < required_space:
        raise IOError('Disk is too full')

    try:
      # Override the old authorized keys file with the new one.
      self.system.MoveFile(new_keys_path, authorized_keys_file)
    finally:
      try:
        self.system.DeleteFile(new_keys_path)
      except:
        pass

    # Make sure the authorized_keys_file has the right perms (u+rw).
    self.os.chmod(authorized_keys_file, 0600)
    self.os.chown(authorized_keys_file, uid, gid)

    # Set SELinux context, if applicable to this system
    self.SetSELinuxContext(authorized_keys_file)
dataset/ETHPy150Open GoogleCloudPlatform/compute-image-packages/google-daemon/usr/share/google/google_daemon/accounts.py/Accounts.WriteAuthorizedSshKeysFile/original