Ejemplo n.º 1
0
def main():
    # INFO furiousassault: backward compatibility rough attempt
    # must be removed later according to https://github.com/2gis/k8s-handle/issues/40
    deprecation_warnings = 0
    filtered_arguments = []

    for argument in sys.argv[1:]:
        if argument in [
                '--sync-mode=true', '--sync-mode=True', '--dry-run=true',
                '--dry-run=True'
        ]:
            deprecation_warnings += 1
            filtered_arguments.append(argument.split('=')[0])
            continue

        if argument in [
                '--sync-mode=false', '--sync-mode=False', '--dry-run=false',
                '--dry-run=False'
        ]:
            deprecation_warnings += 1
            continue

        filtered_arguments.append(argument)

    args, unrecognized_args = parser.parse_known_args(filtered_arguments)

    if deprecation_warnings or unrecognized_args:
        log.warning(
            "Explicit true/false arguments to --sync-mode and --dry-run keys are deprecated "
            "and will be discontinued in the future. Use these keys without arguments instead."
        )

    args = vars(args)
    kubeconfig_namespace = None
    settings.CHECK_STATUS_TRIES = args.get('tries')
    settings.CHECK_DAEMONSET_STATUS_TRIES = args.get('tries')
    settings.CHECK_STATUS_TIMEOUT = args.get('retry_delay')
    settings.CHECK_DAEMONSET_STATUS_TIMEOUT = args.get('retry_delay')
    settings.GET_ENVIRON_STRICT = args.get('strict')
    settings.COUNT_LOG_LINES = args.get('tail_lines')
    settings.CONFIG_FILE = args.get('config') or settings.CONFIG_FILE

    try:
        context = config.load_context_section(args['section'])
        render = templating.Renderer(settings.TEMPLATES_DIR)
        resources = render.generate_by_context(context)
        evaluator = config.PriorityEvaluator(args, context, os.environ)

        if evaluator.environment_deprecated():
            log.warning(
                "K8S_HOST and K8S_CA environment variables support is deprecated "
                "and will be discontinued in the future. Use K8S_MASTER_URI and K8S_CA_BASE64 instead."
            )

        if args.get('dry_run'):
            return

        # INFO rvadim: https://github.com/kubernetes-client/python/issues/430#issuecomment-359483997
        if args.get('use_kubeconfig'):
            try:
                load_kube_config()
                kubeconfig_namespace = list_kube_config_contexts()[1].get(
                    'context').get('namespace')
            except Exception as e:
                raise RuntimeError(e)
        else:
            client.Configuration.set_default(
                evaluator.k8s_client_configuration())

        settings.K8S_NAMESPACE = evaluator.k8s_namespace_default(
            kubeconfig_namespace)
        log.info('Default namespace "{}"'.format(settings.K8S_NAMESPACE))

        if not settings.K8S_NAMESPACE:
            log.info(
                "Default namespace is not set. "
                "This may lead to provisioning error, if namespace is not set for each resource."
            )

        p = Provisioner(args['command'], args.get('sync_mode'),
                        args.get('show_logs'))
        d = ApiDeprecationChecker(
            client.VersionApi().get_code().git_version[1:])

        for resource in resources:
            d.run(resource)

        for resource in resources:
            p.run(resource)

    except templating.TemplateRenderingError as e:
        log.error('Template generation error: {}'.format(e))
        sys.exit(1)
    except InvalidYamlError as e:
        log.error('{}'.format(e))
        sys.exit(1)
    except DeprecationError as e:
        log.error('Deprecation warning: {}'.format(e))
        sys.exit(1)
    except RuntimeError as e:
        log.error('RuntimeError: {}'.format(e))
        sys.exit(1)
    except ProvisioningError:
        sys.exit(1)

    print(r'''
                         _(_)_                          wWWWw   _
             @@@@       (_)@(_)   vVVVv     _     @@@@  (___) _(_)_
            @@()@@ wWWWw  (_)\    (___)   _(_)_  @@()@@   Y  (_)@(_)
             @@@@  (___)     `|/    Y    (_)@(_)  @@@@   \|/   (_)
              /      Y       \|    \|/    /(_)    \|      |/      |
           \ |     \ |/       | / \ | /  \|/       |/    \|      \|/
            \|//    \|///    \|//  \|/// \|///    \|//    |//    \|//
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^''')
Ejemplo n.º 2
0
def main():
    # INFO furiousassault: backward compatibility rough attempt
    # must be removed later according to https://github.com/2gis/k8s-handle/issues/40
    deprecation_warnings = 0
    filtered_arguments = []

    for argument in sys.argv[1:]:
        if argument in ['--sync-mode=true', '--sync-mode=True', '--dry-run=true', '--dry-run=True']:
            deprecation_warnings += 1
            filtered_arguments.append(argument.split('=')[0])
            continue

        if argument in ['--sync-mode=false', '--sync-mode=False', '--dry-run=false', '--dry-run=False']:
            deprecation_warnings += 1
            continue

        filtered_arguments.append(argument)

    args, unrecognized_args = parser.parse_known_args(filtered_arguments)

    if deprecation_warnings or unrecognized_args:
        log.warning("Explicit true/false arguments to --sync-mode and --dry-run keys are deprecated "
                    "and will be removed in the future. Use these keys without arguments instead.")

    if 'config' in args and args.config:
        settings.CONFIG_FILE = args.config

    if 'tries' in args:
        settings.CHECK_STATUS_TRIES = args.tries
        settings.CHECK_DAEMONSET_STATUS_TRIES = args.tries

    if 'retry_delay' in args:
        settings.CHECK_STATUS_TIMEOUT = args.retry_delay
        settings.CHECK_DAEMONSET_STATUS_TIMEOUT = args.retry_delay

    if 'strict' in args:
        settings.GET_ENVIRON_STRICT = args.strict

    if 'tail_lines' in args:
        settings.COUNT_LOG_LINES = args.tail_lines

    show_logs = False

    if 'show_logs' in args:
        show_logs = args.show_logs

    try:
        context = config.load_context_section(args.section)
        render = templating.Renderer(settings.TEMPLATES_DIR)
        resources = render.generate_by_context(context)
        # INFO rvadim: https://github.com/kubernetes-client/python/issues/430#issuecomment-359483997

        if args.dry_run:
            return

        if 'use_kubeconfig' in args and args.use_kubeconfig:
            load_kube_config()
            namespace = list_kube_config_contexts()[1].get('context').get('namespace')

            if not namespace:
                raise RuntimeError("Unable to determine namespace of current context")

            settings.K8S_NAMESPACE = namespace
        else:
            Configuration.set_default(get_client_config(context))
            check_required_vars(context, ['k8s_master_uri', 'k8s_token', 'k8s_ca_base64', 'k8s_namespace'])

        if context.get('k8s_namespace'):
            settings.K8S_NAMESPACE = context.get('k8s_namespace')

        log.info('Default namespace "{}"'.format(settings.K8S_NAMESPACE))
        p = Provisioner(args.command, args.sync_mode, show_logs)
        d = ApiDeprecationChecker(VersionApi().get_code().git_version[1:])

        for resource in resources:
            d.run(resource)

        for resource in resources:
            p.run(resource)

    except templating.TemplateRenderingError as e:
        log.error('Template generation error: {}'.format(e))
        sys.exit(1)
    except InvalidYamlError as e:
        log.error('{}'.format(e))
        sys.exit(1)
    except DeprecationError as e:
        log.error('Deprecation warning: {}'.format(e))
        sys.exit(1)
    except RuntimeError as e:
        log.error('RuntimeError: {}'.format(e))
        sys.exit(1)
    except ProvisioningError:
        sys.exit(1)

    print('''
                         _(_)_                          wWWWw   _
             @@@@       (_)@(_)   vVVVv     _     @@@@  (___) _(_)_
            @@()@@ wWWWw  (_)\    (___)   _(_)_  @@()@@   Y  (_)@(_)
             @@@@  (___)     `|/    Y    (_)@(_)  @@@@   \|/   (_)
              /      Y       \|    \|/    /(_)    \|      |/      |
           \ |     \ |/       | / \ | /  \|/       |/    \|      \|/
            \|//    \|///    \|//  \|/// \|///    \|//    |//    \|//
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^''')