1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| import threading import urllib3
from kubernetes import client, utils from kubernetes.stream import stream
from apps.k8s import models
urllib3.disable_warnings()
class K8sApi(object):
def __init__(self, cluster=None, label_selector=None, namespace=None,): self.cluster = cluster self.label_selector = label_selector self.namespace = namespace
def get_client(self): k8s_qs = models.K8s.objects.get(name=self.cluster) token = k8s_qs.token baseurl = k8s_qs.api_server aConfiguration = client.Configuration() aConfiguration.host = baseurl aConfiguration.verify_ssl = False aConfiguration.api_key = {"authorization": "Bearer " + token} aApiClient = client.ApiClient(aConfiguration) return aApiClient
def get_pod_log(self, name, namespace, container, number): if not number: number = 100 aApiClient = self.get_client() client_v1 = client.CoreV1Api(aApiClient) pod_log = client_v1.read_namespaced_pod_log( name, namespace, container=container, pretty=True, tail_lines=number, timestamps=True) return pod_log
def get_pod_log_stream(self, name, namespace, container, number): """ 实时日志 """ aApiClient = self.get_client() client_v1 = client.CoreV1Api(aApiClient) log_stream = client_v1.read_namespaced_pod_log( name=name, namespace=namespace, container=container, follow=True, pretty=True, _preload_content=False, timestamps=True, tail_lines=number ).stream() return log_stream
class K8SLogStreamThread(threading.Thread): def __init__(self, websocket, container_stream): super(K8SLogStreamThread, self).__init__() self.websocket = websocket self.stream = container_stream
def run(self): for s in self.stream: if s: self.websocket.send(bytes_data=s) else: self.websocket.close()
|