|
| 1 | +import json |
| 2 | +import asyncio |
| 3 | +import collections |
| 4 | +from django.conf import settings |
| 5 | + |
| 6 | +from asgiref.sync import sync_to_async |
| 7 | + |
| 8 | +from kubernetes.client import Configuration |
| 9 | +from kubernetes.client.api import core_v1_api |
| 10 | +from kubernetes.stream import stream |
| 11 | + |
| 12 | +from channels.db import database_sync_to_async |
| 13 | +from channels.exceptions import DenyConnection |
| 14 | +from channels.generic.websocket import AsyncWebsocketConsumer |
| 15 | + |
| 16 | +from .models.app import App |
| 17 | +from .permissions import has_app_permission |
| 18 | + |
| 19 | + |
| 20 | +Request = collections.namedtuple("Request", ["user", "method"]) |
| 21 | + |
| 22 | + |
| 23 | +class AppPodExecConsumer(AsyncWebsocketConsumer): |
| 24 | + |
| 25 | + @property |
| 26 | + def kubernetes(self): |
| 27 | + with open('/var/run/secrets/kubernetes.io/serviceaccount/token') as token_file: |
| 28 | + token = token_file.read() |
| 29 | + config = Configuration(host=settings.SCHEDULER_URL) |
| 30 | + config.api_key = {"authorization": "Bearer " + token} |
| 31 | + config.verify_ssl = settings.K8S_API_VERIFY_TLS |
| 32 | + if config.verify_ssl: |
| 33 | + config.ssl_ca_cert = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" |
| 34 | + Configuration.set_default(config) |
| 35 | + return core_v1_api.CoreV1Api() |
| 36 | + |
| 37 | + async def check(self): |
| 38 | + self.id = self.scope["url_route"]["kwargs"]["id"] |
| 39 | + self.pod_id = self.scope["url_route"]["kwargs"]["pod_id"] |
| 40 | + if self.scope["user"] is None: |
| 41 | + return False, "user not login" |
| 42 | + request = Request(self.scope["user"], "POST") |
| 43 | + app = await database_sync_to_async(App.objects.get)(id=self.id) |
| 44 | + return await database_sync_to_async(has_app_permission)(request, app) |
| 45 | + |
| 46 | + async def connect(self): |
| 47 | + self.stream = None |
| 48 | + self.conneted = True |
| 49 | + is_ok, message = await self.check() |
| 50 | + if is_ok: |
| 51 | + await self.accept() |
| 52 | + else: |
| 53 | + raise DenyConnection(message) |
| 54 | + |
| 55 | + async def send(self, data): |
| 56 | + if data is None: |
| 57 | + return |
| 58 | + elif isinstance(data, bytes): |
| 59 | + await super().send(bytes_data=data) |
| 60 | + elif isinstance(data, str): |
| 61 | + await super().send(text_data=data) |
| 62 | + |
| 63 | + async def task(self): |
| 64 | + while self.stream.is_open() and self.conneted: |
| 65 | + self.stream.update(timeout=9) |
| 66 | + if await sync_to_async(self.stream.peek_stdout)(): |
| 67 | + data = self.stream.read_stdout() |
| 68 | + elif await sync_to_async(self.stream.peek_stderr)(): |
| 69 | + data = self.stream.peek_stderr() |
| 70 | + else: |
| 71 | + data = None |
| 72 | + await self.send(data) |
| 73 | + |
| 74 | + async def disconnect(self, close_code): |
| 75 | + if self.stream: |
| 76 | + self.stream.close() |
| 77 | + self.conneted = False |
| 78 | + |
| 79 | + async def receive(self, text_data=None, bytes_data=None): |
| 80 | + if self.stream is None and text_data is not None: |
| 81 | + args = (self.kubernetes.connect_get_namespaced_pod_exec, self.pod_id, self.id) |
| 82 | + kwargs = json.loads(text_data) |
| 83 | + kwargs.update({"stderr": True, "stdout": True}) |
| 84 | + if kwargs["stdin"]: |
| 85 | + kwargs.update({"_preload_content": False}) |
| 86 | + self.stream = stream(*args, **kwargs) |
| 87 | + asyncio.create_task(self.task()) |
| 88 | + else: |
| 89 | + await self.send(stream(*args, **kwargs)) |
| 90 | + await self.close(code=1000) |
| 91 | + elif self.stream is not None: |
| 92 | + data = text_data if text_data else bytes_data |
| 93 | + await sync_to_async(self.stream.write_stdin)(data) |
| 94 | + else: |
| 95 | + raise ValueError("This operation is not supported!") |
0 commit comments