Example #1
0
 def __init__(self) -> None:
     if os.path.exists(SERVICE_TOKEN_FILENAME):
         load_incluster_config()
     else:
         load_kube_config()
     self.api = ApiClient()
     version_api = VersionApi(self.api)
     self._is_openshift = "eks" not in version_api.get_code().git_version
Example #2
0
 def fetch_state(self) -> OutpostServiceConnectionState:
     try:
         client = self.client()
         api_instance = VersionApi(client)
         version: VersionInfo = api_instance.get_code()
         return OutpostServiceConnectionState(version=version.git_version,
                                              healthy=True)
     except (OpenApiException, HTTPError, ServiceConnectionInvalid):
         return OutpostServiceConnectionState(version="", healthy=False)
Example #3
0
def check_kubernetes_version(k8s_apiclient):
    # NOTE: the `vX.Y.Z` format is used by Kubernetes, not our buildchain
    configured_version = 'v{}'.format(versions.K8S_VERSION)

    k8s_client = VersionApi(api_client=k8s_apiclient)
    observed_version = k8s_client.get_code().git_version

    assert configured_version == observed_version, (
        "The running version of Kubernetes is '{}', while the expected version"
        "is '{}'.".format(observed_version, configured_version))
Example #4
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       \|    \|/    /(_)    \|      |/      |
           \ |     \ |/       | / \ | /  \|/       |/    \|      \|/
            \|//    \|///    \|//  \|/// \|///    \|//    |//    \|//
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^''')
Example #5
0
    def __call__(self,
                 pl,
                 segment_info,
                 create_watcher=None,
                 context_alert: list = None,
                 namespace_alert: list = None,
                 show_namespace=False,
                 show_user=False,
                 show_version=False):

        if context_alert is None:
            context_alert = []

        if namespace_alert is None:
            namespace_alert = []

        try:
            if segment_info['environ'].get('POWERLINE_K8SSTATUS') == "0":
                return
        except TypeError:
            return

        try:
            contexts, active_context = config.list_kube_config_contexts()
        except TypeError:
            return

        if not contexts:
            return

        context = active_context['name']
        contextstatus = "k8sstatus"

        if context in context_alert:
            contextstatus = "k8sstatus:alert"

        namespacestatus = "k8sstatus_namespace"

        if show_namespace:
            try:
                namespace = active_context['context']['namespace']
                if namespace in namespace_alert:
                    namespacestatus = "k8sstatus_namespace:alert"

            except KeyError:
                namespace = 'default'
        else:
            namespace = 'default'

        user = None
        if show_user:
            user = active_context['context']['user']

        version = None
        if show_version:
            try:
                version = VersionApi(
                    config.load_kube_config()).get_code().git_version
            except (ConnectionRefusedError, MaxRetryError, ConfigException):
                version = None

        return self.build_segments(context, namespace, user, version,
                                   contextstatus, namespacestatus)