How to use sfctl - 10 common examples

To help you get started, we’ve selected a few sfctl examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / service-fabric-cli / src / sfctl / custom_cluster.py View on Github external
def get_aad_token(endpoint, no_verify):
    #pylint: disable-msg=too-many-locals
    """Get AAD token"""

    auth = ClientCertAuthentication(None, None, no_verify)

    client = ServiceFabricClientAPIs(auth, base_url=endpoint)
    aad_metadata = client.get_aad_metadata()

    if aad_metadata.type != "aad":
        raise CLIError("Not AAD cluster")

    aad_resource = aad_metadata.metadata

    tenant_id = aad_resource.tenant
    authority_uri = aad_resource.login + '/' + tenant_id
    context = adal.AuthenticationContext(authority_uri,
                                         api_version=None)
    cluster_id = aad_resource.cluster
    client_id = aad_resource.client
github microsoft / service-fabric-cli / src / sfctl / custom_cluster.py View on Github external
:param pem: See select command in this file
    :param cert: See select command in this file
    :param key: See select command in this file
    :param ca: See select command in this file
    :param no_verify: See select command in this file

    :return: ClientCertAuthentication
    """
    client_cert = None
    if pem:
        client_cert = pem
    elif cert:
        client_cert = (cert, key)

    return ClientCertAuthentication(client_cert, ca, no_verify)
github microsoft / service-fabric-cli / src / sfctl / apiclient.py View on Github external
if not endpoint:
        raise CLIError('Connection endpoint not found. '
                       'Before running sfctl commands, connect to a cluster using '
                       'the "sfctl cluster select" command. '
                       'If you are seeing this message on Linux after already selecting a cluster, '
                       'you may need to run the command with sudo.')

    no_verify = no_verify_setting()

    if security_type() == 'aad':
        auth = AdalAuthentication(no_verify)
    else:
        cert = cert_info()
        ca_cert = ca_cert_info()
        auth = ClientCertAuthentication(cert, ca_cert, no_verify)

    client = ServiceFabricClientAPIs(auth, base_url=endpoint)

    # client.config.retry_policy has type msrest.pipeline.ClientRetryPolicy
    client.config.retry_policy.total = False
    client.config.retry_policy.policy.total = False

    # msrest defines ClientRetryPolicy in pipline.py.
    # ClientRetryPolicy.__init__ defines values for status_forcelist
    # which is passed to urllib3.util.retry.Retry
    client.config.retry_policy.policy.status_forcelist = None

    return client
github microsoft / service-fabric-cli / src / sfctl / custom_cluster.py View on Github external
def show_connection():
    """Show which Service Fabric cluster this sfctl instance is connected to."""
    endpoint = client_endpoint()

    if not endpoint:
        return None

    return endpoint
github microsoft / service-fabric-cli / src / sfctl / custom_app.py View on Github external
def upload(path, imagestore_string='fabric:ImageStore', show_progress=False, timeout=300,  # pylint: disable=too-many-locals,missing-docstring,too-many-arguments,too-many-branches,too-many-statements
           compress=False, keep_compressed=False, compressed_location=None):

    from sfctl.config import (client_endpoint, no_verify_setting, ca_cert_info,
                              cert_info)
    import requests

    path = _normalize_path(path)
    if compressed_location is not None:
        compressed_location = _normalize_path(compressed_location)

    abspath = validate_app_path(path)
    basename = os.path.basename(abspath)

    endpoint = client_endpoint()
    cert = cert_info()
    ca_cert = True
    if no_verify_setting():
        ca_cert = False
    elif ca_cert_info():
        ca_cert = ca_cert_info()

    if all([no_verify_setting(), ca_cert_info()]):
        raise CLIError('Cannot specify both CA cert info and no verify')

    if not compress and (keep_compressed or compressed_location is not None):
        raise CLIError('--keep-compressed and --compressed-location options are only applicable '
                       'if the --compress option is set')

    compressed_pkg_location = None
    created_dir_path = None
github microsoft / service-fabric-cli / src / sfctl / apiclient.py View on Github external
def create(_):
    """Create a client for Service Fabric APIs."""

    endpoint = client_endpoint()

    if not endpoint:
        raise CLIError('Connection endpoint not found. '
                       'Before running sfctl commands, connect to a cluster using '
                       'the "sfctl cluster select" command. '
                       'If you are seeing this message on Linux after already selecting a cluster, '
                       'you may need to run the command with sudo.')

    no_verify = no_verify_setting()

    if security_type() == 'aad':
        auth = AdalAuthentication(no_verify)
    else:
        cert = cert_info()
        ca_cert = ca_cert_info()
        auth = ClientCertAuthentication(cert, ca_cert, no_verify)
github microsoft / service-fabric-cli / src / sfctl / custom_cluster.py View on Github external
time_since_last_check = datetime.utcnow() - last_check_time
            allowable_time = timedelta(hours=SF_CLI_VERSION_CHECK_INTERVAL)
            if allowable_time > time_since_last_check:
                # Don't perform any checks
                return True
        else:
            # If last_check_time is None, this means that we've not yet set a time, so it's never
            # been checked. Set the initial value.
            set_cluster_version_check_time()

    cluster_auth = get_cluster_auth()

    auth = _get_client_cert_auth(cluster_auth['pem'], cluster_auth['cert'], cluster_auth['key'],
                                 cluster_auth['ca'], cluster_auth['no_verify'])

    client = ServiceFabricClientAPIs(auth, base_url=client_endpoint())

    sfctl_version = get_sfctl_version()

    # Update the timestamp of the last cluster version check
    set_cluster_version_check_time()

    if dummy_cluster_version is None:
        # This command may fail for various reasons. Most common reason as of writing this comment
        # is that the corresponding get_cluster_version API on the cluster doesn't exist.
        try:
            logger.info('Performing cluster version check')
            cluster_version = client.get_cluster_version().version

        except:  # pylint: disable=bare-except
            ex = exc_info()[0]
            logger.info('Check cluster version failed due to error: %s', str(ex))
github microsoft / service-fabric-cli / src / sfctl / custom_app.py View on Github external
url = urlunparse(url_parsed)

                # timeout is (connect_timeout, read_timeout)
                res = sesh.put(url, data=file_opened,
                               timeout=(get_lesser(60, current_time_left), current_time_left))

                res.raise_for_status()
                current_files_count += 1
                print_progress(current_files_count, total_files_count,
                               os.path.normpath(os.path.join(rel_path, single_file)),
                               show_progress, get_timeout_left(target_timeout))

        current_time_left = get_timeout_left(target_timeout)

        if current_time_left == 0:
            raise SFCTLInternalException('Upload has timed out. Consider passing a longer '
                                         'timeout duration.')

        url_path = (
            os.path.normpath(os.path.join('ImageStore', basename,
                                          rel_path, '_.dir'))
        ).replace('\\', '/')
        url_parsed = list(urlparse(endpoint))
        url_parsed[2] = url_path
        url_parsed[4] = urlencode({'api-version': '6.1',
                                   'timeout': current_time_left})
        url = urlunparse(url_parsed)

        res = sesh.put(url,
                       timeout=(get_lesser(60, current_time_left), current_time_left))
        res.raise_for_status()
        current_files_count += 1
github microsoft / service-fabric-cli / src / sfctl / custom_cluster.py View on Github external
def sfctl_cluster_version_matches(cluster_version, sfctl_version):
    """
    Check if the sfctl version and the cluster version is compatible with each other.

    :param cluster_version: str representing the cluster runtime version of the connected cluster
    :param sfctl_version: str representing this sfctl distribution version
    :return: True if they are a match. False otherwise.
    """

    if sfctl_version in ['8.0.0']:

        return cluster_version.startswith('6.5')

    # If we forget to update this code before a new release, the tests which call this method
    # will fail.
    raise SFCTLInternalException(str.format(
        'Invalid sfctl version {0} provided for check against cluster version {1}.',
        sfctl_version,
        cluster_version))
github microsoft / service-fabric-cli / src / sfctl / commands.py View on Github external
)
            group.command(
                'config-versions',
                'get_provisioned_fabric_config_version_info_list'
            )
            group.command('upgrade-status', 'get_cluster_upgrade_progress')
            group.command('recover-system', 'recover_system_partitions')
            group.command('operation-list', 'get_fault_operation_list')
            group.command('operation-cancel', 'cancel_operation')
            group.command('provision', 'provision_cluster')
            group.command('unprovision', 'unprovision_cluster')
            group.command('upgrade-rollback', 'rollback_cluster_upgrade')
            group.command('upgrade-resume', 'resume_cluster_upgrade')

        with CommandGroup(self, 'node', client_func_path,
                          client_factory=client_create) as group:
            group.command('list', 'get_node_info_list')
            group.command('info', 'get_node_info')
            group.command('health', 'get_node_health')
            group.command('load', 'get_node_load_info')
            group.command('disable', 'disable_node')
            group.command('enable', 'enable_node')
            group.command('remove-state', 'remove_node_state')
            group.command('restart', 'restart_node')
            group.command('transition', 'start_node_transition')
            group.command(
                'transition-status',
                'get_node_transition_progress'
            )
            group.command(
                'add-configuration-parameter-overrides',
                'add_configuration_parameter_overrides'