-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
180 lines (137 loc) · 4.69 KB
/
main.py
File metadata and controls
180 lines (137 loc) · 4.69 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
from fastapi import FastAPI, WebSocket, BackgroundTasks, status
import docker
import json
import re
import shlex
import subprocess
import asyncio
import sys
import requests
import os
from typing import Optional, Set, List
from pydantic import BaseModel
from datetime import datetime, time, timedelta
from starlette.endpoints import WebSocket, WebSocketEndpoint
queue: asyncio.Queue = asyncio.Queue()
client = docker.from_env()
app = FastAPI()
@app.get("/health")
def health():
return {"status": "UP"}
@app.get("/containers")
def index():
containers = client.containers.list(all=True)
result = []
for c in containers:
result.append(container2Object(c))
return result
@app.get("/containers/{id}")
def container(id: str):
return getContainerObject(id)
@app.get("/containers/{id}/stop")
def stop(id: str):
c = getContainer(id)
c.stop()
return getContainerObject(id)
@app.get("/containers/{id}/start")
def start(id: str):
c = getContainer(id)
c.start()
return getContainerObject(id)
@app.get("/containers/{id}/restart")
def restart(id: str):
c = getContainer(id)
c.restart()
return getContainerObject(id)
@app.get("/containers/{id}/logs")
def logs(id: str, tail: int = 100, follow: bool = False, timestamp: bool = True, since=None, until=None):
c = getContainer(id)
result = []
print("tail {} {}".format(tail, type(tail)))
for line in c.logs(stream=True, follow=follow, timestamps=timestamp, since=since, until=until, tail=tail):
foo = line.decode().rstrip()
matcher = re.match(
r'(\d{4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2}.\d+Z)', foo)
time = matcher.group()
message = foo.replace(time, '', 1)
result.append({'timestamp': time, 'message': message})
return result
@app.get("/nodes")
def nodes():
result = client.nodes.list()
for n in result:
print(n.__dict__)
class AlertData(BaseModel):
status: Optional[str] = None
labels: Optional[dict] = None
annotations: Optional[dict] = None
startsAt: Optional[datetime] = None
endsAt: Optional[datetime] = None
generatorURL: Optional[str] = None
class AlertMessage(BaseModel):
version: Optional[str] = None
groupKey: Optional[str] = None
truncatedAlerts: Optional[int] = None
status: Optional[str] = None
receiver: Optional[str] = None
groupLabels: Optional[dict] = None
commonLabels: Optional[dict] = None
commonAnnotations: Optional[dict] = None
externalURL: Optional[str] = None
alerts: Optional[List[AlertData]] = None
vxin_hook_url = os.getenv('VXIN_HOOK_URL')
@app.post("/alerts")
def messages(message: AlertMessage):
if not message.alerts:
return
text = ''
for alert in message.alerts:
text += '%s \n ' % (alert.annotations['summary'])
data = {
"msgtype": "markdown",
"markdown": {
"content": re.sub(u'\u0000', "", text)
}
}
print(type(text), json.dumps(data))
result = requests.post(vxin_hook_url, json.dumps(data))
print(result.text)
@app.websocket_route("/logs")
class ShellWSEndpoint(WebSocketEndpoint):
async def on_connect(self, websocket):
await websocket.accept()
while True:
try:
command = await websocket.receive_text()
command = shlex.split(command)
proc = await asyncio.create_subprocess_exec(
*command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT)
self.proc = proc
while True:
data = await proc.stdout.readline()
line = data.decode().strip()
if not line or not len(line):
code = await proc.wait()
self.code = code
break
await websocket.send_text(line)
except BaseException as e: # asyncio.TimeoutError and ws.close()
if hasattr(self, 'proc'):
self.proc.kill()
await websocket.send_text(str(e))
break
finally:
pass
await websocket.close()
async def on_disconnect(self, websocket, close_code):
await websocket.close()
if hasattr(self, 'proc'):
self.proc.kill()
def getContainer(parameter):
return client.containers.get(parameter)
def getContainerObject(parameter):
return container2Object(getContainer(parameter))
def container2Object(container):
return {'id': container.short_id, 'name': container.name, 'status': container.status, 'image': container.image.tags, 'labels': container.labels}