Beispiel #1
0
    def fetch(self, request, project_id: str, cluster_id: str, namespace: str,
              pod: str):
        """获取日志"""

        data = self.params_validate(serializers.FetchLogsSLZ)

        filter = LogFilter(container_name=data["container_name"],
                           previous=data["previous"])
        if data["started_at"] and data['finished_at']:
            filter.since_time = utils.calc_since_time(data["started_at"],
                                                      data['finished_at'])
        else:
            filter.tail_lines = data["tail_lines"]

        client = LogClient(request.ctx_cluster, namespace, pod)
        content = client.fetch_log(filter)
        logs = utils.refine_k8s_logs(content, data['started_at'])

        url_path_prefix = (
            f"/api/logs/projects/{project_id}/clusters/{cluster_id}/namespaces/{namespace}/pods/{pod}/stdlogs/"  # noqa
        )
        previous = utils.calc_previous_page(logs, data, url_path_prefix)

        result = {"logs": logs, "previous": previous}
        return Response(result)
Beispiel #2
0
    async def reader(self):
        client = LogClient(self.ctx_cluster, self.namespace, self.pod)

        async for line in client.stream(self.filter):
            if self.closed is True:
                return

            # k8s返回使用空格分隔
            t, _, log = line.partition(' ')
            data = {"streams": [{'time': t, 'log': log}]}
            try:
                await self.send(text_data=json.dumps(data))
            except Exception as error:
                logger.error("reader error: %s", error)
                return
Beispiel #3
0
    def download(self, request, project_id: str, cluster_id: str,
                 namespace: str, pod: str):
        """下载日志"""
        data = self.params_validate(serializers.DownloadLogsSLZ)

        filter = LogFilter(container_name=data["container_name"],
                           previous=data["previous"],
                           tail_lines=constants.MAX_TAIL_LINES)

        client = LogClient(request.ctx_cluster, namespace, pod)
        content = client.fetch_log(filter)

        ts = timezone.now().strftime("%Y%m%d%H%M%S")
        filename = f"{pod}-{data['container_name']}-{ts}.log"
        response = HttpResponse(content=content,
                                content_type='application/octet-stream')
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        return response