This repository has been archived by the owner on Dec 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Base.py
155 lines (139 loc) · 5.78 KB
/
Base.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
#!/usr/bin/env python
# coding:utf-8
from .Loger import getLogger, DEBUG, console, file_hand
from .SSHClient import SSH
from subprocess import Popen, PIPE
from tempfile import mktemp
from functools import partial
import os, sys, time,socket
from datetime import datetime
from .Config import Config
class DockerIsExist(Exception):
pass
class MasterIsExist(Exception):
pass
class NodeIsExist(Exception):
pass
class BaseObject(Config):
tmp = mktemp()
def __init__(self, conf):
super(BaseObject,self).__init__(conf)
self.before = datetime.now()
self.logger = getLogger(name='kubernetes')
self.logger.setLevel(DEBUG)
self.logger.propagate = False
self.logger.addHandler(console)
self.logger.addHandler(file_hand)
self.ScriptPath = os.getcwd()
if self.SshPkey:
keypass = self.SshPkeypass if self.SshPkeypass else None
self.SSH = partial(SSH, port=int(self.SshPort),user=self.SshUsername,pKey=self.SshPkey,keypass=keypass)
else:
self.SSH = partial(SSH, port=int(self.SshPort),user=self.SshUsername,passwd=self.SshPassword)
self.ALL_IP = set(self.Nodes.values())
self.Masters = self.ChooseMasters()
self.logger.debug(self.ALL_IP)
def ChooseMasters(self):
if len(self.Nodes.values()) % 2 != 1:
self.logger.error(u"请使用奇数节点!!否则无法部署集群!")
sys.exit(-1)
masters = []
for name,node in self.Nodes.items():
if "master" in name:
masters.append(node)
if not masters and len(self.Nodes.values()) >= 3:
masters.extend(self.Nodes.values()[0:3])
elif not masters:
masters.extend(self.Nodes.values())
return masters
def FindKeyFromValue(self,dic, v):
return {value:key for key,value in dic.items()}[v]
def _Systemd_Check(self, ip, name):
ssh = self.SSH(ip)
for _ in range(120):
msg, stat = ssh.runner('systemctl is-active {}'.format(name))
if msg.strip() == 'active':
self.logger.info("%s %s install successfully!",ip,name)
return self.logger.debug(ssh.runner('systemctl status %s',name))
self.logger.warning("%s %s status:%s",ip,name,msg)
time.sleep(30)
self.logger.debug(ssh.runner('systemctl status %s',name))
else:
self.logger.error("%s %s start fail!!",ip,name)
sys.exit(-1)
def checker(self,ip):
ssh = self.SSH(ip)
kubelet, stat = ssh.runner("systemctl is-active kubelet")
docker, stat = ssh.runner("systemctl is-active docker")
self.logger.debug(kubelet.strip())
self.logger.debug(docker.strip())
if kubelet.strip() == 'active':
raise NodeIsExist(u"{}: kubelet 程序已经在运行,请检查节点!!".format(ip))
if docker.strip() == 'active':
raise DockerIsExist(u"{}: docker 程序已经在运行,请检查节点!!".format(ip))
def InitCheck(self):
self.logger.info(u"安装前检查是否已经存在k8s环境")
for ip in self.ALL_IP:
self.checker(ip)
def _SSL_sender(self, path, remotepath, ip):
ssh = self.SSH(ip)
for files in os.listdir(path):
src = os.path.join(path, files)
dst = os.path.join(remotepath, files)
if files.endswith('.service'):
dst = os.path.join('/etc/systemd/system', files)
ssh.push(src, dst, ip)
def CheckRuning(self, name, ip):
self.logger.info(u"%s 正在启动中!",name)
ssh = self.SSH(ip)
while True:
msg, stat = ssh.runner('kubectl get pods --all-namespaces|grep "{}"'.format(name))
self.logger.debug(msg)
if msg:
for line in msg.split('\r\n'):
if line:
self.logger.debug(line)
try:
namespaces, podname, ready, status, restarts, age = line.split()
except ValueError as e:
self.logger.error(line)
self.logger.error(e)
break
if status != 'Running':
self.logger.warning(' '.join((podname, ready, status)))
break
else:
self.logger.info(' '.join((podname, ready, status)))
else:
break
time.sleep(20)
return self.logger.info("%s install successfully!",name)
def subPopen(self, cmd):
self.logger.debug(cmd)
o = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
return self.logger.debug({
'stdout': o.stdout.read(),
'stderr': o.stderr.read()
})
def testcmd(self,ip,cmd):
print(cmd)
msg = self.SSH(ip).runner(cmd)
print(msg)
def testshell(self,ip,shell):
print(shell)
ssh = self.SSH(ip)
lst = ssh.do_script(shell)
print(lst)
def TestSshPort(self,ip,port):
while True:
try:
so = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
so.settimeout(30)
so.connect((ip,int(port)))
respon = so.recv(1024)
if 'SSH' in respon:
self.logger.debug(respon)
self.logger.debug("%s: %s",ip,"successfully!!")
return so.close()
except Exception , e:
self.logger.error("%s: %s",ip,e)