Exemplo n.º 1
0
 def get_a_user_create_time(self):
     '''收集所有用户信息'''
     all_user = oclient.OapiApi().list_identity()
     return all_user
def main():
    global start_time
    start_time = time.time()

    parser = argparse.ArgumentParser(
        description='Nagios check for OpenShift deployments.')
    parser.add_argument(
        '--use_pvc',
        help='Include adding a PersistentVolumeClaim in the test.',
        action='store_true',
        dest='use_pvc',
        default=False)
    parser.add_argument(
        '--pvc_delay',
        help='Time in seconds to wait after PVC has been created.',
        dest='pvc_delay',
        default=5)
    parser.add_argument('--timeout',
                        help='How long to wait for the test to finish.',
                        dest='timeout',
                        default=300)
    parser.add_argument('--storage_class',
                        help='What storage class to use if a PVC is created.',
                        dest='storage_class',
                        default=None)

    args = parser.parse_args()

    if args.use_pvc:
        string_to_grep = CHECK_TEXT
    else:
        string_to_grep = 'Welcome to nginx!'

    timeout = int(args.timeout)
    pvc_delay = int(args.pvc_delay)

    try:
        oso_config.load_kube_config()
        kube_config.load_kube_config()
        oso_api = oso_client.OapiApi()
        kube_api = kube_client.CoreV1Api()
        rnd = random.randint(0, 999)
        namespace = 'nrpe-check-{}-{}'.format(
            datetime.datetime.now().strftime('%y-%m-%d-%H-%M-%S'), rnd)
    except:
        print('Unexpected error:', sys.exc_info()[0])
        exit_with_stats(NAGIOS_STATE_CRITICAL)

    try:
        route_url = create_nginx(oso_api, kube_api, namespace, args.use_pvc,
                                 pvc_delay, args.storage_class)
        poll_nginx(route_url, string_to_grep, timeout)
    except kube_client.rest.ApiException as e:
        print(e)
        exit_with_stats(NAGIOS_STATE_CRITICAL)
    except PollTimeoutException as e:
        print(e)
        exit_with_stats(NAGIOS_STATE_CRITICAL)
    except requests.exceptions.ConnectionError as e:
        print(e)
        exit_with_stats(NAGIOS_STATE_CRITICAL)
    except:
        print('Unexpected error: ', sys.exc_info()[0])
        exit_with_stats(NAGIOS_STATE_CRITICAL)
    finally:
        # Cleanup is more reliable if we sleep few seconds here (with openshift 3.11)
        # Increased sleep time from 5 > 15 > 25 for avoiding nrpe namespace stuck
        time.sleep(25)
        cleanup(oso_api, namespace)

    exit_with_stats(NAGIOS_STATE_OK)
Exemplo n.º 3
0
                  'false').lower() in ['true', 'yes', 'y', '1']:
    c.Spawner.environment.update(dict(JUPYTER_ENABLE_LAB='true'))

# Setup location for customised template files.

c.JupyterHub.template_paths = ['/opt/app-root/src/templates']

# Configure KeyCloak as authentication provider.

from openshift import client, config

with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace') as fp:
    namespace = fp.read().strip()

config.load_incluster_config()
oapi = client.OapiApi()

routes = oapi.list_namespaced_route(namespace)


def extract_hostname(routes, name):
    for route in routes.items:
        if route.metadata.name == name:
            return route.spec.host


jupyterhub_name = os.environ.get('JUPYTERHUB_SERVICE_NAME')
jupyterhub_hostname = extract_hostname(routes, jupyterhub_name)
print('jupyterhub_hostname', jupyterhub_hostname)

keycloak_name = os.environ.get('KEYCLOAK_SERVICE_NAME')
Exemplo n.º 4
0
def initiateAPI(cluster):
    """ Function to make an oapi Object. """
    config.load_kube_config(context=cluster)
    oapi = oclient.OapiApi()
    return oapi
def cmdrun_setup(**kwargs):
    try:
        docker.DockerClient(base_url='unix://var/run/docker.sock',
                            version='auto')
    except Exception as e:
        print(
            "Error! Failed to connect to Docker client. Please ensure it is running. Exception: %s"
            % e)
        exit(1)

    try:
        openshift_config.load_kube_config()

        #        base64.b64decode(username = kubernetes_client.configuration.get_basic_auth_token().split(' ')[1]))
        #        print(kubernetes_client.configuration.password)
        oapi = openshift_client.OapiApi()
        projlist = oapi.list_project()

    except Exception as e:
        print(
            "\nError! Failed to list namespaces on OpenShift cluster. Please ensure OCP is running."
        )
        print("Exception: %s" % e)
        exit(1)

    try:
        helper = OpenShiftObjectHelper(api_version='v1', kind='user')
        user_body = {'metadata': {'name': 'apb-developer'}}
        helper.create_object(body=user_body)
    except Exception as e:
        print("\nError! Failed to create APB developer user. Exception: %s" %
              e)

    try:
        crb = create_cluster_role_binding('apb-development', 'apb-developer')
        print(crb)
    except Exception as e:
        print("\nError! %s" % e)

    broker_installed = False
    svccat_installed = False
    proj_default_access = False

    for project in projlist.items:
        name = project.metadata.name
        if name == "default":
            proj_default_access = True
        elif "ansible-service-broker" in name:
            broker_installed = True
        elif "service-catalog" in name:
            svccat_installed = True
    if broker_installed is False:
        print(
            "Error! Could not find OpenShift Ansible Broker namespace. Please ensure that the broker is\
                installed and that the current logged in user has access.")
        exit(1)
    if svccat_installed is False:
        print(
            "Error! Could not find OpenShift Service Catalog namespace. Please ensure that the Service\
                Catalog is installed and that the current logged in user has access."
        )
    if proj_default_access is False:
        print(
            "Error! Could not find the Default namespace. Please ensure that the current logged in user has access."
        )
Exemplo n.º 6
0
 def _get_client(self, context):
     conf = config.new_client_from_config(context=context)
     return (os_client.OapiApi(conf), k8s_client.CoreV1Api(conf))
Exemplo n.º 7
0
from openshift import client as oclient
from kubernetes import client, config

config.load_kube_config()
oapi = oclient.OapiApi()
api = client.CoreV1Api()

projects = oapi.list_project().items
print("Below projects exists in our cluster")
for project in projects:
    print(project)