#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#

import os
import socket
import time
from kubernetes import K8sConfig, K8sObject, K8sContainer, K8sPod, K8sReplicationController, K8sSecret
from kubernetes.K8sExceptions import NotFoundException

kubeconfig_fallback = '{0}/.kube/config'.format(os.path.abspath(os.path.dirname(os.path.realpath(__file__))))


def is_reachable(api_host):
    scheme, host, port = api_host.replace("//", "").split(':')
    try:
        s = socket.create_connection((host, port), timeout=1)
        s.close()
        return True
    except Exception:
        return False


def create_container(model=None, name=None, image="redis"):
    if model is None:
        obj = K8sContainer(name=name, image=image)
    else:
        obj = K8sContainer(model=model)
    return obj


def create_config():
    try:
        config = K8sConfig(kubeconfig=kubeconfig_fallback)
    except SyntaxError:
        config = K8sConfig()
    except IOError:
        config = K8sConfig()
    return config


def create_object(config=None, name=None, obj_type=None):
    if config is None:
        config = create_config()
    obj = K8sObject(config=config, name=name, obj_type=obj_type)
    return obj


def create_pod(config=None, name=None):
    if config is None:
        config = create_config()
    obj = K8sPod(config=config, name=name)
    return obj


def create_rc(config=None, name=None, replicas=0):
    if config is None:
        config = create_config()
    obj = K8sReplicationController(config=config, name=name, replicas=replicas)
    return obj


def create_secret(config=None, name=None):
    if config is None:
        config = create_config()
    obj = K8sSecret(config=config, name=name)
    return obj


def cleanup_objects():
    cleanup_pods()


def cleanup_pods():
    pod = create_pod(name="throwaway")
    if is_reachable(pod.config.api_host):
        pods = pod.list()
        for p in pods:
            result = K8sPod.get_by_name(name=p['metadata']['name'])
            try:
                [x.delete() for x in result]
            except NotFoundException:
                continue
        time.sleep(3)  # let the pods die
@@ -690,32 +690,39 @@
 except Exception
+ as err
 :%0A        return
@@ -1034,68 +1034,17 @@
 ept 
-SyntaxError:%0A        config = K8sConfig()%0A    except IOError
+Exception
 :%0A  
@@ -1836,26 +1836,145 @@
 ):%0A    c
-leanup_pod
+onfig = K8sConfig(kubeconfig=kubeconfig_fallback)%0A    if is_reachable(config.api_host):%0A        cleanup_pods()%0A        cleanup_rc
 s()%0A%0A%0Ade
@@ -2133,21 +2133,20 @@
         
-resul
+_lis
 t = K8sP
@@ -2246,13 +2246,410 @@
  in 
-resul
+_list%5D%0A            except NotFoundException:%0A                continue%0A        time.sleep(2)  # let the pods die%0A%0A%0Adef cleanup_rcs():%0A    rc = create_rc(name=%22throwaway%22)%0A    if is_reachable(rc.config.api_host):%0A        rcs = rc.list()%0A        for rc in rcs:%0A            _list = K8sReplicationController.get_by_name(name=rc%5B'metadata'%5D%5B'name'%5D)%0A            try:%0A                %5Bx.delete() for x in _lis
 t%5D%0A 
@@ -2733,9 +2733,9 @@
 eep(
-3
+2
 )  #
@@ -2731,28 +2731,48 @@
 sleep(2)  # let the 
-pod
+replication controller
 s die
+%0A

add method for cleanup of replication controllers