def testParseCustomAdvertisements(self):
        for resource_class in self.resource_classes:
            args = mock.Mock()
            args.advertisement_mode = 'CUSTOM'
            args.set_advertisement_groups = ['ALL_SUBNETS']
            args.set_advertisement_ranges = {
                '10.10.10.10/30': 'custom-range',
                '10.10.10.20/30': ''
            }

            expected_mode = resource_class.AdvertiseModeValueValuesEnum.CUSTOM
            expected_groups = [
                resource_class.AdvertisedGroupsValueListEntryValuesEnum.
                ALL_SUBNETS
            ]
            expected_ranges = [
                self.messages.RouterAdvertisedIpRange(
                    range='10.10.10.10/30', description='custom-range'),
                self.messages.RouterAdvertisedIpRange(range='10.10.10.20/30',
                                                      description=''),
            ]

            (mode, groups, ranges) = router_utils.ParseAdvertisements(
                self.messages, resource_class, args)
            self.assertEqual(expected_mode, mode)
            self.assertEqual(expected_groups, groups)
            self.assertEqual(expected_ranges, ranges)
    def testParseDefaultAdvertisements(self):
        for resource_class in self.resource_classes:
            args = mock.Mock()
            args.advertisement_mode = 'DEFAULT'
            args.set_advertisement_groups = None
            args.set_advertisement_ranges = None

            expected_mode = resource_class.AdvertiseModeValueValuesEnum.DEFAULT
            expected_groups = []
            expected_ranges = []

            (mode, groups, ranges) = router_utils.ParseAdvertisements(
                self.messages, resource_class, args)
            self.assertEqual(expected_mode, mode)
            self.assertEqual(expected_groups, groups)
            self.assertEqual(expected_ranges, ranges)
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        api_client = holder.client.apitools_client
        messages = holder.client.messages
        service = api_client.routers

        ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        existing = service.Get(request_type(**ref.AsDict()))
        replacement = copy.deepcopy(existing)

        peer = _UpdateBgpPeer(replacement, args)

        mode, groups, prefixes = router_utils.ParseAdvertisements(
            messages=messages,
            resource_class=messages.RouterBgpPeer,
            args=args)

        existing_mode = peer.advertiseMode
        router_utils.PromptIfSwitchToDefaultMode(
            messages=messages,
            resource_class=messages.RouterBgpPeer,
            existing_mode=existing_mode,
            new_mode=mode)

        attrs = {
            'advertiseMode': mode,
            'advertisedGroups': groups,
            'advertisedPrefixs': prefixes,
        }

        for attr, value in attrs.items():
            if value is not None:
                setattr(peer, attr, value)

        request_type = messages.ComputeRoutersPatchRequest
        resource = service.Patch(
            request_type(project=ref.project,
                         region=ref.region,
                         router=ref.Name(),
                         routerResource=replacement))

        return resource
Example #4
0
  def _Run(self, args, support_keepalive_interval=False):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    messages = holder.client.messages
    service = holder.client.apitools_client.routers

    router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)
    network_ref = self.NETWORK_ARG.ResolveAsResource(args, holder.resources)

    router_resource = messages.Router(
        name=router_ref.Name(),
        description=args.description,
        network=network_ref.SelfLink())

    if support_keepalive_interval:
      # Add bgp field with the assigned asn and/or keepalive_interval
      if args.asn is not None or args.keepalive_interval is not None:
        router_resource.bgp = (
            messages.RouterBgp(
                asn=args.asn, keepaliveInterval=args.keepalive_interval))
    else:
      # Add bgp field with the assigned asn.
      if args.asn is not None:
        router_resource.bgp = messages.RouterBgp(asn=args.asn)

    if router_utils.HasReplaceAdvertisementFlags(args):
      mode, groups, ranges = router_utils.ParseAdvertisements(
          messages=messages, resource_class=messages.RouterBgp, args=args)

      attrs = {
          'advertiseMode': mode,
          'advertisedGroups': groups,
          'advertisedIpRanges': ranges,
      }
      # Create an empty bgp field if not generated yet.
      if args.asn is None:
        router_resource.bgp = messages.RouterBgp()
      for attr, value in six.iteritems(attrs):
        if value is not None:
          setattr(router_resource.bgp, attr, value)

    result = service.Insert(
        messages.ComputeRoutersInsertRequest(
            router=router_resource,
            region=router_ref.region,
            project=router_ref.project))

    operation_ref = resources.REGISTRY.Parse(
        result.name,
        collection='compute.regionOperations',
        params={
            'project': router_ref.project,
            'region': router_ref.region,
        })

    if args.async_:
      # Override the networks list format with the default operations format
      if not args.IsSpecified('format'):
        args.format = 'none'
      log.CreatedResource(
          operation_ref,
          kind='router [{0}]'.format(router_ref.Name()),
          is_async=True,
          details='Run the [gcloud compute operations describe] command '
          'to check the status of this operation.')
      return result

    target_router_ref = holder.resources.Parse(
        router_ref.Name(),
        collection='compute.routers',
        params={
            'project': router_ref.project,
            'region': router_ref.region,
        })

    operation_poller = poller.Poller(service, target_router_ref)
    return waiter.WaitFor(operation_poller, operation_ref,
                          'Creating router [{0}]'.format(router_ref.Name()))
    def _Run(self, args, support_bfd=False, support_enable=False):
        # Manually ensure replace/incremental flags are mutually exclusive.
        router_utils.CheckIncompatibleFlagsOrRaise(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        replacement = service.Get(request_type(**router_ref.AsDict()))

        # Retrieve specified peer and update base fields.
        peer = _UpdateBgpPeerMessage(messages,
                                     replacement,
                                     args,
                                     support_bfd=support_bfd,
                                     support_enable=support_enable)

        if router_utils.HasReplaceAdvertisementFlags(args):
            mode, groups, ranges = router_utils.ParseAdvertisements(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                args=args)

            router_utils.PromptIfSwitchToDefaultMode(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                existing_mode=peer.advertiseMode,
                new_mode=mode)

            attrs = {
                'advertiseMode': mode,
                'advertisedGroups': groups,
                'advertisedIpRanges': ranges,
            }

            for attr, value in attrs.items():
                if value is not None:
                    setattr(peer, attr, value)

        if router_utils.HasIncrementalAdvertisementFlags(args):
            # This operation should only be run on custom mode peers.
            router_utils.ValidateCustomMode(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                resource=peer)

            # These arguments are guaranteed to be mutually exclusive in args.
            if args.add_advertisement_groups:
                groups_to_add = routers_utils.ParseGroups(
                    resource_class=messages.RouterBgpPeer,
                    groups=args.add_advertisement_groups)
                peer.advertisedGroups.extend(groups_to_add)

            if args.remove_advertisement_groups:
                groups_to_remove = routers_utils.ParseGroups(
                    resource_class=messages.RouterBgpPeer,
                    groups=args.remove_advertisement_groups)
                router_utils.RemoveGroupsFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgpPeer,
                    resource=peer,
                    groups=groups_to_remove)

            if args.add_advertisement_ranges:
                ip_ranges_to_add = routers_utils.ParseIpRanges(
                    messages=messages, ip_ranges=args.add_advertisement_ranges)
                peer.advertisedIpRanges.extend(ip_ranges_to_add)

            if args.remove_advertisement_ranges:
                router_utils.RemoveIpRangesFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgpPeer,
                    resource=peer,
                    ip_ranges=args.remove_advertisement_ranges)

        request_type = messages.ComputeRoutersPatchRequest
        result = service.Patch(
            request_type(project=router_ref.project,
                         region=router_ref.region,
                         router=router_ref.Name(),
                         routerResource=replacement))

        operation_ref = resources.REGISTRY.Parse(
            result.name,
            collection='compute.regionOperations',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        if args. async:
            log.UpdatedResource(
                operation_ref,
                kind='peer [{0}] in router [{1}]'.format(
                    peer.name, router_ref.Name()),
                is_async=True,
                details='Run the [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        target_router_ref = holder.resources.Parse(
            router_ref.Name(),
            collection='compute.routers',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        operation_poller = poller.Poller(service, target_router_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating peer [{0}] in router [{1}]'.format(
                peer.name, router_ref.Name()))
    def Run(self, args):
        """See base.UpdateCommand."""

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        replacement = service.Get(request_type(**router_ref.AsDict()))

        peer = _CreateBgpPeerMessage(messages, args)

        if router_utils.HasReplaceAdvertisementFlags(args):
            mode, groups, ranges = router_utils.ParseAdvertisements(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                args=args)

            attrs = {
                'advertiseMode': mode,
                'advertisedGroups': groups,
                'advertisedIpRanges': ranges,
            }

            for attr, value in six.iteritems(attrs):
                if value is not None:
                    setattr(peer, attr, value)

        replacement.bgpPeers.append(peer)

        result = service.Patch(
            messages.ComputeRoutersPatchRequest(project=router_ref.project,
                                                region=router_ref.region,
                                                router=router_ref.Name(),
                                                routerResource=replacement))

        operation_ref = resources.REGISTRY.Parse(
            result.name,
            collection='compute.regionOperations',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        if args. async:
            log.UpdatedResource(
                operation_ref,
                kind='router [{0}] to add peer [{1}]'.format(
                    router_ref.Name(), peer.name),
                is_async=True,
                details='Run the [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        target_router_ref = holder.resources.Parse(
            router_ref.Name(),
            collection='compute.routers',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        operation_poller = poller.Poller(service, target_router_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Creating peer [{0}] in router [{1}]'.format(
                peer.name, router_ref.Name()))
Example #7
0
    def Run(self, args):
        """See base.CreateCommand."""

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)
        network_ref = self.NETWORK_ARG.ResolveAsResource(
            args, holder.resources)

        router_resource = messages.Router(name=router_ref.Name(),
                                          description=args.description,
                                          network=network_ref.SelfLink(),
                                          bgp=messages.RouterBgp(asn=args.asn))

        if router_utils.HasReplaceAdvertisementFlags(args):
            mode, groups, prefixes = router_utils.ParseAdvertisements(
                messages=messages,
                resource_class=messages.RouterBgp,
                args=args)

            attrs = {
                'advertiseMode': mode,
                'advertisedGroups': groups,
                'advertisedPrefixs': prefixes,
            }

            for attr, value in attrs.iteritems():
                if value is not None:
                    setattr(router_resource.bgp, attr, value)

        result = service.Insert(
            messages.ComputeRoutersInsertRequest(router=router_resource,
                                                 region=router_ref.region,
                                                 project=router_ref.project))

        operation_ref = resources.REGISTRY.Parse(
            result.name,
            collection='compute.regionOperations',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        if args. async:
            # Override the networks list format with the default operations format
            if not args.IsSpecified('format'):
                args.format = 'none'
            log.CreatedResource(
                operation_ref,
                kind='router [{0}]'.format(router_ref.Name()),
                async=True,
                details='Run the [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        target_router_ref = holder.resources.Parse(
            router_ref.Name(),
            collection='compute.routers',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        operation_poller = poller.Poller(service, target_router_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Creating router [{0}]'.format(router_ref.Name()))
    def _Run(self,
             args,
             support_bfd_mode=False,
             support_md5_authentication_keys=False):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        replacement = service.Get(request_type(**router_ref.AsDict()))

        instance_ref = None
        if args.instance is not None:
            instance_ref = self.INSTANCE_ARG.ResolveAsResource(
                args,
                holder.resources,
                scope_lister=instance_flags.GetInstanceZoneScopeLister(
                    holder.client))

        md5_authentication_key_name = None
        if support_md5_authentication_keys:
            md5_authentication_key_name = router_utils.GenerateMd5AuthenticationKeyName(
                replacement, args)

        peer = _CreateBgpPeerMessage(
            messages,
            args,
            md5_authentication_key_name=md5_authentication_key_name,
            support_bfd_mode=support_bfd_mode,
            support_md5_authentication_keys=support_md5_authentication_keys,
            instance_ref=instance_ref)

        if router_utils.HasReplaceAdvertisementFlags(args):
            mode, groups, ranges = router_utils.ParseAdvertisements(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                args=args)

            attrs = {
                'advertiseMode': mode,
                'advertisedGroups': groups,
                'advertisedIpRanges': ranges,
            }

            for attr, value in six.iteritems(attrs):
                if value is not None:
                    setattr(peer, attr, value)

        replacement.bgpPeers.append(peer)

        if support_md5_authentication_keys and args.md5_authentication_key is not None:
            md5_authentication_key = messages.RouterMd5AuthenticationKey(
                name=md5_authentication_key_name,
                key=args.md5_authentication_key)
            replacement.md5AuthenticationKeys.append(md5_authentication_key)

        result = service.Patch(
            messages.ComputeRoutersPatchRequest(project=router_ref.project,
                                                region=router_ref.region,
                                                router=router_ref.Name(),
                                                routerResource=replacement))

        operation_ref = resources.REGISTRY.Parse(
            result.name,
            collection='compute.regionOperations',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        if args.async_:
            log.UpdatedResource(
                operation_ref,
                kind='router [{0}] to add peer [{1}]'.format(
                    router_ref.Name(), peer.name),
                is_async=True,
                details='Run the [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        target_router_ref = holder.resources.Parse(
            router_ref.Name(),
            collection='compute.routers',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        operation_poller = poller.Poller(service, target_router_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Creating peer [{0}] in router [{1}]'.format(
                peer.name, router_ref.Name()))
Example #9
0
    def Run(self, args):
        # Manually ensure replace/incremental flags are mutually exclusive.
        router_utils.CheckIncompatibleFlagsOrRaise(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        router_ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        replacement = service.Get(request_type(**router_ref.AsDict()))
        existing_mode = replacement.bgp.advertiseMode

        if router_utils.HasReplaceAdvertisementFlags(args):
            mode, groups, prefixes = router_utils.ParseAdvertisements(
                messages=messages,
                resource_class=messages.RouterBgp,
                args=args)

            router_utils.PromptIfSwitchToDefaultMode(
                messages=messages,
                resource_class=messages.RouterBgp,
                existing_mode=existing_mode,
                new_mode=mode)

            attrs = {
                'advertiseMode': mode,
                'advertisedGroups': groups,
                'advertisedPrefixs': prefixes,
            }

            for attr, value in attrs.items():
                if value is not None:
                    setattr(replacement.bgp, attr, value)

        if router_utils.HasIncrementalAdvertisementFlags(args):
            # This operation should only be run on custom mode routers.
            router_utils.ValidateCustomMode(messages=messages,
                                            resource_class=messages.RouterBgp,
                                            resource=replacement.bgp)

            # These arguments are guaranteed to be mutually exclusive in args.
            if args.add_advertisement_groups:
                groups_to_add = routers_utils.ParseGroups(
                    resource_class=messages.RouterBgp,
                    groups=args.add_advertisement_groups)
                replacement.bgp.advertisedGroups.extend(groups_to_add)

            if args.remove_advertisement_groups:
                groups_to_remove = routers_utils.ParseGroups(
                    resource_class=messages.RouterBgp,
                    groups=args.remove_advertisement_groups)
                router_utils.RemoveGroupsFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgp,
                    resource=replacement.bgp,
                    groups=groups_to_remove)

            if args.add_advertisement_ranges:
                ip_ranges_to_add = routers_utils.ParseIpRanges(
                    messages=messages, ip_ranges=args.add_advertisement_ranges)
                replacement.bgp.advertisedPrefixs.extend(ip_ranges_to_add)

            if args.remove_advertisement_ranges:
                router_utils.RemoveIpRangesFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgp,
                    resource=replacement.bgp,
                    ip_ranges=args.remove_advertisement_ranges)

        # Cleared list fields need to be explicitly identified for Patch API.
        cleared_fields = []
        if not replacement.bgp.advertisedGroups:
            cleared_fields.append('bgp.advertisedGroups')
        if not replacement.bgp.advertisedPrefixs:
            cleared_fields.append('bgp.advertisedPrefixs')

        with holder.client.apitools_client.IncludeFields(cleared_fields):
            request_type = messages.ComputeRoutersPatchRequest
            result = service.Patch(
                request_type(project=router_ref.project,
                             region=router_ref.region,
                             router=router_ref.Name(),
                             routerResource=replacement))

        operation_ref = resources.REGISTRY.Parse(
            result.name,
            collection='compute.regionOperations',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        if args. async:
            log.UpdatedResource(
                operation_ref,
                kind='router [{0}]'.format(router_ref.Name()),
                async=True,
                details='Run the [gcloud compute operations describe] command '
                'to check the status of this operation.')
            return result

        target_router_ref = holder.resources.Parse(
            router_ref.Name(),
            collection='compute.routers',
            params={
                'project': router_ref.project,
                'region': router_ref.region,
            })

        operation_poller = poller.Poller(service, target_router_ref)
        return waiter.WaitFor(
            operation_poller, operation_ref,
            'Updating router [{0}]'.format(router_ref.Name()))
Example #10
0
  def Run(self, args):
    # Manually ensure replace/incremental flags are mutually exclusive.
    router_utils.CheckIncompatibleFlagsOrRaise(args)

    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client
    messages = client.messages

    ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

    existing = client.MakeRequests([routers_utils.GetGetRequest(client,
                                                                ref)])[0]
    replacement = copy.deepcopy(existing)

    if router_utils.HasReplaceAdvertisementFlags(args):
      mode, groups, prefixes = router_utils.ParseAdvertisements(
          messages=messages, resource_class=messages.RouterBgp, args=args)

      router_utils.PromptIfSwitchToDefaultMode(
          messages=messages,
          resource_class=messages.RouterBgp,
          existing_mode=existing.bgp.advertiseMode,
          new_mode=mode)

      attrs = {
          'advertiseMode': mode,
          'advertisedGroups': groups,
          'advertisedPrefixs': prefixes,
      }

      for attr, value in attrs.items():
        if value is not None:
          setattr(replacement.bgp, attr, value)

    if router_utils.HasIncrementalAdvertisementFlags(args):
      # This operation should only be run on custom mode routers.
      router_utils.ValidateCustomMode(
          messages=messages,
          resource_class=messages.RouterBgp,
          resource=replacement.bgp)

      # These arguments are guaranteed to be mutually exclusive in args.
      if args.add_advertisement_groups:
        groups_to_add = router_utils.ParseGroups(
            resource_class=messages.RouterBgp,
            groups=args.add_advertisement_groups)
        replacement.bgp.advertisedGroups.extend(groups_to_add)

      if args.remove_advertisement_groups:
        groups_to_remove = router_utils.ParseGroups(
            resource_class=messages.RouterBgp,
            groups=args.remove_advertisement_groups)
        router_utils.RemoveGroupsFromAdvertisements(
            messages=messages,
            resource_class=messages.RouterBgp,
            resource=replacement.bgp,
            groups=groups_to_remove)

      if args.add_advertisement_ranges:
        ip_ranges_to_add = router_utils.ParseIpRanges(
            messages=messages, ip_ranges=args.add_advertisement_ranges)
        replacement.bgp.advertisedPrefixs.extend(ip_ranges_to_add)

      if args.remove_advertisement_ranges:
        router_utils.RemoveIpRangesFromAdvertisements(
            messages=messages,
            resource_class=messages.RouterBgp,
            resource=replacement.bgp,
            ip_ranges=args.remove_advertisement_ranges)

    # Cleared list fields need to be explicitly identified for Patch API.
    cleared_fields = []
    if not replacement.bgp.advertisedGroups:
      cleared_fields.append('bgp.advertisedGroups')
    if not replacement.bgp.advertisedPrefixs:
      cleared_fields.append('bgp.advertisedPrefixs')

    with client.apitools_client.IncludeFields(cleared_fields):
      resource_list = client.MakeRequests(
          [routers_utils.GetPatchRequest(client, ref, replacement)])
    return resource_list
Example #11
0
    def Run(self, args):
        # Manually ensure replace/incremental flags are mutually exclusive.
        router_utils.CheckIncompatibleFlagsOrRaise(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client
        messages = client.messages

        ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        existing = client.MakeRequests(
            [routers_utils.GetGetRequest(client, ref)])[0]
        # TODO(b/38240188): Clean up test resources and remove this copy step.
        replacement = copy.deepcopy(existing)

        # Retrieve specified peer and update base fields.
        peer = _UpdateBgpPeer(replacement, args)

        if router_utils.HasReplaceAdvertisementFlags(args):
            mode, groups, prefixes = router_utils.ParseAdvertisements(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                args=args)

            router_utils.PromptIfSwitchToDefaultMode(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                existing_mode=peer.advertiseMode,
                new_mode=mode)

            attrs = {
                'advertiseMode': mode,
                'advertisedGroups': groups,
                'advertisedPrefixs': prefixes,
            }

            for attr, value in attrs.items():
                if value is not None:
                    setattr(peer, attr, value)

        if router_utils.HasIncrementalAdvertisementFlags(args):
            # This operation should only be run on custom mode peers.
            router_utils.ValidateCustomMode(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                resource=peer)

            # These arguments are guaranteed to be mutually exclusive in args.
            if args.add_advertisement_groups:
                groups_to_add = router_utils.ParseGroups(
                    resource_class=messages.RouterBgpPeer,
                    groups=args.add_advertisement_groups)
                peer.advertisedGroups.extend(groups_to_add)

            if args.remove_advertisement_groups:
                groups_to_remove = router_utils.ParseGroups(
                    resource_class=messages.RouterBgpPeer,
                    groups=args.remove_advertisement_groups)
                router_utils.RemoveGroupsFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgpPeer,
                    resource=peer,
                    groups=groups_to_remove)

            if args.add_advertisement_ranges:
                ip_ranges_to_add = router_utils.ParseIpRanges(
                    messages=messages, ip_ranges=args.add_advertisement_ranges)
                peer.advertisedPrefixs.extend(ip_ranges_to_add)

            if args.remove_advertisement_ranges:
                router_utils.RemoveIpRangesFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgpPeer,
                    resource=peer,
                    ip_ranges=args.remove_advertisement_ranges)

        # TODO(b/62667314): Replace MakeRequests with proper poll + mock testing.
        resource_list = client.MakeRequests(
            [routers_utils.GetPatchRequest(client, ref, replacement)])
        return resource_list
Example #12
0
    def Run(self, args):
        # Manually ensure replace/incremental flags are mutually exclusive.
        router_utils.CheckIncompatibleFlagsOrRaise(args)

        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        messages = holder.client.messages
        service = holder.client.apitools_client.routers

        ref = self.ROUTER_ARG.ResolveAsResource(args, holder.resources)

        request_type = messages.ComputeRoutersGetRequest
        existing = service.Get(request_type(**ref.AsDict()))
        replacement = copy.deepcopy(existing)

        # Retrieve specified peer and update base fields.
        peer = _UpdateBgpPeer(replacement, args)

        if router_utils.HasReplaceAdvertisementFlags(args):
            mode, groups, prefixes = router_utils.ParseAdvertisements(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                args=args)

            router_utils.PromptIfSwitchToDefaultMode(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                existing_mode=peer.advertiseMode,
                new_mode=mode)

            attrs = {
                'advertiseMode': mode,
                'advertisedGroups': groups,
                'advertisedPrefixs': prefixes,
            }

            for attr, value in attrs.items():
                if value is not None:
                    setattr(peer, attr, value)

        if router_utils.HasIncrementalAdvertisementFlags(args):
            # This operation should only be run on custom mode peers.
            router_utils.ValidateCustomMode(
                messages=messages,
                resource_class=messages.RouterBgpPeer,
                resource=peer)

            # These arguments are guaranteed to be mutually exclusive in args.
            if args.add_advertisement_groups:
                groups_to_add = router_utils.ParseGroups(
                    resource_class=messages.RouterBgpPeer,
                    groups=args.add_advertisement_groups)
                peer.advertisedGroups.extend(groups_to_add)

            if args.remove_advertisement_groups:
                groups_to_remove = router_utils.ParseGroups(
                    resource_class=messages.RouterBgpPeer,
                    groups=args.remove_advertisement_groups)
                router_utils.RemoveGroupsFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgpPeer,
                    resource=peer,
                    groups=groups_to_remove)

            if args.add_advertisement_ranges:
                ip_ranges_to_add = router_utils.ParseIpRanges(
                    messages=messages, ip_ranges=args.add_advertisement_ranges)
                peer.advertisedPrefixs.extend(ip_ranges_to_add)

            if args.remove_advertisement_ranges:
                router_utils.RemoveIpRangesFromAdvertisements(
                    messages=messages,
                    resource_class=messages.RouterBgpPeer,
                    resource=peer,
                    ip_ranges=args.remove_advertisement_ranges)

        request_type = messages.ComputeRoutersPatchRequest
        resource = service.Patch(
            request_type(project=ref.project,
                         region=ref.region,
                         router=ref.Name(),
                         routerResource=replacement))

        return resource