Exemple #1
0
def validate_url_with_params(url: str, ssh_private_key, ssh_private_key_file,
                             known_hosts, known_hosts_file, https_user,
                             https_key):

    scheme = urlparse(url).scheme
    if scheme.lower() in ('http', 'https'):
        if ssh_private_key or ssh_private_key_file:
            raise MutuallyExclusiveArgumentError(
                consts.SSH_PRIVATE_KEY_WITH_HTTP_URL_ERROR,
                consts.SSH_PRIVATE_KEY_WITH_HTTP_URL_HELP)
        if known_hosts or known_hosts_file:
            raise MutuallyExclusiveArgumentError(
                consts.KNOWN_HOSTS_WITH_HTTP_URL_ERROR,
                consts.KNOWN_HOSTS_WITH_HTTP_URL_HELP)
        if not (https_user and https_key) and scheme == 'https':
            logger.warning(consts.HTTP_URL_NO_AUTH_WARNING)
    else:
        if https_user or https_key:
            raise MutuallyExclusiveArgumentError(
                consts.HTTPS_AUTH_WITH_SSH_URL_ERROR,
                consts.HTTPS_AUTH_WITH_SSH_URL_HELP)

    if https_user and https_key:
        return
    # If we just provide one or the other raise an error
    if https_user or https_key:
        raise RequiredArgumentMissingError(consts.HTTPS_USER_KEY_MATCH_ERROR,
                                           consts.HTTPS_USER_KEY_MATCH_HELP)
def validate_url_with_params(repository_url, ssh_private_key_set,
                             known_hosts_contents_set, https_auth_set):
    scheme = urlparse(repository_url).scheme

    if scheme in ('http', 'https'):
        if ssh_private_key_set:
            raise MutuallyExclusiveArgumentError(
                'Error! An ssh private key cannot be used with an http(s) url',
                'Verify the url provided is a valid ssh url and not an http(s) url'
            )
        if known_hosts_contents_set:
            raise MutuallyExclusiveArgumentError(
                'Error! ssh known_hosts cannot be used with an http(s) url',
                'Verify the url provided is a valid ssh url and not an http(s) url'
            )
        if not https_auth_set and scheme == 'https':
            logger.warning(
                'Warning! https url is being used without https auth params, ensure the repository '
                'url provided is not a private repo')
    else:
        if https_auth_set:
            raise MutuallyExclusiveArgumentError(
                'Error! https auth (--https-user and --https-key) cannot be used with a non-http(s) url',
                'Verify the url provided is a valid http(s) url and not an ssh url'
            )
Exemple #3
0
def billing_invoice_download_validator(namespace):
    from azure.cli.core.azclierror import (
        RequiredArgumentMissingError,
        MutuallyExclusiveArgumentError,
    )

    valid_combs = ("only --account-name, --invoice-name, --download-token / "
                   "--account-name, --download-urls / "
                   "--download-urls /"
                   "--invoice-name, --download-token is valid")

    if namespace.account_name:
        if namespace.download_token is None and namespace.invoice_name is None and namespace.download_urls is None:
            raise RequiredArgumentMissingError(
                "--download-urls / --download-token, --invoice-name is also required"
            )

        if namespace.download_urls is not None:
            if namespace.download_token is not None or namespace.invoice_name is not None:
                raise MutuallyExclusiveArgumentError(valid_combs)
        if namespace.download_urls is None:
            if namespace.download_token is None and namespace.invoice_name is None:
                raise RequiredArgumentMissingError(
                    "--download-token and --invoice-name are also required")
            if namespace.download_token is None:
                raise RequiredArgumentMissingError(
                    "--download-token is also required")
            if namespace.invoice_name is None:
                raise RequiredArgumentMissingError(
                    "--invoice-name is also required")

    if namespace.invoice_name is not None:
        if namespace.download_urls is not None:
            raise MutuallyExclusiveArgumentError(valid_combs)
        if namespace.download_token is None:
            raise RequiredArgumentMissingError(
                "--account-name, --download-token / --download-token is also required"
            )

    if namespace.download_token is not None:
        if namespace.download_urls is not None:
            raise MutuallyExclusiveArgumentError(valid_combs)
        if namespace.account_name is not None:
            raise RequiredArgumentMissingError(
                "--invoice-name is also required")
        if namespace.invoice_name is None:
            raise RequiredArgumentMissingError(
                "--account-name, --invoice-name / --invoice-name is also required"
            )

    if namespace.download_urls is not None:
        if namespace.download_token is not None:
            raise MutuallyExclusiveArgumentError(
                "--download-urls can't be used with --download-token")
        if namespace.invoice_name is not None:
            raise MutuallyExclusiveArgumentError(
                "--download-urls can't be used with --invoice-name")
def __validate_scope_and_namespace(scope, release_namespace, target_namespace):
    if scope == 'cluster':
        if target_namespace is not None:
            message = "When --scope is 'cluster', --target-namespace must not be given."
            raise MutuallyExclusiveArgumentError(message)
    else:
        if release_namespace is not None:
            message = "When --scope is 'namespace', --release-namespace must not be given."
            raise MutuallyExclusiveArgumentError(message)
Exemple #5
0
def billing_permission_list_validator(namespace):
    from azure.cli.core.azclierror import MutuallyExclusiveArgumentError

    if namespace.customer_name is not None:
        if namespace.invoice_section_name is not None:
            raise MutuallyExclusiveArgumentError(
                "--customer-name can't be used with --invoice-section-name")

        if namespace.profile_name is not None:
            raise MutuallyExclusiveArgumentError(
                "--customer-name can't be used with --profile-name")
Exemple #6
0
def migration_update_func(cmd,
                          client,
                          resource_group_name,
                          server_name,
                          migration_id,
                          setup_logical_replication=None,
                          db_names=None,
                          overwrite_dbs=None,
                          cutover=None):

    subscription_id = get_subscription_id(cmd.cli_ctx)

    operationSpecified = False
    if setup_logical_replication is True:
        operationSpecified = True
        properties = "{\"properties\": {\"setupLogicalReplicationOnSourceDBIfNeeded\": \"true\"} }"

    if db_names is not None:
        if operationSpecified is True:
            raise MutuallyExclusiveArgumentError(
                "Incorrect Usage: Can only specify one update operation.")
        operationSpecified = True
        prefix = "{ \"properties\": { \"dBsToMigrate\": ["
        db_names_str = "\"" + "\", \"".join(db_names) + "\""
        suffix = "] } }"
        properties = prefix + db_names_str + suffix

    if overwrite_dbs is True:
        if operationSpecified is True:
            raise MutuallyExclusiveArgumentError(
                "Incorrect Usage: Can only specify one update operation.")
        operationSpecified = True
        properties = "{\"properties\": {\"overwriteDBsInTarget\": \"true\"} }"

    if cutover is True:
        if operationSpecified is True:
            raise MutuallyExclusiveArgumentError(
                "Incorrect Usage: Can only specify one update operation.")
        operationSpecified = True
        properties = "{\"properties\": {\"triggerCutover\": \"true\"} }"

    if operationSpecified is False:
        raise RequiredArgumentMissingError(
            "Incorrect Usage: Atleast one update operation needs to be specified."
        )

    r = send_raw_request(
        cmd.cli_ctx, "patch",
        "https://management.azure.com/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DBforPostgreSQL/flexibleServers/{}/migrations/{}?api-version=2020-02-14-privatepreview"
        .format(subscription_id, resource_group_name, server_name,
                migration_id), None, None, properties)

    return r.json()
Exemple #7
0
def update_va_sql_baseline(client,
                           vm_resource_id,
                           workspace_id,
                           server_name,
                           database_name,
                           rule_id,
                           baseline=None,
                           baseline_latest=False,
                           vm_name=None,
                           agent_id=None,
                           vm_uuid=None):

    va_sql_resource_id = _get_va_sql_resource_id(vm_resource_id, server_name,
                                                 database_name, vm_name,
                                                 agent_id, vm_uuid)
    if baseline_latest is True and baseline is None:
        return client.create_or_update(rule_id, workspace_id,
                                       va_sql_resource_id,
                                       RuleResultsInput(latest_scan=True))
    if baseline_latest is False and baseline is not None:
        return client.create_or_update(rule_id, workspace_id,
                                       va_sql_resource_id,
                                       RuleResultsInput(results=baseline))
    raise MutuallyExclusiveArgumentError(
        "Baseline can be set upon either provided baseline or latest results")
def __validate_version_and_auto_upgrade(version, auto_upgrade_minor_version):
    if version is not None:
        if auto_upgrade_minor_version:
            message = "To pin to specific version, auto-upgrade-minor-version must be set to 'false'."
            raise MutuallyExclusiveArgumentError(message)

        auto_upgrade_minor_version = False
Exemple #9
0
def validate_subnet(cmd, namespace):
    '''
    Validates if name or id has been provided. If name has been provided, it assumes the public ip address is in the same group.
    '''
    subnet = namespace.subnet_resource_id
    vnet = namespace.vnet_name

    if vnet and '/' in vnet:
        raise InvalidArgumentValueError(
            "incorrect usage: --subnet ID | --subnet NAME --vnet-name NAME")

    subnet_is_id = is_valid_resource_id(subnet)
    if (subnet_is_id and vnet) or (not subnet_is_id and not vnet):
        raise MutuallyExclusiveArgumentError(
            "incorrect usage: --subnet ID | --subnet NAME --vnet-name NAME")

    if not subnet_is_id and vnet:
        namespace.subnet_resource_id = resource_id(
            subscription=get_subscription_id(cmd.cli_ctx),
            resource_group=namespace.resource_group_name,
            namespace='Microsoft.Network',
            type='virtualNetworks',
            name=vnet,
            child_type_1='subnets',
            child_name_1=subnet)
Exemple #10
0
def billing_profile_show_validator(namespace):

    from azure.cli.core.azclierror import MutuallyExclusiveArgumentError

    if namespace.profile_name is not None and namespace.customer_name is not None:
        raise MutuallyExclusiveArgumentError(
            "--profile-name can't be used with --customer-name")
def validate_param_combos_for_vm(cmd, namespace):
    is_existing = namespace.inventory_item is not None
    is_new = all(getattr(namespace, k) is not None for k in ['vm_template', 'cloud'])
    if not all([any([is_existing, is_new]), (not all([is_existing, is_new]))]):
        raise MutuallyExclusiveArgumentError(
            'Either "inventory_id" has to be specified or both "vm_template" and "cloud" have to be specified.'
        )
    validate_custom_location_name_or_id(cmd, namespace)
    validate_vmmserver_name_or_id(cmd, namespace)
    validate_inventory_item_name_or_id(namespace)
    if is_new:
        namespace.vm_template = get_resource_id(
            cmd,
            namespace.resource_group_name,
            SCVMM_NAMESPACE,
            VMTEMPLATE_RESOURCE_TYPE,
            namespace.vm_template,
        )
        namespace.cloud = get_resource_id(
            cmd,
            namespace.resource_group_name,
            SCVMM_NAMESPACE,
            CLOUD_RESOURCE_TYPE,
            namespace.cloud,
        )
    if namespace.availability_sets is not None and len(namespace.availability_sets) > 1:
        raise InvalidArgumentValueError(
            'Only one availability set can be specified while creating the VM'
        )
Exemple #12
0
def apim_api_schema_create(client, resource_group_name, service_name, api_id, schema_id, schema_type,
                           schema_name=None, schema_path=None, schema_content=None,
                           resource_type=None, no_wait=False):
    """creates or updates an API Schema. """

    if schema_path is not None and schema_content is None:
        api_file = open(schema_path, 'r')
        content_value = api_file.read()
        value = content_value
    elif schema_content is not None and schema_path is None:
        value = schema_content
    elif schema_path is not None and schema_content is not None:
        raise MutuallyExclusiveArgumentError(
            "Can't specify schema_path and schema_content at the same time.")
    else:
        raise RequiredArgumentMissingError(
            "Please either specify schema_path or schema_content.")

    parameters = SchemaContract(
        id=schema_id,
        name=schema_name,
        type=resource_type,
        content_type=schema_type,
        value=value
    )

    return sdk_no_wait(no_wait, client.api_schema.begin_create_or_update,
                       resource_group_name=resource_group_name,
                       service_name=service_name, api_id=api_id, schema_id=schema_id, parameters=parameters)
def datamigration_assessment(connection_string=None,
                             output_folder=None,
                             overwrite=False,
                             config_file_path=None):

    try:

        defaultOutputFolder, exePath = helper.console_app_setup()

        if connection_string is not None and config_file_path is not None:
            raise MutuallyExclusiveArgumentError(
                "Both connection_string and config_file_path are mutually exclusive arguments. Please provide only one of these arguments."
            )

        if connection_string is not None:
            connection_string = " ".join(f"\"{i}\"" for i in connection_string)
            cmd = f'{exePath} Assess --sqlConnectionStrings {connection_string} ' if output_folder is None else f'{exePath} Assess --sqlConnectionStrings {connection_string} --outputFolder "{output_folder}" '
            cmd += '--overwrite False' if overwrite is False else ''
            subprocess.call(cmd, shell=False)
        elif config_file_path is not None:
            helper.validate_config_file_path(config_file_path, "assess")
            cmd = f'{exePath} --configFile "{config_file_path}"'
            subprocess.call(cmd, shell=False)
        else:
            raise RequiredArgumentMissingError(
                'No valid parameter set used. Please provide any one of the these prameters: connection_string, config_file_path'
            )

        # Printing log file path
        logFilePath = os.path.join(defaultOutputFolder, "Logs")
        print(f"Event and Error Logs Folder Path: {logFilePath}")

    except Exception as e:
        raise e
def datamigration_get_sku_recommendation(output_folder=None,
                                         target_platform="Any",
                                         target_sql_instance=None,
                                         target_percentile=95,
                                         scaling_factor=100,
                                         start_time=None,
                                         end_time=None,
                                         overwrite=False,
                                         display_result=False,
                                         elastic_strategy=False,
                                         database_allow_list=None,
                                         database_deny_list=None,
                                         config_file_path=None):

    try:
        defaultOutputFolder, exePath = helper.console_app_setup()

        if output_folder is not None and config_file_path is not None:
            raise MutuallyExclusiveArgumentError(
                "Both output_folder and config_file_path are mutually exclusive arguments. Please provide only one of these arguments."
            )

        if config_file_path is not None:
            helper.validate_config_file_path(config_file_path,
                                             "getskurecommendation")
            cmd = f'{exePath} --configFile "{config_file_path}"'
            subprocess.call(cmd, shell=False)
        else:
            parameterList = {
                "--outputFolder": output_folder,
                "--targetPlatform": target_platform,
                "--targetSqlInstance": target_sql_instance,
                "--scalingFactor": scaling_factor,
                "--targetPercentile": target_percentile,
                "--startTime": start_time,
                "--endTime": end_time,
                "--overwrite": overwrite,
                "--displayResult": display_result,
                "--elasticStrategy": elastic_strategy,
                "--databaseAllowList": database_allow_list,
                "--databaseDenyList": database_deny_list
            }
            cmd = f'{exePath} GetSkuRecommendation'
            for param in parameterList:
                if parameterList[param] is not None and not param.__contains__(
                        "List"):
                    cmd += f' {param} "{parameterList[param]}"'
                elif param.__contains__(
                        "List") and parameterList[param] is not None:
                    parameterList[param] = " ".join(
                        f"\"{i}\"" for i in parameterList[param])
                    cmd += f' {param} {parameterList[param]}'
            subprocess.call(cmd, shell=False)

        # Printing log file path
        logFilePath = os.path.join(defaultOutputFolder, "Logs")
        print(f"Event and Error Logs Folder Path: {logFilePath}")

    except Exception as e:
        raise e
Exemple #15
0
def set_va_sql_baseline(client,
                        vm_resource_id,
                        workspace_id,
                        server_name,
                        database_name,
                        baseline=None,
                        baseline_latest=False,
                        vm_name=None,
                        agent_id=None,
                        vm_uuid=None):

    va_sql_resource_id = _get_va_sql_resource_id(vm_resource_id, server_name,
                                                 database_name, vm_name,
                                                 agent_id, vm_uuid)
    if baseline_latest is True and baseline is None:
        return client.add(workspace_id,
                          _get_va_sql_api_version(),
                          va_sql_resource_id,
                          latest_scan=True)
    if baseline_latest is False and baseline is not None:
        return client.add(workspace_id,
                          _get_va_sql_api_version(),
                          va_sql_resource_id,
                          results=baseline)
    raise MutuallyExclusiveArgumentError(
        "Baseline can be set upon either provided baseline or latest results")
Exemple #16
0
def _get_va_sql_resource_id(vm_resource_id, server_name, database_name, vm_name, agent_id, vm_uuid):

    if vm_name is None and agent_id is None and vm_uuid is None:
        return f'{vm_resource_id}/sqlServers/{server_name}/databases/{database_name}'
    if vm_name is not None and agent_id is not None and vm_uuid is not None:
        vm_identifier = f'{vm_name}_{agent_id}_{vm_uuid}'
        return f'{vm_resource_id}/onPremiseMachines/{vm_identifier}/sqlServers/{server_name}/databases/{database_name}'
    raise MutuallyExclusiveArgumentError('Please specify all of (--vm-name, --agent-id, --vm-uuid) for On-Premise resources, or none, other resource types')
Exemple #17
0
def validate_create(registry_identity, registry_pass, registry_user,
                    registry_server, no_wait):
    if registry_identity and (registry_pass or registry_user):
        raise MutuallyExclusiveArgumentError(
            "Cannot provide both registry identity and username/password")
    if is_registry_msi_system(registry_identity) and no_wait:
        raise MutuallyExclusiveArgumentError(
            "--no-wait is not supported with system registry identity")
    if registry_identity and not is_valid_resource_id(
            registry_identity) and not is_registry_msi_system(
                registry_identity):
        raise InvalidArgumentValueError(
            "--registry-identity must be an identity resource ID or 'system'")
    if registry_identity and ACR_IMAGE_SUFFIX not in (registry_server or ""):
        raise InvalidArgumentValueError(
            "--registry-identity: expected an ACR registry (*.azurecr.io) for --registry-server"
        )
Exemple #18
0
def validate_asp_create(namespace):
    validate_tags(namespace)
    sku = _normalize_sku(namespace.sku)
    _validate_asp_sku(sku, namespace.app_service_environment,
                      namespace.zone_redundant)
    if namespace.is_linux and namespace.hyper_v:
        raise MutuallyExclusiveArgumentError(
            'Usage error: --is-linux and --hyper-v cannot be used together.')
Exemple #19
0
def datamigration_assessment(connection_string=None,
                             output_folder=None,
                             overwrite=False,
                             config_file_path=None):

    try:

        validate_os_env()

        defaultOutputFolder = get_default_output_folder()

        # Assigning base folder path
        baseFolder = os.path.join(defaultOutputFolder, "Downloads")
        exePath = os.path.join(baseFolder, "SqlAssessment.Console.csproj",
                               "SqlAssessment.exe")

        # Creating base folder structure
        if not os.path.exists(baseFolder):
            os.makedirs(baseFolder)

        testPath = os.path.exists(exePath)

        # Downloading console app zip and extracting it
        if not testPath:
            zipSource = "https://sqlassess.blob.core.windows.net/app/SqlAssessment.zip"
            zipDestination = os.path.join(baseFolder, "SqlAssessment.zip")

            urllib.request.urlretrieve(zipSource, filename=zipDestination)
            with ZipFile(zipDestination, 'r') as zipFile:
                zipFile.extractall(path=baseFolder)

        if connection_string is not None and config_file_path is not None:
            raise MutuallyExclusiveArgumentError(
                "Both connection_string and config_file_path are mutually exclusive arguments. Please provide only one of these arguments."
            )

        if connection_string is not None:
            connection_string = ", ".join(f"\"{i}\""
                                          for i in connection_string)
            cmd = f'{exePath} Assess --sqlConnectionStrings {connection_string} ' if output_folder is None else f'{exePath} Assess --sqlConnectionStrings {connection_string} --outputFolder "{output_folder}" '
            cmd += '--overwrite False' if overwrite is False else ''
            subprocess.call(cmd, shell=False)
        elif config_file_path is not None:
            validate_config_file_path(config_file_path)
            cmd = f'{exePath} --configFile "{config_file_path}"'
            subprocess.call(cmd, shell=False)
        else:
            raise RequiredArgumentMissingError(
                'No valid parameter set used. Please provide any one of the these prameters: connection_string, config_file_path'
            )

        # Printing log file path
        logFilePath = os.path.join(defaultOutputFolder, "Logs")
        print(f"Event and Error Logs Folder Path: {logFilePath}")

    except Exception as e:
        raise e
Exemple #20
0
def validate_crr(target_rg_id, rehydration_priority):
    if target_rg_id is None:
        raise RequiredArgumentMissingError(
            "Please provide target resource group using --target-resource-group."
        )

    if rehydration_priority is not None:
        raise MutuallyExclusiveArgumentError(
            "Archive restore isn't supported for secondary region.")
Exemple #21
0
def validate_strict_import(namespace):
    if namespace.strict:
        if namespace.skip_features:
            raise MutuallyExclusiveArgumentError(
                "The option '--skip-features' cannot be used with the '--strict' option."
            )
        if namespace.source != 'file':
            raise InvalidArgumentValueError(
                "The option '--strict' can only be used when importing from a file."
            )
    def __validate_scoring_fe_settings(self, configuration_settings,
                                       configuration_protected_settings):
        isTestCluster = _get_value_from_config_protected_config(
            self.inferenceLoadBalancerHA, configuration_settings,
            configuration_protected_settings)
        isTestCluster = str(isTestCluster).lower() == 'false'
        if isTestCluster:
            configuration_settings['clusterPurpose'] = 'DevTest'
        else:
            configuration_settings['clusterPurpose'] = 'FastProd'
        isAKSMigration = _get_value_from_config_protected_config(
            self.IS_AKS_MIGRATION, configuration_settings,
            configuration_protected_settings)
        isAKSMigration = str(isAKSMigration).lower() == 'true'
        if isAKSMigration:
            configuration_settings['scoringFe.namespace'] = "default"
            configuration_settings[self.IS_AKS_MIGRATION] = "true"
        feSslCertFile = configuration_protected_settings.get(
            self.sslCertPemFile)
        feSslKeyFile = configuration_protected_settings.get(self.sslKeyPemFile)
        allowInsecureConnections = _get_value_from_config_protected_config(
            self.allowInsecureConnections, configuration_settings,
            configuration_protected_settings)
        allowInsecureConnections = str(
            allowInsecureConnections).lower() == 'true'
        if (not feSslCertFile
                or not feSslKeyFile) and not allowInsecureConnections:
            raise InvalidArgumentValueError(
                "Provide ssl certificate and key. "
                "Otherwise explicitly allow insecure connection by specifying "
                "'--configuration-settings allowInsecureConnections=true'")

        feIsNodePort = _get_value_from_config_protected_config(
            self.privateEndpointNodeport, configuration_settings,
            configuration_protected_settings)
        feIsNodePort = str(feIsNodePort).lower() == 'true'
        feIsInternalLoadBalancer = _get_value_from_config_protected_config(
            self.privateEndpointILB, configuration_settings,
            configuration_protected_settings)
        feIsInternalLoadBalancer = str(
            feIsInternalLoadBalancer).lower() == 'true'

        if feIsNodePort and feIsInternalLoadBalancer:
            raise MutuallyExclusiveArgumentError(
                "Specify either privateEndpointNodeport=true or privateEndpointILB=true, but not both."
            )
        if feIsNodePort:
            configuration_settings[
                'scoringFe.serviceType.nodePort'] = feIsNodePort
        elif feIsInternalLoadBalancer:
            configuration_settings[
                'scoringFe.serviceType.internalLoadBalancer'] = feIsInternalLoadBalancer
            logger.warning(
                'Internal load balancer only supported on AKS and AKS Engine Clusters.'
            )
def get_data_from_key_or_file(key, filepath, strip_newline=False):
    if key and filepath:
        raise MutuallyExclusiveArgumentError(
            consts.KEY_AND_FILE_TOGETHER_ERROR,
            consts.KEY_AND_FILE_TOGETHER_HELP)
    data = None
    if filepath:
        data = read_key_file(filepath, strip_newline)
    elif key:
        data = key
    return data
Exemple #24
0
def get_data_from_key_or_file(key, filepath):
    if key != '' and filepath != '':
        raise MutuallyExclusiveArgumentError(
            'Error! Both textual key and key filepath cannot be provided',
            'Try providing the file parameter without providing the plaintext parameter')
    data = ''
    if filepath != '':
        data = read_key_file(filepath)
    elif key != '':
        data = key
    return data
Exemple #25
0
def validate_subnet(ns):
    from msrestazure.tools import is_valid_resource_id

    # vnet_name is depricated, using for backwards compatability
    if ns.vnet_name and not ns.vnet:
        ns.vnet = ns.vnet_name

    if not is_valid_resource_id(ns.subnet) and ((ns.vnet and not ns.subnet) or
                                                (ns.subnet and not ns.vnet)):
        raise CLIError(
            'usage error: --vnet NAME --subnet NAME | --vnet ID --subnet NAME | --subnet ID'
        )

    if (ns.subnet or ns.vnet) and ns.ip_address:
        raise MutuallyExclusiveArgumentError(
            'Can not use "--subnet" or "--vnet" with IP address type "Public".'
        )
    if (ns.subnet or ns.vnet) and ns.dns_name_label:
        raise MutuallyExclusiveArgumentError(
            'Can not use "--subnet" or "--vnet" with "--dns-name-label".')
Exemple #26
0
def validate_assessment(namespace):
    '''
    Validates assessment settings
    '''
    enable_assessment = namespace.enable_assessment
    enable_assessment_schedule = namespace.enable_assessment_schedule
    assessment_weekly_interval = namespace.assessment_weekly_interval
    assessment_monthly_occurrence = namespace.assessment_monthly_occurrence
    assessment_day_of_week = namespace.assessment_day_of_week
    assessment_start_time_local = namespace.assessment_start_time_local

    is_assessment_schedule_provided = False
    if (assessment_weekly_interval is not None
            or assessment_weekly_interval is not None
            or assessment_monthly_occurrence is not None
            or assessment_day_of_week is not None
            or assessment_start_time_local is not None):
        is_assessment_schedule_provided = True

    # Validate conflicting settings
    if (enable_assessment_schedule is False
            and is_assessment_schedule_provided):
        raise InvalidArgumentValueError(
            "Assessment schedule settings cannot be provided while enable-assessment-schedule is False"
        )

    # Validate conflicting settings
    if (enable_assessment is False and is_assessment_schedule_provided):
        raise InvalidArgumentValueError(
            "Assessment schedule settings cannot be provided while enable-assessment is False"
        )

    # Validate necessary fields for Assessment schedule
    if is_assessment_schedule_provided:
        if (assessment_weekly_interval is not None
                and assessment_monthly_occurrence is not None):
            raise MutuallyExclusiveArgumentError(
                "Both assessment-weekly-interval and assessment-montly-occurrence cannot be provided at the same time for Assessment schedule"
            )
        if (assessment_weekly_interval is None
                and assessment_monthly_occurrence is None):
            raise RequiredArgumentMissingError(
                "Either assessment-weekly-interval or assessment-montly-occurrence must be provided for Assessment schedule"
            )
        if assessment_day_of_week is None:
            raise RequiredArgumentMissingError(
                "assessment-day-of-week must be provided for Assessment schedule"
            )
        if assessment_start_time_local is None:
            raise RequiredArgumentMissingError(
                "assessment-start-time-local must be provided for Assessment schedule"
            )
Exemple #27
0
def validate_onedeploy_params(namespace):
    if namespace.src_path and namespace.src_url:
        raise MutuallyExclusiveArgumentError(
            'Only one of --src-path and --src-url can be specified')

    if not namespace.src_path and not namespace.src_url:
        raise RequiredArgumentMissingError(
            'Either of --src-path or --src-url must be specified')

    if namespace.src_url and not namespace.artifact_type:
        raise RequiredArgumentMissingError(
            'Deployment type is mandatory when deploying from URLs. Use --type'
        )
Exemple #28
0
def validate_repository_ref(branch: str, tag: str, semver: str, commit: str):
    num_set_args = 0
    for elem in [branch, tag, semver, commit]:
        if elem:
            num_set_args += 1
    if num_set_args == 0:
        raise RequiredArgumentMissingError(
            consts.REPOSITORY_REF_REQUIRED_VALUES_MISSING_ERROR,
            consts.REPOSITORY_REF_REQUIRED_VALUES_MISSING_HELP)
    if num_set_args == 1:
        return
    raise MutuallyExclusiveArgumentError(
        consts.REPOSITORY_REF_TOO_MANY_VALUES_ERROR,
        consts.REPOSITORY_REF_TOO_MANY_VALUES_HELP)
Exemple #29
0
def _validate_subnet_id(cli_ctx, subnet, vnet_name, resource_group_name):
    subnet_is_id = is_valid_resource_id(subnet)
    if subnet_is_id and not vnet_name:
        return subnet
    if subnet and not subnet_is_id and vnet_name:
        return resource_id(
            subscription=get_subscription_id(cli_ctx),
            resource_group=resource_group_name,
            namespace='Microsoft.Network',
            type='virtualNetworks',
            name=vnet_name,
            child_type_1='subnets',
            child_name_1=subnet)
    raise MutuallyExclusiveArgumentError('Please specify either: --subnet ID or (--subnet NAME and --vnet-name NAME)')
def add_webapp_access_restriction(
        cmd, resource_group_name, name, priority, rule_name=None,
        action='Allow', ip_address=None, subnet=None,
        vnet_name=None, description=None, scm_site=False,
        ignore_missing_vnet_service_endpoint=False, slot=None, vnet_resource_group=None,
        service_tag=None, http_headers=None):
    configs = get_site_configs(cmd, resource_group_name, name, slot)
    if (int(service_tag is not None) + int(ip_address is not None) +
            int(subnet is not None) != 1):
        err_msg = 'Please specify either: --subnet or --ip-address or --service-tag'
        raise MutuallyExclusiveArgumentError(err_msg)

    # get rules list
    access_rules = configs.scm_ip_security_restrictions if scm_site else configs.ip_security_restrictions
    # check for null
    access_rules = access_rules or []

    rule_instance = None
    if subnet:
        vnet_rg = vnet_resource_group if vnet_resource_group else resource_group_name
        subnet_id = _validate_subnet(cmd.cli_ctx, subnet, vnet_name, vnet_rg)
        if not ignore_missing_vnet_service_endpoint:
            _ensure_subnet_service_endpoint(cmd.cli_ctx, subnet_id)
        # check for duplicates
        for rule in list(access_rules):
            if rule.vnet_subnet_resource_id and rule.vnet_subnet_resource_id.lower() == subnet_id.lower():
                raise ArgumentUsageError('Service endpoint rule for: ' + subnet_id + ' already exists. '
                                         'Cannot add duplicate service endpoint rules.')
        rule_instance = IpSecurityRestriction(
            name=rule_name, vnet_subnet_resource_id=subnet_id,
            priority=priority, action=action, tag='Default', description=description)
        access_rules.append(rule_instance)
    elif ip_address:
        rule_instance = IpSecurityRestriction(
            name=rule_name, ip_address=ip_address,
            priority=priority, action=action, tag='Default', description=description)
        access_rules.append(rule_instance)
    elif service_tag:
        rule_instance = IpSecurityRestriction(
            name=rule_name, ip_address=service_tag,
            priority=priority, action=action, tag='ServiceTag', description=description)
        access_rules.append(rule_instance)
    if http_headers:
        logger.info(http_headers)
        rule_instance.headers = _parse_http_headers(http_headers=http_headers)

    result = _generic_site_operation(
        cmd.cli_ctx, resource_group_name, name, 'update_configuration', slot, configs)
    return result.scm_ip_security_restrictions if scm_site else result.ip_security_restrictions