Beispiel #1
0
def AddMinLogLevelFlag(parser):
    min_log_arg = base.ChoiceArgument(
        '--min-log-level',
        choices=[x.lower() for x in SEVERITIES],
        help_str='Minimum level of logs to be fetched.')
    min_log_arg.AddToParser(parser)
Beispiel #2
0
def _GetDeviceCredentialFlags(combine_flags=True, only_modifiable=False):
    """"Generates credentials-related flags."""
    flags = []
    if not only_modifiable:
        flags.extend([
            base.Argument(
                '--path',
                required=True,
                type=str,
                help='The path on disk to the file containing the key.'),
            base.ChoiceArgument('--type',
                                choices=_VALID_KEY_TYPES,
                                required=True,
                                help_str='The type of the key.')
        ])
    flags.append(
        base.Argument('--expiration-time',
                      type=arg_parsers.Datetime.Parse,
                      help=('The expiration time for the key. See '
                            '$ gcloud topic datetimes for information on '
                            'time formats.')))
    if not combine_flags:
        return flags

    sub_argument_help = []
    spec = {}
    for flag in flags:
        name = flag.name.lstrip('-')
        required = flag.kwargs.get('required')
        choices = flag.kwargs.get('choices')
        choices_str = ''
        if choices:
            choices_str = ', '.join(map('`{}`'.format, sorted(choices)))
            choices_str = ' One of [{}].'.format(choices_str)
        help_ = flag.kwargs['help']
        spec[name] = flag.kwargs['type']
        sub_argument_help.append(
            '* *{name}*: {required}.{choices} {help}'.format(
                name=name,
                required=('Required' if required else 'Optional'),
                choices=choices_str,
                help=help_))
    key_type_help = []
    for key_type, description in reversed(sorted(_VALID_KEY_TYPES.items())):
        key_type_help.append('* `{}`: {}'.format(key_type, description))
    flag = base.Argument(
        '--public-key',
        dest='public_keys',
        metavar='path=PATH,type=TYPE,[expiration-time=EXPIRATION-TIME]',
        type=arg_parsers.ArgDict(spec=spec),
        action='append',
        help="""\
Specify a public key.

Supports four key types:

{key_type_help}

The key specification is given via the following sub-arguments:

{sub_argument_help}

For example:

  --public-key \\
      path=/path/to/id_rsa.pem,type=RSA_PEM,expiration-time=2017-01-01T00:00-05

This flag may be provide multiple times to provide multiple keys (maximum 3).
""".format(key_type_help='\n'.join(key_type_help),
           sub_argument_help='\n'.join(sub_argument_help)))
    return [flag]
Beispiel #3
0
    def __init__(self,
                 arg_name,
                 message_enum,
                 custom_mappings=None,
                 help_str=None,
                 required=False,
                 action=None,
                 metavar=None,
                 dest=None,
                 default=None,
                 hidden=False,
                 include_filter=None):
        """Initialize ChoiceEnumMapper.

    Args:
      arg_name: str, The name of the argparse argument to create
      message_enum: apitools.Enum, the enum to map
      custom_mappings: See Above.
      help_str: string, pass through for base.Argument,
        see base.ChoiceArgument().
      required: boolean,string, pass through for base.Argument,
          see base.ChoiceArgument().
      action: string or argparse.Action, string, pass through for base.Argument,
          see base.ChoiceArgument().
      metavar: string,  string, pass through for base.Argument,
          see base.ChoiceArgument()..
      dest: string, string, pass through for base.Argument,
          see base.ChoiceArgument().
      default: string, string, pass through for base.Argument,
          see base.ChoiceArgument().
      hidden: boolean, pass through for base.Argument,
          see base.ChoiceArgument().
      include_filter: callable, function of type string->bool used to filter
          enum values from message_enum that should be included in choices.
          If include_filter returns True for a particular enum value, it will be
          included otherwise it will be excluded. This is ignored if
          custom_mappings is specified.

    Raises:
      ValueError: If no enum is given, mappings are incomplete
      TypeError: If invalid values are passed for base.Argument or
       custom_mapping
    """
        # pylint:disable=protected-access
        if not isinstance(message_enum, messages._EnumClass):
            raise ValueError('Invalid Message Enum: [{}]'.format(message_enum))
        self._arg_name = arg_name
        self._enum = message_enum
        self._custom_mappings = custom_mappings
        if include_filter is not None and not callable(include_filter):
            raise TypeError(
                'include_filter must be callable received [{}]'.format(
                    include_filter))

        self._filter = include_filter
        self._filtered_enum = self._enum
        self._ValidateAndParseMappings()
        self._choice_arg = base.ChoiceArgument(arg_name,
                                               self.choices,
                                               help_str=help_str,
                                               required=required,
                                               action=action,
                                               metavar=metavar,
                                               dest=dest,
                                               default=default,
                                               hidden=hidden)
Beispiel #4
0
def AddCycleFrequencyArgs(parser,
                          flag_suffix,
                          start_time_help,
                          cadence_help,
                          supports_hourly=False,
                          has_restricted_start_times=False,
                          supports_weekly=False):
    """Add Cycle Frequency args for Resource Policies."""
    freq_group = parser.add_argument_group('Cycle Frequency Group.',
                                           required=True,
                                           mutex=True)
    if has_restricted_start_times:
        start_time_help += """\
        Valid choices are 00:00, 04:00, 08:00,12:00,
        16:00 and 20:00 UTC. For example, `--start-time="03:00-05"`
        (which gets converted to 08:00 UTC)."""
    freq_flags_group = freq_group.add_group(
        'From flags:' if supports_weekly else '')
    freq_flags_group.add_argument('--start-time',
                                  required=True,
                                  type=arg_parsers.Datetime.Parse,
                                  help=start_time_help)
    cadence_group = freq_flags_group.add_group(mutex=True, required=True)
    cadence_group.add_argument(
        '--daily-{}'.format(flag_suffix),
        dest='daily_cycle',
        action='store_true',
        help='{} starts daily at START_TIME.'.format(cadence_help))

    if supports_hourly:
        cadence_group.add_argument(
            '--hourly-{}'.format(flag_suffix),
            metavar='HOURS',
            dest='hourly_cycle',
            type=arg_parsers.BoundedInt(lower_bound=1),
            help='{} occurs every n hours starting at START_TIME.'.format(
                cadence_help))

    if supports_weekly:
        base.ChoiceArgument(
            '--weekly-{}'.format(flag_suffix),
            dest='weekly_cycle',
            choices=[
                'monday', 'tuesday', 'wednesday', 'thursday', 'friday',
                'saturday', 'sunday'
            ],
            help_str='{} occurs weekly on WEEKLY_{} at START_TIME.'.format(
                cadence_help, flag_suffix.upper())).AddToParser(cadence_group)
        freq_file_group = freq_group.add_group('From file:')
        freq_file_group.add_argument(
            '--weekly-{}-from-file'.format(flag_suffix),
            dest='weekly_cycle_from_file',
            type=arg_parsers.FileContents(),
            help="""\
        A JSON/YAML file which specifies a weekly schedule. It should be a
        list of objects with the following fields:

        day: Day of the week with the same choices as `--weekly-{}`.
        startTime: Start time of the snapshot schedule with the same format
            as --start-time.
        """.format(flag_suffix))
Beispiel #5
0
def _AddArgs(cls, parser, include_alpha=False):
    """Add subnetwork create arguments to parser."""
    cls.SUBNETWORK_ARG = flags.SubnetworkArgument()
    cls.NETWORK_ARG = network_flags.NetworkArgumentForOtherResource(
        'The network to which the subnetwork belongs.')
    cls.SUBNETWORK_ARG.AddArgument(parser, operation_type='create')
    cls.NETWORK_ARG.AddArgument(parser)

    parser.add_argument('--description',
                        help='An optional description of this subnetwork.')

    parser.add_argument(
        '--range',
        required=True,
        help='The IP space allocated to this subnetwork in CIDR format.')

    parser.add_argument(
        '--enable-private-ip-google-access',
        action='store_true',
        default=False,
        help=(
            'Enable/disable access to Google Cloud APIs from this subnet for '
            'instances without a public ip address.'))

    parser.add_argument('--secondary-range',
                        type=arg_parsers.ArgDict(min_length=1),
                        action='append',
                        metavar='PROPERTY=VALUE',
                        help="""\
      Adds a secondary IP range to the subnetwork for use in IP aliasing.

      For example, `--secondary-range range1=192.168.64.0/24` adds
      a secondary range 192.168.64.0/24 with name range1.

      * `RANGE_NAME` - Name of the secondary range.
      * `RANGE` - `IP range in CIDR format.`
      """)

    parser.add_argument(
        '--enable-flow-logs',
        action='store_true',
        default=None,
        help=(
            'Enable/disable VPC flow logging for this subnet. More information '
            'for VPC flow logs can be found at '
            'https://cloud.google.com/vpc/docs/using-flow-logs.'))

    if include_alpha:
        parser.add_argument(
            '--purpose',
            choices={
                'PRIVATE':
                'Regular user created or automatically created subnet.',
                'INTERNAL_HTTPS_LOAD_BALANCER':
                'Reserved for Internal HTTP(S) Load Balancing.'
            },
            type=lambda x: x.replace('-', '_').upper(),
            help='The purpose of this subnetwork.')

        parser.add_argument(
            '--role',
            choices={
                'ACTIVE': 'The ACTIVE subnet that is currently used.',
                'BACKUP': 'The BACKUP subnet that could be promoted to ACTIVE.'
            },
            type=lambda x: x.replace('-', '_').upper(),
            help=
            ('The role of subnetwork. This field is only used when'
             'purpose=INTERNAL_HTTPS_LOAD_BALANCER. The value can be set to '
             'ACTIVE or BACKUP. An ACTIVE subnetwork is one that is currently '
             'being used for Internal HTTP(S) Load Balancing. A BACKUP '
             'subnetwork is one that is ready to be promoted to ACTIVE or is '
             'currently draining.'))

        aggregation_interval_argument = base.ChoiceArgument(
            '--aggregation-interval',
            choices=[
                'interval-5-sec', 'interval-30-sec', 'interval-1-min',
                'interval-5-min', 'interval-10-min', 'interval-15-min'
            ],
            help_str="""\
        Can only be specified if VPC flow logging for this subnetwork is
        enabled. Toggles the aggregation interval for collecting flow logs.
        Increasing the interval time will reduce the amount of generated flow
        logs for long lasting connections. Default is an interval of 5 seconds
        per connection.
        """)
        aggregation_interval_argument.AddToParser(parser)

        parser.add_argument('--flow-sampling',
                            type=arg_parsers.BoundedFloat(lower_bound=0.0,
                                                          upper_bound=1.0),
                            help="""\
        Can only be specified if VPC flow logging for this subnetwork is
        enabled. The value of the field must be in [0, 1]. Set the sampling rate
        of VPC flow logs within the subnetwork where 1.0 means all collected
        logs are reported and 0.0 means no logs are reported. Default is 0.5
        which means half of all collected logs are reported.
        """)

        metadata_argument = base.ChoiceArgument(
            '--metadata',
            choices=['include-all-metadata', 'exclude-all-metadata'],
            help_str="""\
        Can only be specified if VPC flow logging for this subnetwork is
        enabled. Configures whether metadata fields should be added to the
        reported VPC flow logs. Default is to include all metadata.
        """)
        metadata_argument.AddToParser(parser)

        parser.add_argument(
            '--enable-private-ipv6-access',
            action='store_true',
            default=None,
            help=('Enable/disable private IPv6 access for the subnet.'))
def GetTypeFlag():
    """Anthos auth token type flag, specifies the type of token to be created."""
    return base.ChoiceArgument('--type',
                               required=True,
                               choices=['aws', 'oidc'],
                               help_str='Type of token to be created.')