forked from PNU-P2K/vm-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc_backup_2.py
342 lines (279 loc) · 11.6 KB
/
func_backup_2.py
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
from flask import Flask, render_template, request, jsonify
import os, time
import base64
import hashlib
import yaml
import threading
from Crypto.Cipher import AES
app = Flask(__name__)
BS = 16
pad = (lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode())
unpad = (lambda s: s[:-ord(s[len(s)-1:])])
extractNodeInfos = dict()
extractPodInfos = dict()
extractNodeCPUs = dict()
# pv pod 만드는 함수
def generatePVPodYaml(pvName, storageClassName, pathName) :
PVDefinition = {
"apiVersion": "v1",
"kind": "PersistentVolume",
"metadata": {"name": pvName},
"spec": {
"capacity": {
"storage": "500Mi",
},
"volumeMode": "Filesystem",
"accessModes": ["ReadWriteOnce"],
"storageClassName": storageClassName,
"persistentVolumeReclaimPolicy": "Delete",
"hostPath": {
"path": "/tmp/backup/"+pathName
}
}
}
# YAML로 변환하여 문자열로 반환합니다.
PVYaml = yaml.dump(PVDefinition, default_flow_style=False)
return PVYaml
# pvc pod 만드는 함수
def generatePVCPodYaml(pvcName, storageClassName) :
PVCDefinition = {
"apiVersion": "v1",
"kind": "PersistentVolumeClaim",
"metadata": {"name": pvcName},
"spec": {
"volumeMode": "Filesystem",
"accessModes": ["ReadWriteOnce"],
"storageClassName": storageClassName,
"resources": {
"requests": {
"storage": "500Mi"
}
}
}
}
# YAML로 변환하여 문자열로 반환합니다.
PVCYaml = yaml.dump(PVCDefinition, default_flow_style=False)
return PVCYaml
# deployment pod 만드는 함수
def generateDeploymentPodYaml(deploymentName, containerName, imageName, servicePort, pathName, volumeName, pvcName) :
deploymentDefinition = {
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {"name": deploymentName},
"spec": {
"replicas": 1,
"selector": {
"matchLabels": {
"app": "webdesktop", # service에서 pod를 선택할 때 구별하는 용도
"port": str(servicePort) # port label 추가
}
},
"template": {
"metadata": {
"labels": {
"app": "webdesktop", # 새로운 pod가 생성될 때 template 정의
"port": str(servicePort) # port label 추가
}
},
"spec": {
"containers": [
{
"name": containerName,
"image": imageName,
"ports": [{"containerPort": 6901}], # container 포트는 이미지 받을 때부터 열려있었던 포트인 6901로 접속해야 가능
"volumeMounts": [{
"mountPath": "/var/backups/"+pathName,
"name": volumeName
}]
}
],
"imagePullSecrets": [{"name": "harbor"}], # harbor라는 이름의 kubeconfig.yaml 파일
"volumes": [{
"name": volumeName,
"persistentVolumeClaim": {
"claimName": pvcName
}
}]
}
}
}
}
# YAML로 변환하여 문자열로 반환합니다.
deploymentYaml = yaml.dump(deploymentDefinition, default_flow_style=False)
return deploymentYaml
# deployment pod 만드는 함수
def generateLoadDeploymentPodYaml(deploymentName, containerName, imageName, servicePort, pathName, volumeName, pvcName) :
deploymentDefinition = {
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {"name": deploymentName},
"spec": {
"replicas": 1,
"selector": {
"matchLabels": {
"app": "webdesktop", # service에서 pod를 선택할 때 구별하는 용도
"port": str(servicePort) # port label 추가
}
},
"template": {
"metadata": {
"labels": {
"app": "webdesktop", # 새로운 pod가 생성될 때 template 정의
"port": str(servicePort) # port label 추가
}
},
"spec": {
"containers": [
{
"name": containerName,
"image": imageName,
"ports": [{"containerPort": 6901}], # container 포트는 이미지 받을 때부터 열려있었던 포트인 6901로 접속해야 가능
"volumeMounts": [{
"mountPath": "/var/backups/"+pathName,
"name": volumeName
}],
"command": ["/bin/bash", "-ec", "while :; do echo '.'; sleep 5; done"]
}
],
"imagePullSecrets": [{"name": "harbor"}], # harbor라는 이름의 kubeconfig.yaml 파일
"volumes": [{
"name": volumeName,
"persistentVolumeClaim": {
"claimName": pvcName
}
}]
}
}
}
}
# YAML로 변환하여 문자열로 반환합니다.
deploymentYaml = yaml.dump(deploymentDefinition, default_flow_style=False)
return deploymentYaml
# service pod를 만드는 함수 (pod를 외부로 노출하기 위함)
def generateServiceYaml(serviceName, servicePort, nodePort):
# Service의 기본 구조를 딕셔너리로 정의합니다.
serviceDefinition = {
"apiVersion": "v1",
"kind": "Service",
"metadata": {"name": serviceName},
"spec": {
"type": "NodePort",
"selector": {
"app": "webdesktop",
"port": str(servicePort) # port label 추가
},
"ports": [
{
"port": int(servicePort),
"targetPort": 6901, # deployment의 containerPort와 일치해야 함
"nodePort": int(nodePort) # node_port는 30000~32768
}
]
}
}
# YAML로 변환하여 문자열로 반환합니다.
serviceYaml = yaml.dump(serviceDefinition, default_flow_style=False)
return serviceYaml
# node의 이름과 ip를 추출하기 위한 용도
def extractNodeInfo():
result = os.popen("kubectl get nodes -o wide --kubeconfig /root/kubeconfig.yml").read()
print("result:", result)
nodeInfoList = result.split('\n')[1:-1]
print("nodeInfo: ", nodeInfoList)
for nodeInfo in nodeInfoList:
node = nodeInfo.split()
nodeName, nodeExternalIp = node[0], node[6]
extractNodeInfos[nodeName] = nodeExternalIp
print("extractN: ", extractNodeInfos)
return extractNodeInfos
# pod의 external ip를 알기 위한 함수
def extractPodInfo():
result = os.popen("kubectl get pods -o wide --kubeconfig /root/kubeconfig.yml").read()
print("result:", result)
podInfoList = result.split('\n')[1:-1]
print("podInfo: ", podInfoList)
for podInfo in podInfoList:
pod = podInfo.split()
podName, nodeName = pod[0], pod[6]
extractPodInfos[podName] = nodeName
return extractPodInfos
# pod의 external ip를 알기 위한 함수
def extractNodeIpOfPod(nodeList):
podList = extractPodInfo()
for _, nodeName in podList.items():
if nodeName in nodeList:
return extractNodeInfos[nodeName]
return "Not Found"
# Pod yaml로 생성하기
def applyPodCmd(yamlFilePath):
return "kubectl apply -f " + yamlFilePath + " --kubeconfig /root/kubeconfig.yml"
# label로 Pod 이름 조회하기
def getPodName(port) :
return "kubectl get pod -l port="+port+" -o name --kubeconfig /root/kubeconfig.yml"
# pod 내부로 start.sh 복사하기
def copyScriptToPod(podName, containerName) :
return "kubectl cp /home/ubuntu/start.sh "+podName+":/tmp/ -c "+containerName+" --kubeconfig /root/kubeconfig.yml"
# pv Pod 지우기
def deletePVPodCmd(pvName):
return "kubectl delete pv " + pvName + " --kubeconfig /root/kubeconfig.yml"
# pvc Pod 지우기
def deletePVCPodCmd(pvcName):
return "kubectl delete pvc " + pvcName + " --kubeconfig /root/kubeconfig.yml"
# deployment Pod 지우기
def deleteDeployPodCmd(deploymentName):
return "kubectl delete deployment " + deploymentName + " --kubeconfig /root/kubeconfig.yml"
# service Pod 지우기
def deleteServicePodCmd(serviceName):
return "kubectl delete service " + serviceName + " --kubeconfig /root/kubeconfig.yml"
# yaml 파일 지우기
def deleteYamlFile(yamlFilePath):
return "rm " + yamlFilePath
#===================
# pod namespace 가져오기
def getPodNameSpace(podName):
return f"kubectl get pod {podName} -o custom-columns=NAMESPACE:.metadata.namespace --no-headers --kubeconfig /root/kubeconfig.yml"
# Dockerfile build 함수
def buildDockerImage(imagePath, port, dockerFilePath, parentPath):
os.popen(f"docker build -t {imagePath}:{port} -f {dockerFilePath} {parentPath}")
return f"{imagePath}:{port}"
#=================
# 컨테이너 관련 명령어
def createContainerCmd(port, pwd, imageId) : # vm+port 이름의 컨테이너 생성
vmname = "vm"+port
return "docker create --shm-size=512m -p "+port+":6901 -e VNC_PW="+pwd+" --name "+vmname+" "+imageId
def startContainerCmd(containerId) : # containerid로 컨테이너 실행
return "docker start "+containerId
def stopContainerCmd(containerId) : # containerid로 컨테이너 중지
return "docker stop "+containerId
def deleteContainerCmd(containerId) : # containerid로 컨테이너 삭제
return "docker rm -f "+containerId
def copyScriptToContainer(containerId) :
return "docker cp /home/ubuntu/start.sh "+containerId+":/dockerstartup/"
def copyDesktopToContainer(containerId, vmName) :
return "sudo docker cp /home/dockerFile/backup/"+vmName+"/Desktop/. "+containerId+":/home/kasm-user/Desktop/"
# 이미지 관련 명령어
def createImgCmd(containerId, userId, port) : # registry.p2kcloud.com/base/userid:port 이름의 새로운 이미지 생성
return "docker commit "+containerId+" registry.p2kcloud.com/base/"+userId+":"+port
def pushImgCmd(userId, port) : # harbor에 이미지 저장
return "docker push registry.p2kcloud.com/base/"+userId+":"+port
def deleteImgCmd(imageId) : # imageid로 이미지 삭제
return "docker rmi -f "+imageId
class AESCipher(object):
def __init__(self, key):
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, message):
message = message.encode()
raw = pad(message)
cipher = AES.new(self.key, AES.MODE_CBC, self.__iv().encode('utf8'))
enc = cipher.encrypt(raw)
return base64.b64encode(enc).decode('utf-8')
def decrypt(self, enc):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, self.__iv().encode('utf8'))
dec = cipher.decrypt(enc)
return unpad(dec).decode('utf-8')
def __iv(self):
return chr(0) * 16
key = "thisiskey"
aes = AESCipher(key)
#=====================