Exemplo n.º 1
0
def _DeduceRegionInProject(resources, current_project, disk_resource, dummy,
                           region, region_name, replica_zones):
    """Deduce region from zones in given project."""
    # parse all --replica-zones, consuming project from above
    current_zones = [
        resources.Parse(zone,
                        collection='compute.zones',
                        params={'project': current_project})
        for zone in replica_zones
    ]
    # check if all zones live in disks' project
    for zone in current_zones:
        if zone.project != current_project:
            raise exceptions.InvalidArgumentException(
                '--zone',
                'Zone [{}] lives in different project than disk [{}].'.format(
                    str(zone.SelfLink()), str(disk_resource.SelfLink())))
    # check if all zones live in the same region
    for i in range(len(current_zones) - 1):
        if (utils.ZoneNameToRegionName(current_zones[i].zone) !=
                utils.ZoneNameToRegionName(current_zones[i + 1].zone)):
            raise exceptions.InvalidArgumentException('--replica-zones', (
                'Zones [{}, {}] live in different regions [{}, {}], but should '
                'live in the same.').format(
                    current_zones[i].zone, current_zones[i + 1].zone,
                    utils.ZoneNameToRegionName(current_zones[i].zone),
                    utils.ZoneNameToRegionName(current_zones[i + 1].zone)))
    # check if --replica-zones is consistent with --region
    result = utils.ZoneNameToRegionName(current_zones[0].zone)
    if region is not None and region_name != dummy and region_name != result:
        raise exceptions.InvalidArgumentException(
            '--replica-zones',
            ('Region from [--replica-zones] ({}) is different from [--region] '
             '({}).').format(result, region_name))
    return result
Exemplo n.º 2
0
def GetComputeResources(release_track, cluster_name):
    """Returns a resources object with resolved GCE zone and region."""
    holder = compute_base.ComputeApiHolder(release_track)
    region_prop = properties.VALUES.compute.region
    zone_prop = properties.VALUES.compute.zone
    resources = holder.resources

    # Prompt for scope if necessary
    zone = properties.VALUES.compute.zone.Get()
    if not zone:
        _, zone = scope_prompter.PromptForScope(
            resource_name='cluster',
            underspecified_names=[cluster_name],
            scopes=[compute_scope.ScopeEnum.ZONE],
            default_scope=None,
            scope_lister=flags.GetDefaultScopeLister(holder.client))
        if not zone:
            # Still no zone, just raise error generated by this property.
            zone = properties.VALUES.compute.zone.GetOrFail()

    zone_ref = resources.Parse(zone,
                               params={
                                   'project':
                                   properties.VALUES.core.project.GetOrFail,
                               },
                               collection='compute.zones')

    zone_name = zone_ref.Name()
    zone_prop.Set(zone_name)
    region_name = compute_utils.ZoneNameToRegionName(zone_name)
    region_prop.Set(region_name)

    return resources
Exemplo n.º 3
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        messages = holder.client.messages

        node_group_ref = flags.MakeNodeGroupArg().ResolveAsResource(
            args,
            holder.resources,
            scope_lister=compute_flags.GetDefaultScopeLister(holder.client))
        node_template_ref = util.ParseNodeTemplate(
            holder.resources,
            args.node_template,
            project=node_group_ref.project,
            region=compute_utils.ZoneNameToRegionName(node_group_ref.zone))

        node_group = messages.NodeGroup(
            name=node_group_ref.Name(),
            description=args.description,
            nodeTemplate=node_template_ref.SelfLink())
        request = messages.ComputeNodeGroupsInsertRequest(
            nodeGroup=node_group,
            initialNodeCount=args.target_size,
            project=node_group_ref.project,
            zone=node_group_ref.zone)

        service = holder.client.apitools_client.nodeGroups
        return client.MakeRequests([(service, 'Insert', request)])[0]
    def CreateRequests(self, args):
        resource_arg = instance_groups_flags.ZONAL_INSTANCE_GROUP_MANAGER_ARG
        default_scope = flags.ScopeEnum.ZONE
        scope_lister = flags.GetDefaultScopeLister(self.compute_client,
                                                   self.project)
        ref = resource_arg.ResolveAsResource(args,
                                             self.resources,
                                             default_scope=default_scope,
                                             scope_lister=scope_lister)
        region = utils.ZoneNameToRegionName(ref.zone)
        pool_refs = []
        for target_pool in args.target_pools:
            pool_refs.append(
                self.resources.Parse(target_pool,
                                     collection='compute.targetPools',
                                     params={'region': region}))

        pools = [pool_ref.SelfLink() for pool_ref in pool_refs]
        request = (
            self.messages.ComputeInstanceGroupManagersSetTargetPoolsRequest(
                instanceGroupManager=ref.Name(),
                instanceGroupManagersSetTargetPoolsRequest=(
                    self.messages.InstanceGroupManagersSetTargetPoolsRequest(
                        targetPools=pools, )),
                project=self.project,
                zone=ref.zone,
            ))
        return [request]
Exemplo n.º 5
0
def ParseDiskResource(resources, name, project, zone, type_):
    """Parses disk resources.

  Project and zone are ignored if a fully-qualified resource name is given, i.e.
    - https://compute.googleapis.com/compute/v1/projects/my-project
          /zones/us-central1-a/disks/disk-1
    - projects/my-project/zones/us-central1-a/disks/disk-1

  If project and zone cannot be parsed, we will use the given project and zone
  as fallbacks.

  Args:
    resources: resources.Registry, The resource registry
    name: str, name of the disk.
    project: str, project of the disk.
    zone: str, zone of the disk.
    type_: ScopeEnum, type of the disk.

  Returns:
    A disk resource.
  """
    if type_ == compute_scopes.ScopeEnum.REGION:
        return resources.Parse(name,
                               collection='compute.regionDisks',
                               params={
                                   'project': project,
                                   'region': utils.ZoneNameToRegionName(zone)
                               })
    else:
        return resources.Parse(name,
                               collection='compute.disks',
                               params={
                                   'project': project,
                                   'zone': zone
                               })
    def CreateNetworkInterfaceMessage(self, args, instance_refs):
        """Returns a new NetworkInterface message."""
        region = utils.ZoneNameToRegionName(instance_refs[0].zone)

        network_interface = None
        if args.subnet is not None:
            subnet_ref = self.CreateRegionalReference(
                args.subnet, region, resource_type='subnetworks')
            network_interface = self.messages.NetworkInterface(
                subnetwork=subnet_ref.SelfLink())
        else:
            network_ref = self.CreateGlobalReference(args.network,
                                                     resource_type='networks')
            network_interface = self.messages.NetworkInterface(
                network=network_ref.SelfLink())

        if not args.no_address:
            access_config = self.messages.AccessConfig(
                name=constants.DEFAULT_ACCESS_CONFIG_NAME,
                type=self.messages.AccessConfig.TypeValueValuesEnum.
                ONE_TO_ONE_NAT)

            # If the user provided an external IP, populate the access
            # config with it.
            # TODO(b/25278937): plays poorly when creating multiple instances
            if len(instance_refs) == 1:
                address = self.ExpandAddressFlag(args, region)
                if address:
                    access_config.natIP = address

            network_interface.accessConfigs = [access_config]

        return network_interface
Exemplo n.º 7
0
    def CreateRequests(self, args):
        instance_refs = self.CreateZonalReferences(args.instances,
                                                   args.zone,
                                                   resource_type='instances')

        instances = [
            self.messages.InstanceReference(instance=instance_ref.SelfLink())
            for instance_ref in instance_refs
        ]

        # This check to make sure the regions for the instances are the same is not
        # really necessary, but it does allow for a fast fail if the user passes in
        # instances from different regions.
        unique_regions = set(
            utils.ZoneNameToRegionName(instance_ref.zone)
            for instance_ref in instance_refs)

        if len(unique_regions) > 1:
            raise calliope_exceptions.ToolException(
                'Instances must all be in the same region as the target pool.')

        target_pool_ref = self.CreateRegionalReference(
            args.name, unique_regions.pop(), resource_type='targetPools')

        request = self.messages.ComputeTargetPoolsRemoveInstanceRequest(
            region=target_pool_ref.region,
            project=self.project,
            targetPool=target_pool_ref.Name(),
            targetPoolsRemoveInstanceRequest=(
                self.messages.TargetPoolsRemoveInstanceRequest(
                    instances=instances)))

        return [request]
Exemplo n.º 8
0
 def ResolveGceUris(self, cluster_name, image, master_machine_type,
                    worker_machine_type, network, subnetwork):
     """Build dict of GCE URIs for Dataproc cluster request."""
     zone_ref = self._GetZoneRef(cluster_name)
     zone = zone_ref.Name()
     region = compute_utils.ZoneNameToRegionName(zone)
     uris = {
         'image':
         self._GetResourceUri(image, 'images'),
         'master_machine_type':
         self._GetResourceUri(master_machine_type,
                              'machineTypes',
                              zone=zone),
         'worker_machine_type':
         self._GetResourceUri(worker_machine_type,
                              'machineTypes',
                              zone=zone),
         'network':
         self._GetResourceUri(network, 'networks'),
         'subnetwork':
         self._GetResourceUri(subnetwork, 'subnetworks', region=region),
         'zone':
         zone_ref.SelfLink(),
     }
     return uris
Exemplo n.º 9
0
def GetRegionalTarget(client,
                      resources,
                      args,
                      forwarding_rule_ref=None,
                      allow_global_target=False):
    """Return the forwarding target for a regionally scoped request."""
    _ValidateRegionalArgs(args, allow_global_target)
    if forwarding_rule_ref:
        region_arg = forwarding_rule_ref.region
        project_arg = forwarding_rule_ref.project
    else:
        region_arg = args.region
        project_arg = None

    if args.target_pool:
        if not args.target_pool_region and region_arg:
            args.target_pool_region = region_arg
        target_ref = flags.TARGET_POOL_ARG.ResolveAsResource(
            args,
            resources,
            scope_lister=compute_flags.GetDefaultScopeLister(client))
        target_region = target_ref.region
    elif args.target_instance:
        target_ref = flags.TARGET_INSTANCE_ARG.ResolveAsResource(
            args,
            resources,
            scope_lister=_GetZonesInRegionLister(
                ['--target-instance-zone'], region_arg, client, project_arg
                or properties.VALUES.core.project.GetOrFail()))
        target_region = utils.ZoneNameToRegionName(target_ref.zone)
    elif getattr(args, 'target_vpn_gateway', None):
        if not args.target_vpn_gateway_region and region_arg:
            args.target_vpn_gateway_region = region_arg
        target_ref = flags.TARGET_VPN_GATEWAY_ARG.ResolveAsResource(
            args, resources)
        target_region = target_ref.region
    elif getattr(args, 'backend_service', None):
        if not args.backend_service_region and region_arg:
            args.backend_service_region = region_arg
        target_ref = flags.BACKEND_SERVICE_ARG.ResolveAsResource(
            args, resources)
        target_region = target_ref.region
    elif args.target_http_proxy:
        target_ref = flags.TARGET_HTTP_PROXY_ARG.ResolveAsResource(
            args, resources)
        target_region = region_arg
    elif args.target_https_proxy:
        target_ref = flags.TARGET_HTTPS_PROXY_ARG.ResolveAsResource(
            args, resources)
        target_region = region_arg
    elif args.target_ssl_proxy:
        target_ref = flags.TARGET_SSL_PROXY_ARG.ResolveAsResource(
            args, resources)
        target_region = region_arg
    elif args.target_tcp_proxy:
        target_ref = flags.TARGET_TCP_PROXY_ARG.ResolveAsResource(
            args, resources)
        target_region = region_arg

    return target_ref, target_region
    def CreateRequests(self, args):
        instance_refs = self.CreateZonalReferences(args.instances,
                                                   args.zone,
                                                   resource_type='instances')

        instances = [
            self.messages.InstanceReference(instance=instance_ref.SelfLink())
            for instance_ref in instance_refs
        ]

        unique_regions = set(
            utils.ZoneNameToRegionName(instance_ref.zone)
            for instance_ref in instance_refs)

        # Check that all regions are the same.
        if len(unique_regions) > 1:
            raise calliope_exceptions.ToolException(
                'Instances must all be in the same region as the target pool.')

        target_pool_ref = self.CreateRegionalReference(
            args.name, unique_regions.pop(), resource_type='targetPools')

        request = self.messages.ComputeTargetPoolsAddInstanceRequest(
            region=target_pool_ref.region,
            project=self.project,
            targetPool=target_pool_ref.Name(),
            targetPoolsAddInstanceRequest=(
                self.messages.TargetPoolsAddInstanceRequest(
                    instances=instances)))
        return [request]
Exemplo n.º 11
0
def ValidateManagedInstanceGroupScopeArgs(args, resources):
    """Validate arguments specifying scope of the managed instance group."""
    ignored_required_params = {'project': 'fake'}
    if args.zones and args.zone:
        raise exceptions.ConflictingArgumentsException('--zone', '--zones')
    zone_names = []
    for zone in args.zones:
        zone_ref = resources.Parse(zone,
                                   collection='compute.zones',
                                   params=ignored_required_params)
        zone_names.append(zone_ref.Name())

    zone_regions = set([utils.ZoneNameToRegionName(z) for z in zone_names])
    if len(zone_regions) > 1:
        raise exceptions.InvalidArgumentException(
            '--zones', 'All zones must be in the same region.')
    elif len(zone_regions) == 1 and args.region:
        zone_region = zone_regions.pop()
        region_ref = resources.Parse(args.region,
                                     collection='compute.regions',
                                     params=ignored_required_params)
        region = region_ref.Name()
        if zone_region != region:
            raise exceptions.InvalidArgumentException(
                '--zones', 'Specified zones not in specified region.')
  def Create(self, neg_ref, neg_type, network_endpoint_type, default_port=None,
             network=None, subnet=None):
    """Creates a network endpoint group."""
    network_uri = None
    if network:
      network_ref = self.resources.Parse(network, {'project': neg_ref.project},
                                         collection='compute.networks')
      network_uri = network_ref.SelfLink()
    subnet_uri = None
    if subnet:
      region = api_utils.ZoneNameToRegionName(neg_ref.zone)
      subnet_ref = self.resources.Parse(
          subnet,
          {'project': neg_ref.project, 'region': region},
          collection='compute.subnetworks')
      subnet_uri = subnet_ref.SelfLink()

    type_enum = self.messages.NetworkEndpointGroup.TypeValueValuesEnum
    endpoint_type_enum = (self.messages.NetworkEndpointGroup
                          .NetworkEndpointTypeValueValuesEnum)
    network_endpoint_group = self.messages.NetworkEndpointGroup(
        name=neg_ref.Name(),
        type=arg_utils.ChoiceToEnum(neg_type, type_enum),
        networkEndpointType=arg_utils.ChoiceToEnum(
            network_endpoint_type, endpoint_type_enum),
        loadBalancer=self.messages.NetworkEndpointGroupLbNetworkEndpointGroup(
            defaultPort=default_port,
            network=network_uri,
            subnetwork=subnet_uri))
    request = self.messages.ComputeNetworkEndpointGroupsInsertRequest(
        networkEndpointGroup=network_endpoint_group,
        project=neg_ref.project,
        zone=neg_ref.zone)

    return self.client.MakeRequests([(self._service, 'Insert', request)])[0]
Exemplo n.º 13
0
 def _GetRegionName(self, igm_ref):
   if igm_ref.Collection() == 'compute.instanceGroupManagers':
     return utils.ZoneNameToRegionName(igm_ref.zone)
   elif igm_ref.Collection() == 'compute.regionInstanceGroupManagers':
     return igm_ref.region
   else:
     raise ValueError('Unknown reference type {0}'.format(
         igm_ref.Collection()))
def ParseDiskResource(resources, name, zone, type_):
    if type_ == compute_scopes.ScopeEnum.REGION:
        return resources.Parse(
            name,
            collection='compute.regionDisks',
            params={'region': utils.ZoneNameToRegionName(zone)})
    else:
        return resources.Parse(name,
                               collection='compute.disks',
                               params={'zone': zone})
Exemplo n.º 15
0
    def Run(self, args):
        """Issues a TargetPools.RemoveInstance request."""
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        if args.zone and not args.instances_zone:
            args.instances_zone = args.zone
            log.warning(
                'The --zone flag is deprecated. Use equivalent '
                '--instances-zone=%s flag.', args.instances_zone)

        instance_refs = self.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=compute_flags.GetDefaultScopeLister(client))

        instances = [
            client.messages.InstanceReference(instance=instance_ref.SelfLink())
            for instance_ref in instance_refs
        ]

        # This check to make sure the regions for the instances are the same is not
        # really necessary, but it does allow for a fast fail if the user passes in
        # instances from different regions.
        unique_regions = set(
            utils.ZoneNameToRegionName(instance_ref.zone)
            for instance_ref in instance_refs)

        if len(unique_regions) > 1:
            raise calliope_exceptions.ToolException(
                'Instances must all be in the same region as the target pool.')

        region = unique_regions.pop()

        # Check that the region of the instances is the same as target pool region.
        if args.region and region != args.region:
            raise calliope_exceptions.ToolException(
                'Instances must all be in the same region as the target pool.')

        args.region = region

        target_pool_ref = self.TARGET_POOL_ARG.ResolveAsResource(
            args, holder.resources)

        request = client.messages.ComputeTargetPoolsRemoveInstanceRequest(
            region=target_pool_ref.region,
            project=target_pool_ref.project,
            targetPool=target_pool_ref.Name(),
            targetPoolsRemoveInstanceRequest=(
                client.messages.TargetPoolsRemoveInstanceRequest(
                    instances=instances)))

        return client.MakeRequests([(client.apitools_client.targetPools,
                                     'RemoveInstance', request)])
Exemplo n.º 16
0
def _GetOSUpgradeRegion(args):  # pylint:disable=unused-argument
  """Return region to run OS upgrade in.

  Args:
    args: command args

  Returns:
    str: region. Can be empty.
  """
  if args.zone:
    return utils.ZoneNameToRegionName(args.zone)
  return ''
Exemplo n.º 17
0
    def CreateRequests(self, args):
        resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
        default_scope = compute_scope.ScopeEnum.ZONE
        scope_lister = flags.GetDefaultScopeLister(self.compute_client)
        group_ref = resource_arg.ResolveAsResource(args,
                                                   self.resources,
                                                   default_scope=default_scope,
                                                   scope_lister=scope_lister)

        if group_ref.Collection() == 'compute.instanceGroupManagers':
            region = utils.ZoneNameToRegionName(group_ref.zone)
        else:
            region = group_ref.region

        pool_refs = []
        for target_pool in args.target_pools:
            pool_refs.append(
                self.resources.Parse(
                    target_pool,
                    params={
                        'project': properties.VALUES.core.project.GetOrFail,
                        'region': region
                    },
                    collection='compute.targetPools'))
        pools = [pool_ref.SelfLink() for pool_ref in pool_refs]

        if group_ref.Collection() == 'compute.instanceGroupManagers':
            service = self.compute.instanceGroupManagers
            request = (self.messages.
                       ComputeInstanceGroupManagersSetTargetPoolsRequest(
                           instanceGroupManager=group_ref.Name(),
                           instanceGroupManagersSetTargetPoolsRequest=(
                               self.messages.
                               InstanceGroupManagersSetTargetPoolsRequest(
                                   targetPools=pools, )),
                           project=group_ref.project,
                           zone=group_ref.zone,
                       ))
        else:
            service = self.compute.regionInstanceGroupManagers
            request = (
                self.messages.
                ComputeRegionInstanceGroupManagersSetTargetPoolsRequest(
                    instanceGroupManager=group_ref.Name(),
                    regionInstanceGroupManagersSetTargetPoolsRequest=(
                        self.messages.
                        RegionInstanceGroupManagersSetTargetPoolsRequest(
                            targetPools=pools, )),
                    project=group_ref.project,
                    region=group_ref.region,
                ))
        return [(service, self.method, request)]
Exemplo n.º 18
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG
        default_scope = compute_scope.ScopeEnum.ZONE
        scope_lister = flags.GetDefaultScopeLister(client)
        group_ref = resource_arg.ResolveAsResource(args,
                                                   holder.resources,
                                                   default_scope=default_scope,
                                                   scope_lister=scope_lister)

        if group_ref.Collection() == 'compute.instanceGroupManagers':
            region = utils.ZoneNameToRegionName(group_ref.zone)
        else:
            region = group_ref.region

        pool_refs = []
        for target_pool in args.target_pools:
            pool_refs.append(
                holder.resources.Parse(target_pool,
                                       params={
                                           'project': group_ref.project,
                                           'region': region
                                       },
                                       collection='compute.targetPools'))
        pools = [pool_ref.SelfLink() for pool_ref in pool_refs]

        if group_ref.Collection() == 'compute.instanceGroupManagers':
            service = client.apitools_client.instanceGroupManagers
            request = (client.messages.
                       ComputeInstanceGroupManagersSetTargetPoolsRequest(
                           instanceGroupManager=group_ref.Name(),
                           instanceGroupManagersSetTargetPoolsRequest=(
                               client.messages.
                               InstanceGroupManagersSetTargetPoolsRequest(
                                   targetPools=pools)),
                           project=group_ref.project,
                           zone=group_ref.zone))
        else:
            service = client.apitools_client.regionInstanceGroupManagers
            request = (
                client.messages.
                ComputeRegionInstanceGroupManagersSetTargetPoolsRequest(
                    instanceGroupManager=group_ref.Name(),
                    regionInstanceGroupManagersSetTargetPoolsRequest=(
                        client.messages.
                        RegionInstanceGroupManagersSetTargetPoolsRequest(
                            targetPools=pools)),
                    project=group_ref.project,
                    region=group_ref.region))
        return client.MakeRequests([(service, 'SetTargetPools', request)])
Exemplo n.º 19
0
def _GetInstanceImportRegion(args):  # pylint:disable=unused-argument
    """Return region to run instance import in.

  Args:
    args: command args

  Returns:
    str: region. Can be empty.
  """
    zone = properties.VALUES.compute.zone.Get()
    if zone:
        return utils.ZoneNameToRegionName(zone)
    return ''
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        messages = holder.client.messages

        node_group_ref = flags.MakeNodeGroupArg().ResolveAsResource(
            args,
            holder.resources,
            scope_lister=compute_flags.GetDefaultScopeLister(holder.client))
        node_template_ref = util.ParseNodeTemplate(
            holder.resources,
            args.node_template,
            project=node_group_ref.project,
            region=compute_utils.ZoneNameToRegionName(node_group_ref.zone))

        node_group = messages.NodeGroup(
            name=node_group_ref.Name(),
            description=args.description,
            nodeTemplate=node_template_ref.SelfLink())

        if hasattr(args, 'maintenance_policy'):
            mapper = flags.GetMaintenancePolicyEnumMapper(messages)
            maintenance_policy = mapper.GetEnumForChoice(
                args.maintenance_policy)
            node_group.maintenancePolicy = maintenance_policy

        if hasattr(args, 'autoscaler_mode') and args.autoscaler_mode:
            if args.autoscaler_mode != 'off' and args.max_nodes is None:
                raise exceptions.RequiredArgumentException(
                    '--max-nodes', '--autoscaler-mode is on')
            autoscaling_policy = util.BuildAutoscaling(args, messages)
            node_group.autoscalingPolicy = autoscaling_policy

        if args.maintenance_window_start_time:
            node_group.maintenanceWindow = messages.NodeGroupMaintenanceWindow(
                startTime=args.maintenance_window_start_time)

        if hasattr(args, 'location_hint') and args.location_hint:
            node_group.locationHint = args.location_hint

        if hasattr(args, 'share_setting'):
            node_group.shareSettings = util.BuildShareSettings(messages, args)

        request = messages.ComputeNodeGroupsInsertRequest(
            nodeGroup=node_group,
            initialNodeCount=args.target_size,
            project=node_group_ref.project,
            zone=node_group_ref.zone)

        service = holder.client.apitools_client.nodeGroups
        return client.MakeRequests([(service, 'Insert', request)])[0]
Exemplo n.º 21
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        if args.zone and not args.instances_zone:
            args.instances_zone = args.zone
            log.warning(
                'The --zone flag is deprecated. Use equivalent '
                '--instances-zone=%s flag.', args.instances_zone)

        instance_refs = self.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=compute_flags.GetDefaultScopeLister(client))

        instances = [
            client.messages.InstanceReference(instance=instance_ref.SelfLink())
            for instance_ref in instance_refs
        ]

        unique_regions = set(
            utils.ZoneNameToRegionName(instance_ref.zone)
            for instance_ref in instance_refs)

        # Check that all regions are the same.
        if len(unique_regions) > 1:
            raise exceptions.ArgumentError(
                'Instances must all be in the same region as the target pool.')

        region = unique_regions.pop()

        # Check that the region of the instances is the same as target pool region.
        if args.region and region != args.region:
            raise exceptions.ArgumentError(
                'Instances must all be in the same region as the target pool.')

        args.region = region

        target_pool_ref = self.TARGET_POOL_ARG.ResolveAsResource(
            args, holder.resources)

        request = client.messages.ComputeTargetPoolsAddInstanceRequest(
            region=target_pool_ref.region,
            project=target_pool_ref.project,
            targetPool=target_pool_ref.Name(),
            targetPoolsAddInstanceRequest=(
                client.messages.TargetPoolsAddInstanceRequest(
                    instances=instances)))

        return client.MakeRequests([(client.apitools_client.targetPools,
                                     'AddInstance', request)])
Exemplo n.º 22
0
def CreateNetworkInterfaceMessage(
    resources, compute_client,
    network, subnet, private_network_ip, no_address, address,
    instance_refs, alias_ip_ranges_string=None):
  """Returns a new NetworkInterface message."""
  # TODO(b/30460572): instance reference should have zone name, not zone URI.
  region = utils.ZoneNameToRegionName(instance_refs[0].zone.split('/')[-1])
  messages = compute_client.messages
  network_interface = messages.NetworkInterface()
  # By default interface is attached to default network. If network or subnet
  # are specified they're used instead.
  if subnet is not None:
    subnet_ref = resources.Parse(
        subnet,
        collection='compute.subnetworks',
        params={'region': region})
    network_interface.subnetwork = subnet_ref.SelfLink()
  if network is not None:
    network_ref = resources.Parse(network, collection='compute.networks')
    network_interface.network = network_ref.SelfLink()
  elif subnet is None:
    network_ref = resources.Parse(
        constants.DEFAULT_NETWORK, collection='compute.networks')
    network_interface.network = network_ref.SelfLink()

  if private_network_ip is not None:
    network_interface.networkIP = private_network_ip

  if alias_ip_ranges_string:
    network_interface.aliasIpRanges = (
        alias_ip_range_utils.CreateAliasIpRangeMessagesFromString(
            messages, True, alias_ip_ranges_string))

  if not no_address:
    access_config = messages.AccessConfig(
        name=constants.DEFAULT_ACCESS_CONFIG_NAME,
        type=messages.AccessConfig.TypeValueValuesEnum.ONE_TO_ONE_NAT)

    # If the user provided an external IP, populate the access
    # config with it.
    # TODO(b/25278937): plays poorly when creating multiple instances
    if len(instance_refs) == 1:
      address_resource = flags.ExpandAddressFlag(
          resources, compute_client, address, region)
      if address_resource:
        access_config.natIP = address_resource

    network_interface.accessConfigs = [access_config]

  return network_interface
Exemplo n.º 23
0
def GetSubnetRegion():
    """Gets region from global properties/args that should be used for subnet arg.

  Returns:
    str, region
  Raises:
    SubnetException: if region couldn't be inferred.
  """
    if properties.VALUES.compute.zone.Get():
        return utils.ZoneNameToRegionName(properties.VALUES.compute.zone.Get())
    elif properties.VALUES.compute.region.Get():
        return properties.VALUES.compute.region.Get()

    raise SubnetException('Region or zone should be specified.')
Exemplo n.º 24
0
 def SetNodeTemplate(self, node_group_ref, node_template):
     """Sets the node template field on the node group."""
     node_template_ref = util.ParseNodeTemplate(
         self.resources,
         node_template,
         project=node_group_ref.project,
         region=compute_util.ZoneNameToRegionName(node_group_ref.zone))
     set_request = self.messages.NodeGroupsSetNodeTemplateRequest(
         nodeTemplate=node_template_ref.RelativeName())
     request = self.messages.ComputeNodeGroupsSetNodeTemplateRequest(
         nodeGroupsSetNodeTemplateRequest=set_request,
         nodeGroup=node_group_ref.Name(),
         project=node_group_ref.project,
         zone=node_group_ref.zone)
     return self._service.SetNodeTemplate(request)
Exemplo n.º 25
0
 def _CreateGroupReference(self, args):
     if args.zones:
         zone_ref = self.resources.Parse(args.zones[0],
                                         collection='compute.zones')
         region = utils.ZoneNameToRegionName(zone_ref.Name())
         return self.resources.Parse(
             args.name,
             params={'region': region},
             collection='compute.regionInstanceGroupManagers')
     return (instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.
             ResolveAsResource)(args,
                                self.resources,
                                default_scope=compute_scope.ScopeEnum.ZONE,
                                scope_lister=flags.GetDefaultScopeLister(
                                    self.compute_client))
Exemplo n.º 26
0
def _GetImageExportRegion(args):  # pylint:disable=unused-argument
    """Return region to run image export in.

  Args:
    args: command args

  Returns:
    str: region. Can be empty.
  """
    zone = properties.VALUES.compute.zone.Get()
    if zone:
        return utils.ZoneNameToRegionName(zone)
    elif args.destination_uri:
        return _GetBucketLocation(args.destination_uri)
    return ''
Exemplo n.º 27
0
def ParseDiskResource(resources, name, project, zone, type_):
    """Parses the regional disk resources."""
    if type_ == compute_scopes.ScopeEnum.REGION:
        return resources.Parse(name,
                               collection='compute.regionDisks',
                               params={
                                   'project': project,
                                   'region': utils.ZoneNameToRegionName(zone)
                               })
    else:
        return resources.Parse(name,
                               collection='compute.disks',
                               params={
                                   'project': project,
                                   'zone': zone
                               })
Exemplo n.º 28
0
def _GetImageImportRegion(args):
    """Return region to run image import in.

  Args:
    args: command args

  Returns:
    str: region. Can be empty.
  """
    zone = properties.VALUES.compute.zone.Get()
    if zone:
        return utils.ZoneNameToRegionName(zone)
    elif args.source_file and not IsLocalFile(args.source_file):
        return _GetBucketLocation(args.source_file)
    elif args.storage_location:
        return args.storage_location.lower()
    return ''
 def CreateRequests(self, args):
     ref = self.CreateZonalReference(args.name, args.zone)
     region = utils.ZoneNameToRegionName(ref.zone)
     pool_refs = self.CreateRegionalReferences(args.target_pools,
                                               region,
                                               resource_type='targetPools')
     pools = [pool_ref.SelfLink() for pool_ref in pool_refs]
     request = (
         self.messages.ComputeInstanceGroupManagersSetTargetPoolsRequest(
             instanceGroupManager=ref.Name(),
             instanceGroupManagersSetTargetPoolsRequest=(
                 self.messages.InstanceGroupManagersSetTargetPoolsRequest(
                     targetPools=pools, )),
             project=self.project,
             zone=ref.zone,
         ))
     return [request]
Exemplo n.º 30
0
 def CreateGroupReference(self, args, client, resources):
   if args.zones:
     zone_ref = resources.Parse(
         args.zones[0], collection='compute.zones',
         params={'project': properties.VALUES.core.project.GetOrFail})
     region = utils.ZoneNameToRegionName(zone_ref.Name())
     return resources.Parse(
         args.name,
         params={
             'region': region,
             'project': properties.VALUES.core.project.GetOrFail},
         collection='compute.regionInstanceGroupManagers')
   return (instance_groups_flags.GetInstanceGroupManagerArg().
           ResolveAsResource)(
               args, resources,
               default_scope=compute_scope.ScopeEnum.ZONE,
               scope_lister=flags.GetDefaultScopeLister(client))