Esempio n. 1
0
 def Run(self, args):
     client = zones_api.Client(version=self._API_VERSION)
     messages = util.GetMessages(version=self._API_VERSION)
     perimeter_ref = args.CONCEPTS.perimeter.Parse()
     policies.ValidateAccessPolicyArg(perimeter_ref, args)
     original_perimeter = client.Get(perimeter_ref)
     base_config = _GetBaseConfig(original_perimeter)
     updated_resources = repeated.ParsePrimitiveArgs(
         args, 'resources', lambda: base_config.resources or [])
     updated_restricted_services = repeated.ParsePrimitiveArgs(
         args, 'restricted-services',
         lambda: base_config.restrictedServices or [])
     updated_access_levels = repeated.ParsePrimitiveArgs(
         args, 'access-levels', lambda: base_config.accessLevels or [])
     base_vpc_config = base_config.vpcAccessibleServices
     if base_vpc_config is None:
         base_vpc_config = messages.VpcAccessibleServices()
     updated_vpc_services = repeated.ParsePrimitiveArgs(
         args, 'vpc-allowed-services',
         lambda: base_vpc_config.allowedServices or [])
     if args.IsSpecified('enable_vpc_accessible_services'):
         updated_vpc_enabled = args.enable_vpc_accessible_services
     elif base_config.vpcAccessibleServices is not None:
         updated_vpc_enabled = base_vpc_config.enableRestriction
     else:
         updated_vpc_enabled = None
     return client.PatchDryRunConfig(
         perimeter_ref,
         resources=updated_resources,
         levels=updated_access_levels,
         restricted_services=updated_restricted_services,
         vpc_allowed_services=updated_vpc_services,
         enable_vpc_accessible_services=updated_vpc_enabled)
Esempio n. 2
0
 def testMutuallyExclusive(self):
     args, _ = self.parser.parse_known_args(
         '--clear-bars --set-bars a,b'.split(' '))
     with self.assertRaises(ValueError):
         # This should be caught at argument parse time, but in a test context full
         # argument parsing is hard to replicate.
         repeated.ParsePrimitiveArgs(args, 'bars', [].pop)
Esempio n. 3
0
def Update(versions_client, operations_client, version_ref, args,
           enable_user_code=False):
  """Update the given version."""
  get_result = repeated.CachedResult.FromFunc(
      versions_client.Get, version_ref)
  labels_update = ParseUpdateLabels(versions_client, get_result, args)
  all_args = ['update_labels', 'clear_labels', 'remove_labels', 'description']

  if enable_user_code:
    all_args.extend([
        'clear_model_class', 'model_class',
        'add_package_uris', 'remove_package_uris', 'clear_package_uris',
        'set_package_uris'])
    model_class_update = update_util.ParseClearableField(args, 'model_class')
    package_uris = repeated.ParsePrimitiveArgs(
        args, 'package_uris', get_result.GetAttrThunk('packageUris'))
  else:
    model_class_update = None
    package_uris = None

  try:
    op = versions_client.Patch(version_ref, labels_update, args.description,
                               model_class_update=model_class_update,
                               package_uris=package_uris)
  except versions_api.NoFieldsSpecifiedError:
    if not any(args.IsSpecified(arg) for arg in all_args):
      raise
    log.status.Print('No update to perform.')
    return None
  else:
    return operations_client.WaitForOperation(
        op, message='Updating version [{}]'.format(version_ref.Name())).response
Esempio n. 4
0
 def UpdateAssetNamesAndTypes(self, args, feed_name, update_masks):
     """Get Updated assetNames and assetTypes."""
     feed = self.service.Get(
         self.message_module.CloudassetFeedsGetRequest(name=feed_name))
     asset_names = repeated.ParsePrimitiveArgs(args, 'asset_names',
                                               lambda: feed.assetNames)
     if asset_names is not None:
         update_masks.append('asset_names')
     else:
         asset_names = []
     asset_types = repeated.ParsePrimitiveArgs(args, 'asset_types',
                                               lambda: feed.assetTypes)
     if asset_types is not None:
         update_masks.append('asset_types')
     else:
         asset_types = []
     return asset_names, asset_types
Esempio n. 5
0
def ParseLevels(args, perimeter_result, policy_id, dry_run=False):
    """Process repeated level changes."""
    def GetLevelIds():
        return [
            _GetLevelIdFromLevelName(l)
            for l in _GetConfig(perimeter_result, dry_run).accessLevels
        ]

    level_ids = repeated.ParsePrimitiveArgs(args, 'access_levels', GetLevelIds)
    return ExpandLevelNamesIfNecessary(level_ids, policy_id)
Esempio n. 6
0
    def testParse(self, before, flag_value, expected):
        if before is None:
            result = repeated.CachedResult([].pop)
        else:
            result = repeated.CachedResult([before].pop)

        args, _ = self.parser.parse_known_args(flag_value.split(' '))

        after = repeated.ParsePrimitiveArgs(args, 'bars', result.Get)
        self.assertEqual(after, expected)
  def AdjustConfiguration(self, config, metadata):
    def GetCurrentInstances():
      annotation_val = config.revision_annotations.get(_CLOUDSQL_ANNOTATION)
      if annotation_val:
        return annotation_val.split(',')
      return []

    instances = repeated.ParsePrimitiveArgs(
        self, 'cloudsql-instances', GetCurrentInstances)
    config.revision_annotations[_CLOUDSQL_ANNOTATION] = ','.join(instances)
Esempio n. 8
0
def ParseLevels(args, perimeter_result, policy_id):
  level_ids = repeated.ParsePrimitiveArgs(
      args, 'access_levels',
      perimeter_result.GetAttrThunk(
          'accessLevels', transform=_GetLevelIdFromLevelName))
  if level_ids is None:
    return None
  return [REGISTRY.Create(levels.COLLECTION,
                          accessPoliciesId=policy_id,
                          accessLevelsId=l) for l in level_ids]
Esempio n. 9
0
  def Adjust(self, resource):
    def GetCurrentInstances():
      annotation_val = resource.template.annotations.get(_CLOUDSQL_ANNOTATION)
      if annotation_val:
        return annotation_val.split(',')
      return []

    instances = repeated.ParsePrimitiveArgs(
        self, 'cloudsql-instances', GetCurrentInstances)
    if instances is not None:
      resource.template.annotations[_CLOUDSQL_ANNOTATION] = ','.join(instances)
Esempio n. 10
0
def _GetRepeatedFieldValue(args, field_name, base_config_value, has_spec):
    """Returns the repeated field value to use for the update operation."""
    repeated_field = repeated.ParsePrimitiveArgs(
        args, field_name, lambda: base_config_value or [])
    # If there is no difference between base_config_value and command line input,
    # AND there is no spec, then send the list of existing values from
    # base_config_value for update operation. This is due to edge case of existing
    # status, but no existing spec. base_config_value will be values in status in
    # this case, and if the input is the same as what is set in status config,
    # then an empty list will be given as the value for the corresponding field
    # when creating the spec (which is incorrect).
    if not has_spec and not repeated_field:
        repeated_field = base_config_value
    return repeated_field
Esempio n. 11
0
def ParseLevels(args, perimeter_result, policy_id):
  """Process repeated level changes."""

  def GetLevelIds():
    return [
        _GetLevelIdFromLevelName(l)
        for l in perimeter_result.Get().status.accessLevels
    ]

  level_ids = repeated.ParsePrimitiveArgs(args, 'access_levels', GetLevelIds)

  if level_ids is None:
    return None
  return [REGISTRY.Create(levels.COLLECTION,
                          accessPoliciesId=policy_id,
                          accessLevelsId=l) for l in level_ids]
Esempio n. 12
0
def ParseVpcRestriction(args, perimeter_result, version, dry_run=False):
    """Parse service restriction related arguments."""
    if _IsServiceFilterUpdateSpecified(args):
        # If there is no service restriction message in the request, make an empty
        # one to populate.
        config = _GetConfig(perimeter_result, dry_run)
        if getattr(config, 'vpcAccessibleServices', None) is None:
            restriction_message = getattr(
                apis.GetMessagesModule('accesscontextmanager', version),
                'VpcAccessibleServices')()
            setattr(config, 'vpcAccessibleServices', restriction_message)

    def FetchAllowed():
        return getattr(_GetConfig(perimeter_result, dry_run),
                       'vpcAccessibleServices').allowedServices

    return repeated.ParsePrimitiveArgs(args, 'vpc_allowed_services',
                                       FetchAllowed)
Esempio n. 13
0
def _ParseRestriction(args, perimeter_result, version, restriction_type):
    """Parse service restriction related arguments."""
    if _IsServiceFilterUpdateSpecified(args, restriction_type):
        # If there is no service restriction message in the request, make an empty
        # one to populate.
        if getattr(perimeter_result.Get().status,
                   restriction_type + 'ServiceRestriction', None) is None:
            restriction_message = getattr(
                apis.GetMessagesModule('accesscontextmanager', version),
                restriction_type.capitalize() + 'ServiceRestriction')()
            setattr(perimeter_result.Get().status,
                    restriction_type + 'ServiceRestriction',
                    restriction_message)

    def FetchAllowed():
        return getattr(perimeter_result.Get().status,
                       restriction_type + 'ServiceRestriction').allowedServices

    return repeated.ParsePrimitiveArgs(args,
                                       restriction_type + '_allowed_services',
                                       FetchAllowed)
Esempio n. 14
0
def ParseResources(args, perimeter_result):
  return repeated.ParsePrimitiveArgs(args, 'resources',
                                     perimeter_result.GetAttrThunk('resources'))
Esempio n. 15
0
def ParseRestrictedServices(args, perimeter_result):
  return repeated.ParsePrimitiveArgs(
      args, 'restricted_services',
      lambda: perimeter_result.Get().status.restrictedServices)
def ParseRestrictedServices(args, perimeter_result, dry_run=False):
    return repeated.ParsePrimitiveArgs(
        args, 'restricted_services',
        lambda: _GetConfig(perimeter_result, dry_run).restrictedServices)
Esempio n. 17
0
def ParseUnrestrictedServices(args, zone_result):
  return repeated.ParsePrimitiveArgs(
      args, 'unrestricted_services',
      zone_result.GetAttrThunk('unrestrictedServices'))
Esempio n. 18
0
def ParseRestrictedServices(args, perimeter_result):
  return repeated.ParsePrimitiveArgs(
      args, 'restricted_services',
      perimeter_result.GetAttrThunk('restrictedServices'))