Exemplo n.º 1
0
    def Run(self, args):
        """Run 'instance-groups add-service'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'unmanaged set-named-ports].')
        client = self.context['instanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        get_request = client.getService(project=project,
                                        zone=args.zone,
                                        resourceView=args.name)

        try:
            get_response = get_request.execute()
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)

        request_body = {}
        request_body['fingerprint'] = get_response['fingerprint']

        endpoints = None
        if 'endpoints' in get_response:
            endpoints = get_response['endpoints']

        request_body['endpoints'] = service_util.AddServiceToEndpoints(
            args.service, args.port, endpoints)

        set_request = client.setService(project=project,
                                        zone=args.zone,
                                        resourceView=args.name,
                                        body=request_body)

        try:
            set_request.execute()
            log.Print('Service {0}:{1} added.'.format(args.service, args.port))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 2
0
  def Run(self, args):
    """Run 'instance group get'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      The object representing the instance group.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
    log.warn('Please use instead [gcloud compute instance-groups '
             'unmanaged describe].')
    client = self.context['instanceGroupsClient']
    project = properties.VALUES.core.project.Get(required=True)

    request = client.get(
        project=project, zone=args.zone, resourceView=args.name)

    try:
      response = request.execute()
      if not args.format:
        util.PrettyPrint(response, 'yaml')
      return response
    except errors.HttpError as error:
      raise exceptions.HttpException(util.GetError(error))
    except errors.Error as error:
      raise exceptions.ToolException(error)
Exemplo n.º 3
0
    def Run(self, args):
        """Run 'replicapool resize'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      An object representing the service response obtained by the Resize
      API if the Resize call was successful.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        client = self.context['replicapool']
        project = properties.VALUES.core.project.Get(required=True)

        request = client.pools().resize(projectName=project,
                                        zone=args.zone,
                                        poolName=args.pool,
                                        numReplicas=args.new_size)

        try:
            request.execute()
            log.Print('Replica pool {0} is being resized.'.format(args.pool))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 4
0
    def Run(self, args):
        """Run 'replicapool get'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.

    Returns:
      The get API's response
    """
        client = self.context['replicapool']
        project = properties.VALUES.core.project.Get(required=True)

        request = client.pools().get(projectName=project,
                                     zone=args.zone,
                                     poolName=args.pool)

        try:
            response = request.execute()
            util.PrettyPrint(response, args.format or 'yaml')
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 5
0
    def Run(self, args):
        """Run 'managed-instance-groups describe'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.

    Returns:
      response: the response returned by the service, expected to be a
          zonal operation resource
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'managed describe].')
        client = self.context['managedInstanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        request = client.instanceGroupManagers().get(
            project=project, zone=args.zone, instanceGroupManager=args.group)

        try:
            response = request.execute()
            util.PrettyPrint(response, args.format or 'yaml')
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 6
0
    def Run(self, args):
        """Run 'instance-groups list-services'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      the API response.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'unmanaged get-named-ports].')
        client = self.context['instanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)
        get_request = client.getService(project=project,
                                        zone=args.zone,
                                        resourceView=args.name)

        try:
            response = get_request.execute()
            util.PrettyPrint(response)
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 7
0
    def Run(self, args):
        """Run 'replicapool delete'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        client = self.context['replicapool']
        project = properties.VALUES.core.project.Get(required=True)

        delete_body = {}
        if args.abandon_instance:
            delete_body['abandonInstances'] = args.abandon_instance

        request = client.pools().delete(projectName=project,
                                        zone=args.zone,
                                        poolName=args.pool,
                                        body=delete_body)

        try:
            request.execute()
            log.Print('Replica pool {0} is being deleted.'.format(args.pool))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 8
0
    def Run(self, args):
        """Run 'instance-groups delete'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'unmanaged delete].')
        client = self.context['instanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        for group_name in args.name:
            request = client.delete(project=project,
                                    zone=args.zone,
                                    resourceView=group_name)

            try:
                request.execute()
                log.Print('Instance group {0} deleted.'.format(group_name))
            except errors.HttpError as error:
                raise exceptions.HttpException(util.GetError(error))
            except errors.Error as error:
                raise exceptions.ToolException(error)
Exemplo n.º 9
0
    def Run(self, args):
        """Run 'managed-instance-groups list'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      An object representing the service response obtained by the List
      API if the List call was successful.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'managed list].')
        client = self.context['managedInstanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        limit = util.SanitizeLimitFlag(args.limit)

        # TODO(user): Add filter support later.
        request = client.instanceGroupManagers().list(project=project,
                                                      zone=args.zone)

        results = []
        try:
            response = request.execute()
            self.AppendResults(results, response)
            while response and 'nextPageToken' in response and len(
                    results) < limit:
                request = client.instanceGroupManagers().list(
                    project=project,
                    zone=args.zone,
                    pageToken=response['nextPageToken'])

                response = request.execute()
                self.AppendResults(results, response)

            if len(results) > limit:
                results = results[0:limit]

            return results
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 10
0
    def Run(self, args):
        """Run 'resourceviews resources add'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        zone_views_client = self.context['zoneViewsClient']
        project = properties.VALUES.core.project.Get(required=True)

        if args.region:
            raise exceptions.ToolException(
                ValueError(
                    'addinstance must be used against a zonal resourceview'))

        instance_urls = []
        for instance in args.resource:
            instance_urls.append(
                'https://www.googleapis.com/compute/v1/projects/' + project +
                '/zones/' + args.zone + '/instances/' + instance)
        request_body = {'resources': instance_urls}

        if 'v1beta1' in args.api_version:
            request = zone_views_client.addresources(
                projectName=project,
                zone=args.zone,
                resourceViewName=args.resourceview,
                body=request_body)
        else:
            request = zone_views_client.addResources(
                project=project,
                zone=args.zone,
                resourceView=args.resourceview,
                body=request_body)

        try:
            request.execute()
            log.Print('Instances added to resource view {0}.'.format(
                args.resourceview))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 11
0
    def Run(self, args):
        """Run 'managed-instance-groups set-template'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      An object representing the service response obtained by the Get
      API if the Get call was successful.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.

    Returns:
      response: the response returned by the service, expected to be a
          zonal operation resource
    """
        client = self.context['managedInstanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        # TODO(user): Use resources.Create(...).
        template_url = ('https://www.googleapis.com/compute/v1/'
                        'projects/{0}/global/instanceTemplates/{1}')

        request_body = {
            'instanceTemplate': template_url.format(project, args.template)
        }
        request = client.instanceGroupManagers().setInstanceTemplate(
            project=project,
            zone=args.zone,
            instanceGroupManager=args.group,
            body=request_body)

        try:
            response = request.execute()
            log.Print(
                'Instance template {0} set for managed instance group {1}.'.
                format(args.template, args.group))
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 12
0
    def Run(self, args):
        """Run 'resourceviews resources add'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        zone_views_client = self.context['zoneViewsClient']
        region_views_client = self.context['regionViewsClient']

        project = properties.VALUES.core.project.Get(required=True)

        request_body = {'resources': args.resource}
        if 'v1beta1' in args.api_version:
            if args.region:
                request = region_views_client.addresources(
                    projectName=project,
                    region=args.region,
                    resourceViewName=args.resourceview,
                    body=request_body)
            else:
                request = zone_views_client.addresources(
                    projectName=project,
                    zone=args.zone,
                    resourceViewName=args.resourceview,
                    body=request_body)
        else:
            request = zone_views_client.addResources(
                project=project,
                zone=args.zone,
                resourceView=args.resourceview,
                body=request_body)

        try:
            request.execute()
            log.Print('Resources added to resource view {0}.'.format(
                args.resourceview))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 13
0
    def Run(self, args):
        """Run 'replicapool create'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        client = self.context['replicapool']
        project = properties.VALUES.core.project.Get(required=True)

        template = replica_template_util.ParseTemplate(
            args.template,
            params=args.param,
            params_from_file=args.param_from_file)

        new_replicapool = {
            'name': args.pool,
            'description': args.description,
            'numReplicas': args.size,
            'autoRestart': True,
            'template': template['template']
        }
        if args.no_auto_restart:
            new_replicapool['autoRestart'] = False
        if args.target_pools:
            new_replicapool['targetPools'] = args.target_pools
        if args.resource_views:
            new_replicapool['resourceViews'] = args.resource_views

        request = client.pools().insert(projectName=project,
                                        zone=args.zone,
                                        body=new_replicapool)

        try:
            request.execute()
            log.Print('Replica pool {0} is being created.'.format(args.pool))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 14
0
    def Run(self, args):
        """Run 'resourceviews create'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        zone_views_client = self.context['zoneViewsClient']
        # remove the regional service client when v1beta1 is deprecated.
        region_views_client = self.context['regionViewsClient']

        project = properties.VALUES.core.project.Get(required=True)

        new_resourceview = {
            'name': args.name,
            'description': args.description,
        }

        if 'v1beta1' in args.api_version:
            if args.region:
                request = region_views_client.insert(projectName=project,
                                                     region=args.region,
                                                     body=new_resourceview)
            else:
                request = zone_views_client.insert(projectName=project,
                                                   zone=args.zone,
                                                   body=new_resourceview)
        else:
            request = zone_views_client.insert(project=project,
                                               zone=args.zone,
                                               body=new_resourceview)

        try:
            request.execute()
            log.Print('Resource view {0} created.'.format(args.name))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 15
0
    def Run(self, args):
        """Run 'resourceviews get'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      The object representing the resource views.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        zone_views_client = self.context['zoneViewsClient']
        region_views_client = self.context['regionViewsClient']

        project = properties.VALUES.core.project.Get(required=True)

        if 'v1beta1' in args.api_version:
            if args.region:
                request = region_views_client.get(projectName=project,
                                                  region=args.region,
                                                  resourceViewName=args.name)
            else:
                request = zone_views_client.get(projectName=project,
                                                zone=args.zone,
                                                resourceViewName=args.name)
        else:
            request = zone_views_client.get(project=project,
                                            zone=args.zone,
                                            resourceView=args.name)

        try:
            response = request.execute()
            if not args.format:
                util.PrettyPrint(response, 'yaml')
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 16
0
    def Run(self, args):
        """Run 'managed-instance-groups recreate-instances'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.

    Returns:
      response: the response returned by the service, expected to be a
          zonal operation resource
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'managed recreate-instances].')
        client = self.context['managedInstanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        request_body = {}
        instances = []
        for instance in args.instance:
            instances.append(instance)
        request_body['instances'] = instances

        request = client.instanceGroupManagers().recreateInstances(
            project=project,
            zone=args.zone,
            instanceGroupManager=args.group,
            body=request_body)

        try:
            response = request.execute()
            log.Print(('Instances {0} are being recreated in group {1}. '
                       'Operation: {2}').format(args.instance, args.group,
                                                response['name']))
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 17
0
    def Run(self, args):
        """Run 'instance-groups instances remove'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'unmanaged remove-instances].')
        client = self.context['instanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        instance_urls = []
        if args.urls:
            instance_urls = args.instances
        else:
            for instance in args.instances:
                instance_urls.append(
                    'https://www.googleapis.com/compute/v1/projects/' +
                    project + '/zones/' + args.zone + '/instances/' + instance)

        request_body = {'resources': instance_urls}

        request = client.removeResources(project=project,
                                         zone=args.zone,
                                         resourceView=args.group,
                                         body=request_body)

        try:
            request.execute()
            log.Print('Instances removed from instance group {0}.'.format(
                args.group))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 18
0
    def Run(self, args):
        """Run 'managed-instance-group resize'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      An object representing the service response obtained by the Resize
      API if the Resize call was successful.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.

    Returns:
      response: the response returned by the service, expected to be a
          zonal operation resource
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'managed resize].')
        client = self.context['managedInstanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        request = client.instanceGroupManagers().resize(
            project=project,
            zone=args.zone,
            instanceGroupManager=args.group,
            size=args.new_size)

        try:
            response = request.execute()
            log.Print(('Managed instance group {0} is being resized. '
                       'Operation: {1}').format(args.group, response['name']))
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 19
0
  def Run(self, args):
    """Run 'instance-groups create'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
    log.warn('Please use instead [gcloud compute instance-groups '
             'unmanaged create].')
    client = self.context['instanceGroupsClient']
    project = properties.VALUES.core.project.Get(required=True)

    new_instance_group = {
        'name': args.name,
        'description': args.description,
    }
    compute_api_version = 'v1'

    if args.network:
      network_url = ('https://www.googleapis.com/compute/{0}/'
                     'projects/{1}/global/networks/{2}')
      new_instance_group['network'] = network_url.format(
          compute_api_version, project, args.network)

    request = client.insert(
        project=project, zone=args.zone, body=new_instance_group)

    try:
      request.execute()
      log.Print('Instance group {0} created.'.format(args.name))
    except errors.HttpError as error:
      raise exceptions.HttpException(util.GetError(error))
    except errors.Error as error:
      raise exceptions.ToolException(error)
Exemplo n.º 20
0
    def Run(self, args):
        """Run 'instance-groups list'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      A list object representing the instance groups obtained by the List
      operation if the List API call was successful.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'unmanaged list].')
        limit = util.SanitizeLimitFlag(args.limit)

        request = self.BuildRequest(args)
        results = []
        try:
            response = request.execute()
            self.AppendResults(results, response)
            while response and 'nextPageToken' in response and len(
                    results) < limit:
                request = self.BuildRequest(args, response['nextPageToken'])
                response = request.execute()
                self.AppendResults(results, response)

            if len(results) > limit:
                results = results[0:limit]

            return results
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 21
0
    def Run(self, args):
        """Run 'replicapool update-template'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      An object representing the service response obtained by the Get
      API if the Get call was successful.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.
    """
        client = self.context['replicapool']
        project = properties.VALUES.core.project.Get(required=True)

        template = replica_template_util.ParseTemplate(
            args.template,
            params=args.param,
            params_from_file=args.param_from_file)

        request = client.pools().updatetemplate(projectName=project,
                                                zone=args.zone,
                                                poolName=args.pool,
                                                body=template['template'])

        try:
            request.execute()
            log.Print('Template updated for replica pool {0}.'.format(
                args.pool))
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 22
0
    def Run(self, args):
        """Run 'managed-instance-groups create'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.

    Returns:
      response: the response returned by the service, expected to be a
          zonal operation resource
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'managed create].')
        client = self.context['managedInstanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        # TODO(user): Replace this with an actual call to the GCE Zones.Get() API
        # Truncate last two letters of zone to get region
        # e.g. us-central1 for us-central1-a
        region = args.zone[0:-2]
        target_pool_url = ('https://www.googleapis.com/compute/v1/'
                           'projects/{0}/regions/{1}/targetPools/{2}')

        # TODO(user): Replace this with an actual call to the GCE
        # InstanceTemplates.Get() API
        template_url = ('https://www.googleapis.com/compute/v1/'
                        'projects/{0}/global/instanceTemplates/{1}')

        new_group = {
            'name': args.group,
            'description': args.description,
            'instanceTemplate': template_url.format(project, args.template),
            'baseInstanceName': args.base_instance_name
        }

        if args.target_pool:
            target_pools = []
            for target_pool in args.target_pool:
                target_pools.append(
                    target_pool_url.format(project, region, target_pool))
            new_group['targetPools'] = target_pools

        request = client.instanceGroupManagers().insert(project=project,
                                                        zone=args.zone,
                                                        size=args.size,
                                                        body=new_group)

        try:
            response = request.execute()
            log.Print(('Managed instance group {0} is being created. '
                       'Operation: {1}').format(args.group, response['name']))
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)
Exemplo n.º 23
0
    def Run(self, args):
        """Run 'managed-instance-groups set-target-pools'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      An object representing the service response obtained by the Get
      API if the Get call was successful.

    Raises:
      HttpException: A http error response was received while executing api
          request.
      ToolException: An error other than http error occured while executing
          the command.

    Returns:
      response: the response returned by the service, expected to be a
          zonal operation resource
    """
        log.warn('Please use instead [gcloud compute instance-groups '
                 'managed set-target-pools].')
        client = self.context['managedInstanceGroupsClient']
        project = properties.VALUES.core.project.Get(required=True)

        get_request = client.instanceGroupManagers().get(
            project=project, zone=args.zone, instanceGroupManager=args.group)

        fingerprint = None
        try:
            group = get_request.execute()
            fingerprint = group['fingerprint']
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)

        # TODO(user): Replace this with an actual call to the GCE Zones.Get() API
        # Truncate last two letters of zone to get region
        # e.g. us-central1 for us-central1-a
        region = args.zone[0:-2]

        target_pool_url = ('https://www.googleapis.com/compute/v1/'
                           'projects/{0}/regions/{1}/targetPools/{2}')

        target_pools = []
        for target_pool in args.target_pool:
            target_pools.append(
                target_pool_url.format(project, region, target_pool))

        request_body = {
            'fingerprint': fingerprint,
            'targetPools': target_pools
        }

        request = client.instanceGroupManagers().setTargetPools(
            project=project,
            zone=args.zone,
            instanceGroupManager=args.group,
            body=request_body)

        try:
            response = request.execute()
            log.Print(
                'Target pools set for managed instance group {0}.'.format(
                    args.group))
            return response
        except errors.HttpError as error:
            raise exceptions.HttpException(util.GetError(error))
        except errors.Error as error:
            raise exceptions.ToolException(error)