manage.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. #!/usr/bin/env python3
  2. import sys
  3. import datetime
  4. import platform
  5. import os
  6. from urllib.request import urlopen, HTTPError
  7. import re
  8. import subprocess
  9. import string
  10. import time
  11. import random
  12. import socket
  13. texts = {
  14. 'hello1': {
  15. 'en': 'SafeLine is a self-hosted WAF(Web Application Firewall) to protect your web apps from attacks and exploits.',
  16. 'zh': 'SafeLine,中文名 "雷池",是一款简单好用, 效果突出的 Web 应用防火墙(WAF),可以保护 Web 服务不受黑客攻击。'
  17. },
  18. 'hello2': {
  19. 'en': 'A web application firewall helps protect web apps by filtering and monitoring HTTP traffic between a web application and the Internet. It typically protects web apps from attacks such as SQL injection, XSS, code injection, os command injection, CRLF injection, ldap injection, xpath injection, RCE, XXE, SSRF, path traversal, backdoor, bruteforce, http-flood, bot abused, among others.',
  20. 'zh': '雷池通过过滤和监控 Web 应用与互 联网之间的 HTTP 流量来保护 Web 服务。可以保护 Web 服务免受 SQL 注入、XSS 、 代码注入、命令注入、CRLF 注入、ldap 注入、xpath 注入、RCE、XXE、SSRF、路径遍历、后门、暴力破解、CC、爬虫 等攻击。'
  21. },
  22. 'talking-group': {
  23. 'en': '\n'
  24. 'https://discord.gg/SVnZGzHFvn\n'
  25. '\n'
  26. 'Join discord group for more informations of SafeLine by above address',
  27. 'zh': '\n'
  28. '▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄\n'
  29. '█ ▄▄▄▄▄ █▀ █▀▀██▀▄▀▀▄▀▄▀▄██ ▄▄▄▄▄ █\n'
  30. '█ █ █ █▀ ▄ █▀▄▄▀▀ ▄█▄ ▀█ █ █ █\n'
  31. '█ █▄▄▄█ █▀█ █▄█▄▀▀▄▀▄ ▀▀▄▄█ █▄▄▄█ █\n'
  32. '█▄▄▄▄▄▄▄█▄█▄█ █▄▀ █ ▀▄▀ █▄█▄▄▄▄▄▄▄█\n'
  33. '█▄ ▄▄ █▄▄ ▄█▄▄▄▄▀▄▀▀▄██ ▄▄▀▄█▄▀ ▀█\n'
  34. '█▄ ▄▀▄ ▄▀▄ ▀ ▄█▀ ▀▄ █▀▀ ▀█▀▄██▄▀▄██\n'
  35. '██ ▀▄█ ▄ ▄▄▀▄▀▀█▄▀▄▄▀▄▀▄ ▄ ▀▄▄▄█▀▀█\n'
  36. '█ █▀▄▀ ▄▀▄▄▀█▀ ▄▄ █▄█▀▀▄▀▀█▄█▄█▀▄██\n'
  37. '█ █ ▀ ▄▀▀ ██▄█▄▄▄▄▄▀▄▀▀▀▄▄▀█▄▀█ ▀█\n'
  38. '█ █ ▀▄ ▄██▀▀ ▄█▀ ▀███▄ ▀▄▀▄▄ ▄▀▄██\n'
  39. '█▀▄▄█ ▄▀▄▀ ▄▀▀▀▄▀▄▀ ▄▀▄ ▄▀ ▄▀█ ▀█\n'
  40. '█ █ █ █▄▀ █▄█▀ ▄▄███▀▀▀▄█▀▄ ▀ ▀▄██\n'
  41. '█▄███▄█▄▄▀▄ █▄█▄▄▄▄▀▀▄█▀▀ ▄▄▄ ▀█ █\n'
  42. '█ ▄▄▄▄▄ █▄▀█ ▄█▀▄ █▀█▄ ▀ █▄█ ▀▄▀█\n'
  43. '█ █ █ █ █▄▀▀▀▄▄▄▀▀▀▀▀▀ ▄▄ ▀█ █\n'
  44. '█ █▄▄▄█ █ ▀█▀ ▄▄▄▄ ▀█ ▀▀▄▀ ▀▀ ▀███\n'
  45. '█▄▄▄▄▄▄▄█▄▄██▄█▄▄█▄██▄██▄▄█▄▄█▄█▄██\n'
  46. '\n'
  47. '微信扫描上方二维码加入雷池项目讨论组'
  48. },
  49. 'input-target-path': {
  50. 'en': 'Input the path to install SafeLine WAF',
  51. 'zh': '请输入雷池 WAF 的安装目录'
  52. },
  53. 'input-mgt-port': {
  54. 'en': 'Input the mgt port',
  55. 'zh': '请输入雷池 WAF 的管理端口'
  56. },
  57. 'python-version-too-low': {
  58. 'en': 'The Python version is too low, Python 3.5 above is required',
  59. 'zh': 'Python 版本过低, 脚本无法运行, 需要 Python 3.5 以上'
  60. },
  61. 'not-a-tty': {
  62. 'en': 'Stdin is not a standard TTY',
  63. 'zh': '运行脚本的方式不对, STDIN 不是标准的 TTY'
  64. },
  65. 'not-root': {
  66. 'en': 'Requires root privileges to run',
  67. 'zh': '需要 root 权限才能运行'
  68. },
  69. 'not-linux': {
  70. 'en': 'SafeLine WAF does not support %s OS yet',
  71. 'zh': '雷池 WAF 暂时不支持 %s 操作系统'
  72. },
  73. 'unsupported-arch': {
  74. 'en': 'SafeLine WAF does not support %s processor yet',
  75. 'zh': '雷池 WAF 暂时不支持 %s 处理器'
  76. },
  77. 'prepare-to-install': {
  78. 'en': 'Will be going to installing SafeLine WAF for you.',
  79. 'zh': '即将为您安装雷池 WAF'
  80. },
  81. 'choice-action': {
  82. 'en': 'Choice what do you want to do',
  83. 'zh': '选择你要执行的动作'
  84. },
  85. 'default-value': {
  86. 'en': 'Keep blank default to',
  87. 'zh': '留空则为默认值'
  88. },
  89. 'ssse3-not-support': {
  90. 'en': 'SSSE3 instruction set not enabled in your CPU',
  91. 'zh': '当前 CPU 未启用 SSSE3 指令集'
  92. },
  93. 'precheck-failed': {
  94. 'en': 'The environment does not meet the installation conditions of SafeLine WAF',
  95. 'zh': '当前环境不符合雷池 WAF 的安装条件'
  96. },
  97. 'precheck-passed': {
  98. 'en': 'Installation environment check passed',
  99. 'zh': '检查安装环境已完成'
  100. },
  101. 'insufficient-memory': {
  102. 'en': 'Remaining memory is less than 1 GB',
  103. 'zh': '剩余内存不足 1 GB'
  104. },
  105. 'docker-not-installed': {
  106. 'en': 'Running SafeLine WAF requires Docker, but Docker is not installed',
  107. 'zh': '运行雷池 WAF 依赖 Docker, 但是 Docker 没安装'
  108. },
  109. 'docker-compose-not-installed': {
  110. 'en': 'Running SafeLine WAF requires Docker Compose, but Docker Compose is not installed',
  111. 'zh': '运行雷池 WAF 依赖 Docker Compose, 但是 Docker Compose 没安装'
  112. },
  113. 'docker-version-too-low': {
  114. 'en': 'Docker version is too low, it does not match SafeLine WAF',
  115. 'zh': 'Docker 版本太低, 不满足雷池 WAF 的安装需求'
  116. },
  117. 'if-install-docker': {
  118. 'en': 'Do you want the latest version of Docker to be automatically installed for you?',
  119. 'zh': '是否需要为你自动安装 Docker 的最新版本'
  120. },
  121. 'if-update-docker': {
  122. 'en': 'Do you want to update your Docker version?',
  123. 'zh': '是否需要为你自动更新 Docker 版本'
  124. },
  125. 'install-docker-failed': {
  126. 'en': 'Failed to install Docker. Please try to install Docker manually before installing SafeLine WAF',
  127. 'zh': '安装 Docker 失败, 请尝试手动安装 Docker 后再来安装雷池 WAF'
  128. },
  129. 'install-docker': {
  130. 'en': 'Docker is being installed for you. It will take a few minutes. Please wait patiently.',
  131. 'zh': '正在为你安装 Docker, 需要几分钟时间, 请耐心等待'
  132. },
  133. 'get-space-failed': {
  134. 'en': 'Unable to query disk capacity of "%s"',
  135. 'zh': '无法查询 "%s" 的磁盘容量'
  136. },
  137. 'remain-disk-capacity': {
  138. 'en': 'Disk capacity of "%s" has %s avaiable',
  139. 'zh': '"%s" 路径有 %s 的空间可用'
  140. },
  141. 'insufficient-disk-capacity': {
  142. 'en': 'Insufficient disk capacity of "%s", at least 5 GB is required to install SafeLine WAF',
  143. 'zh': '"%s" 的磁盘容量不足,安装雷池 WAF 至少需要 5 GB'
  144. },
  145. 'pg-pass-contains-invalid-char': {
  146. 'en': 'The POSTGRES_PASSWORD variable contains special characters and cannot be started normally',
  147. 'zh': 'POSTGRES_PASSWORD 变量包含特殊字符, 无法正常启动'
  148. },
  149. 'invalid-path': {
  150. 'en': '"%s" is not a valid absolute path',
  151. 'zh': '"%s" 不是合法的绝对路径'
  152. },
  153. 'path-exists': {
  154. 'en': '"%s" already exists, please select a new directory',
  155. 'zh': '路径 "%s" 已存在,请选择一个全新的目录'
  156. },
  157. 'fail-to-parse-route': {
  158. 'en': 'Unable to parse /proc/net/route file',
  159. 'zh': '无法解析 /proc/net/route 文件'
  160. },
  161. 'fail-to-download-compose': {
  162. 'en': 'Failed to download docker compose script',
  163. 'zh': '下载 docker compose 脚本失败'
  164. },
  165. 'fail-to-download-reset-tengine': {
  166. 'en': 'Failed to download reset_tengine script',
  167. 'zh': '下载 reset_tengine 脚本失败'
  168. },
  169. 'fail-to-create-dir': {
  170. 'en': 'Unable to create the "%s" directory',
  171. 'zh': '无法创建 "%s" 目录'
  172. },
  173. 'docker-pull': {
  174. 'en': 'Pulling Docker image',
  175. 'zh': '正在拉取 Docker 镜像'
  176. },
  177. 'try-another-image-source': {
  178. 'en': 'Try another image source',
  179. 'zh': '尝试使用其他镜像源'
  180. },
  181. 'image-clean': {
  182. 'en': 'Cleaning Docker image',
  183. "zh": '正在清理 Docker 镜像'
  184. },
  185. 'update-config': {
  186. 'en': 'Updating .env configuration files',
  187. 'zh': '正在更新 .env 配置文件'
  188. },
  189. 'download-compose': {
  190. 'en': 'Downloading the compose.yaml file',
  191. 'zh': '正在下载 compose.yaml 文件'
  192. },
  193. 'download-reset-tengine': {
  194. 'en': 'Downloading the reset_tengine script',
  195. 'zh': '正在下载 reset_tengine.sh 文件'
  196. },
  197. 'fail-to-pull-image': {
  198. 'en': 'Failed to pull Docker image',
  199. 'zh': '拉取 Docker 镜像失败'
  200. },
  201. 'docker-up': {
  202. 'en': 'Starting Docker containers',
  203. 'zh': '正在启动 Docker 容器'
  204. },
  205. 'fail-to-up': {
  206. 'en': 'Failed to start Docker containers',
  207. 'zh': '启动 Docker 容器失败'
  208. },
  209. 'install-finish': {
  210. 'en': 'SafeLine WAF installation completed',
  211. 'zh': '雷池 WAF 安装完成'
  212. },
  213. 'upgrade-finish': {
  214. 'en': 'SafeLine WAF upgrade completed',
  215. 'zh': '雷池 WAF 升级完成'
  216. },
  217. 'go-to-panel': {
  218. 'en': 'SafeLine WAF management panel: https://%s:%s/',
  219. 'zh': '雷池 WAF 管理面板: https://%s:%s/'
  220. }
  221. ,'install': {
  222. 'en': 'INSTALL',
  223. 'zh': '安装'
  224. },
  225. 'repair': {
  226. 'en': 'REPAIR',
  227. 'zh': '修复'
  228. },
  229. 'upgrade': {
  230. 'en': 'UPDRADE',
  231. 'zh': '升级'
  232. },
  233. 'backup': {
  234. 'en': 'BACKUP',
  235. 'zh': '备份'
  236. },
  237. 'yes': {
  238. 'en': 'Yes',
  239. 'zh': '是'
  240. },
  241. 'no': {
  242. 'en': 'No',
  243. 'zh': '否'
  244. },
  245. 'fail-to-get-installed-dir': {
  246. 'en': 'Failed to get installed dir',
  247. 'zh': '未能找到安装目录',
  248. },
  249. 'fail-to-connect-image-source': {
  250. 'en': 'Failed to connect image source',
  251. 'zh': '无法连接到任何镜像源'
  252. },
  253. 'fail-to-connect-docker-source': {
  254. 'en': 'Failed to connect docker source',
  255. 'zh': '无法连接到任何 docker 源'
  256. },
  257. 'fail-to-download-docker-installation': {
  258. 'en': 'Failed to download docker installation',
  259. "zh": '下载 docker 安装脚本失败'
  260. },
  261. 'docker-source': {
  262. 'en': 'Docker source',
  263. "zh": 'docker 源'
  264. },
  265. 'reset-admin': {
  266. 'en': 'Setup admin',
  267. "zh": '设置 admin'
  268. },
  269. 'docker-version': {
  270. 'en': 'Checking docker version',
  271. 'zh': '检查 docker 版本'
  272. },
  273. 'docker-compose-version': {
  274. 'en': 'Checking docker compose version',
  275. 'zh': '检查 docker compose 版本'
  276. },
  277. 'keyboard-interrupt': {
  278. 'en': 'Installation cancelled',
  279. "zh": '取消安装'
  280. },
  281. 'docker-up-iptables-failed': {
  282. 'en': 'Iptables policy error, try to restart docker',
  283. 'zh': 'iptables 规则错误,尝试重启 docker'
  284. },
  285. 'install-channel': {
  286. 'en': 'Installing',
  287. 'zh': '安装通道'
  288. },
  289. 'preview-release': {
  290. 'en': 'Preview',
  291. 'zh': '预览版'
  292. },
  293. 'lts-release': {
  294. 'en': 'LTS',
  295. 'zh': 'LTS 版'
  296. }
  297. }
  298. lang = ''
  299. def text(label, var=()):
  300. t = texts.get(label, {
  301. 'en': 'Unknown "%s" (%s)' % (label, var),
  302. 'zh': '未知变量 "%s" (%s)' % (label, var)
  303. })
  304. return t[lang if lang in t else 'en'] % var
  305. BOLD = 1
  306. DIM = 1
  307. BLINK = 5
  308. REVERSE = 7
  309. RED = 31
  310. GREEN = 32
  311. YELLOW = 33
  312. BLUE = 34
  313. CYAN = 36
  314. DEBUG = False
  315. LTS = False
  316. IMAGE_CLEAN = False
  317. EN = False
  318. INSTALL = False
  319. def color(t, attrs=[], end=True):
  320. t = '\x1B[%sm%s' % (';'.join([str(i) for i in attrs]), t)
  321. if end:
  322. t = t + '\x1B[m'
  323. return t
  324. def banner():
  325. t = r'''
  326. ______ ___ _____ _ ____ ____ _ ________
  327. .' ____ \ .' ..] |_ _| (_) |_ _| |_ _| / \ |_ __ |
  328. | (___ \_| ,--. _| |_ .---. | | __ _ .--. .---. \ \ /\ / / / _ \ | |_ \_|
  329. _.____`. `'_\ : '-| |-' / /__\\ | | _ [ | [ `.-. | / /__\\ \ \/ \/ / / ___ \ | _|
  330. | \____) | // | |, | | | \__., _| |__/ | | | | | | | | \__., \ /\ / _/ / \ \_ _| |_
  331. \______.' \'-;__/ [___] '.__.' |________| [___] [___||__] '.__.' \/ \/ |____| |____| |_____|
  332. '''.strip('\n')
  333. print(color(t + '\n', [GREEN, BLINK]))
  334. class log():
  335. @staticmethod
  336. def _log(c, l, s):
  337. t = datetime.datetime.now().strftime('%H:%M:%S')
  338. print('\r\033[0;%dm[%-5s %s]: %s\033[0m' % (c, l, t, s))
  339. @staticmethod
  340. def debug(s):
  341. if DEBUG:
  342. log._log(DIM, 'DEBUG', s)
  343. @staticmethod
  344. def info(s):
  345. log._log(CYAN, 'INFO', s)
  346. @staticmethod
  347. def warning(s):
  348. log._log(YELLOW, 'WARN', s)
  349. @staticmethod
  350. def error(s):
  351. log._log(RED, 'ERROR', s)
  352. def get_url(url):
  353. try:
  354. response = urlopen(url)
  355. content = response.read()
  356. return content.decode('utf-8')
  357. except Exception as e:
  358. log.error(e)
  359. def ui_read(question, default):
  360. while True:
  361. if default is None:
  362. sys.stdout.write('%s: ' % (
  363. color(question, [GREEN]),
  364. ))
  365. else:
  366. sys.stdout.write('%s %s: ' % (
  367. color(question, [GREEN]),
  368. color('(%s %s)' % (text('default-value'), default), [YELLOW]),
  369. ))
  370. r = input().strip()
  371. if len(r) == 0:
  372. if default is None or len(default) == 0:
  373. continue
  374. r = default
  375. return r
  376. def ui_choice(question, options):
  377. while True:
  378. s_options = '[ %s ]' % ' '.join(['%s.%s' % option for option in options])
  379. s_choices = '(%s)' % '/'.join([option[0] for option in options])
  380. sys.stdout.write('%s %s %s: ' % (color(question, [GREEN]), color(s_options, [YELLOW]), color(s_choices, [YELLOW])))
  381. r = input().strip()
  382. if r in [i[0] for i in options]:
  383. return r
  384. def humen_size(x):
  385. if x >= 1024 * 1024 * 1024 * 1024:
  386. return '%.02f TB' % (x / 1024 / 1024 / 1024 / 1024)
  387. elif x >= 1024 * 1024 * 1024:
  388. return '%.02f GB' % (x / 1024 / 1024 / 1024)
  389. elif x >= 1024 * 1024:
  390. return '%.02f MB' % (x / 1024 / 1024)
  391. elif x >= 1024:
  392. return '%.02f KB' % (x / 1024)
  393. else:
  394. return '%d Bytes'
  395. def rand_subnet():
  396. routes = []
  397. try:
  398. with open('/proc/net/route', 'r') as f:
  399. next(f)
  400. for line in f:
  401. parts = line.split()
  402. if len(parts) < 8:
  403. continue
  404. destination = int(parts[1], 0x10)
  405. if destination == 0:
  406. continue
  407. mask = int(parts[7], 0x10)
  408. routes.append((destination, mask))
  409. except Exception as e:
  410. log.error(text('fail-to-parse-route') + ' ' + str(e))
  411. for i in range(256):
  412. t = 192
  413. t += 168 << 8
  414. t += i << 16
  415. for route in routes:
  416. if t & route[1] == route[0]:
  417. break
  418. else:
  419. return '%d.%d.%d' % (t & 0xFF, (t >> 8) & 0xFF, (t >> 16) & 0xFF)
  420. return '172.22.222'
  421. def free_space(path):
  422. while not os.path.exists(path) and path != '/':
  423. path = os.path.dirname(path)
  424. try:
  425. st = os.statvfs(path)
  426. free_bytes = st.f_bavail * st.f_frsize
  427. return free_bytes
  428. except Exception as e:
  429. log.error(text('get-space-failed', path) + ' ' + str(e))
  430. return None
  431. def free_memory():
  432. t = filter(lambda x: 'MemAvailable' in x, open('/proc/meminfo', 'r').readlines())
  433. return int(next(t).split()[1]) * 1024
  434. def exec_command(*args,shell=False):
  435. try:
  436. proc = subprocess.run(args, check=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True,shell=shell)
  437. subprocess_output(proc.stdout.strip())
  438. return proc.returncode, proc.stdout, proc.stderr
  439. except Exception as e:
  440. return -1, '', str(e)
  441. def exec_command_with_loading(*args, cwd=None, env=None):
  442. try:
  443. with subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, env=env, cwd=cwd) as proc:
  444. if not DEBUG:
  445. loading = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"]
  446. iloading = 0
  447. while proc.poll() is None:
  448. sys.stderr.write('\r' + loading[iloading])
  449. sys.stderr.flush()
  450. iloading = (iloading + 1) % len(loading)
  451. time.sleep(0.1)
  452. sys.stderr.write('\r')
  453. sys.stderr.flush()
  454. else:
  455. for line in iter(proc.stdout.readline, b''):
  456. if line.strip() != '':
  457. log.debug(" -->> "+line.strip())
  458. if proc.poll() is not None and line == '':
  459. break
  460. return proc.returncode, proc.stdout.read(), proc.stderr.read()
  461. except Exception as e:
  462. return -1, '', str(e)
  463. def subprocess_output(stdout):
  464. if stdout != '':
  465. log.debug(" -->> "+stdout)
  466. else:
  467. log.debug(" -->> subprocess empty output")
  468. def start_docker():
  469. return exec_command('systemctl enable docker && systemctl daemon-reload && systemctl restart docker',shell=True)
  470. def check_port(port):
  471. if not INSTALL:
  472. return True
  473. try:
  474. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  475. s.bind(('0.0.0.0', int(port)))
  476. return True
  477. except Exception as e:
  478. log.debug("try listen mgt port failed: "+str(e))
  479. return False
  480. def install_docker():
  481. log.info(text('install-docker'))
  482. log.debug("downloading get-docker.sh")
  483. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/get-docker.sh','get-docker.sh'):
  484. raise Exception(text('fail-to-download-docker-installation'))
  485. source = docker_source()
  486. if source == '':
  487. raise Exception(text('fail-to-connect-docker-source'))
  488. log.debug(text('docker-source')+': '+source)
  489. env = {
  490. "DOWNLOAD_URL": source,
  491. "https_proxy": os.environ.get('https_proxy',''),
  492. }
  493. log.debug("installing docker")
  494. r = exec_command_with_loading('bash get-docker.sh',env=env)
  495. if r[0] == 0:
  496. p = start_docker()
  497. subprocess_output(p[1].strip())
  498. if p[0] != 0:
  499. log.error("start docker failed: "+p[2].strip())
  500. return p[0] == 0
  501. else:
  502. log.error("install docker error: "+r[2].strip())
  503. return False
  504. compose_command = ''
  505. def precheck_docker_compose():
  506. log.info(text("docker-compose-version"))
  507. global compose_command
  508. while True:
  509. version_output = ''
  510. proc = exec_command('docker', 'compose', 'version')
  511. if proc[0] == 0:
  512. help_proc = exec_command('docker', 'compose', 'up', '--help')
  513. if help_proc[0] == 0 and '--detach' in help_proc[1]:
  514. compose_command = 'docker compose'
  515. version_output = proc[1].strip()
  516. else:
  517. log.debug('docker compose can not find detach argument')
  518. else:
  519. compose_proc = exec_command('docker-compose', 'version')
  520. if compose_proc[0] == 0:
  521. help_proc = exec_command('docker-compose', 'up', '--help')
  522. if help_proc[0] == 0 and '--detach' in help_proc[1]:
  523. compose_command = 'docker-compose'
  524. version_output = compose_proc[1].strip()
  525. else:
  526. log.debug('docker-compose can not find detach argument')
  527. else:
  528. log.warning(text('docker-compose-not-installed'))
  529. if version_output != '':
  530. t = re.findall(r'^Docker Compose version v(\d+)\.', version_output)
  531. if len(t) == 0:
  532. log.warning(text('docker-compose-not-installed'))
  533. elif int(t[0]) < 2:
  534. log.warning(text('docker-version-too-low'))
  535. else:
  536. return True
  537. action = ui_choice(text('if-update-docker'), [
  538. ('y', text('yes')),
  539. ('n', text('no')),
  540. ])
  541. if action.lower() == 'n':
  542. return False
  543. elif action.lower() == 'y':
  544. if not install_docker():
  545. log.warning(text('install-docker-failed'))
  546. return False
  547. def precheck():
  548. if platform.machine() in ('x86_64', 'AMD64') and 'ssse3' not in open('/proc/cpuinfo', 'r').read().lower():
  549. log.warning(text('ssse3-not-support'))
  550. return False
  551. if free_memory() < 1024 * 1024 * 1024:
  552. log.warning(text('insufficient-memory'))
  553. return False
  554. log.info(text("docker-version"))
  555. while True:
  556. proc = exec_command('docker', '--version')
  557. if proc[0] == 0:
  558. t = re.findall(r'^Docker version (\d+)\.', proc[1])
  559. if len(t) == 0:
  560. log.warning(text('docker-not-installed'))
  561. elif int(t[0]) < 20:
  562. log.warning(text('docker-version-too-low'))
  563. else:
  564. break
  565. else:
  566. log.warning(text('docker-not-installed'))
  567. action = ui_choice(text('if-install-docker'), [
  568. ('y', text('yes')),
  569. ('n', text('no')),
  570. ])
  571. if action.lower() == 'n':
  572. return False
  573. elif action.lower() == 'y':
  574. if not install_docker():
  575. log.warning(text('install-docker-failed'))
  576. return False
  577. log.info(text("docker-compose-version"))
  578. if not precheck_docker_compose():
  579. return False
  580. return True
  581. def docker_pull(cwd):
  582. log.info(text('docker-pull'))
  583. try:
  584. subprocess.check_call(compose_command+' pull', cwd=cwd, shell=True)
  585. return True
  586. except Exception as e:
  587. log.warning("docker pull error: "+str(e))
  588. return False
  589. def image_clean():
  590. log.info(text('image-clean'))
  591. proc = exec_command('docker image prune -f --filter="label=maintainer=SafeLine-CE"', shell=True)
  592. if proc[0] != 0:
  593. log.warning("remove docker image failed: "+proc[2])
  594. def docker_up(cwd):
  595. log.info(text('docker-up'))
  596. while True:
  597. p = exec_command_with_loading(compose_command+' up -d --remove-orphans', cwd=cwd)
  598. if p[0] == 0:
  599. return True
  600. if 'iptables failed' in p[2]:
  601. log.warning("docker up error: "+p[2])
  602. while True:
  603. action = ui_choice(text('docker-up-iptables-failed'),[
  604. ('y', text('yes')),
  605. ('n', text('no')),
  606. ])
  607. if action.lower() == 'y':
  608. start_docker()
  609. break
  610. elif action.lower() == 'n':
  611. return False
  612. else:
  613. log.error("docker up error: "+p[2])
  614. def get_url_time(url):
  615. now = datetime.datetime.now()
  616. try:
  617. urlopen(url)
  618. except HTTPError as e:
  619. log.debug("get url "+url+" status: "+str(e.status))
  620. if e.status > 499:
  621. return 999999
  622. except Exception as e:
  623. log.debug("get url "+url+" failed: "+str(e))
  624. return 999999
  625. return (datetime.datetime.now() - now).microseconds / 1000
  626. def get_avg_delay(url):
  627. log.debug("test url avg delay: "+url)
  628. total_delay = 0
  629. for i in range(3):
  630. total_delay += get_url_time(url)
  631. avg_delay = total_delay / 3
  632. log.debug("url "+url+" avg delay: "+str(avg_delay))
  633. return avg_delay
  634. pull_failed_prefix = []
  635. def image_source():
  636. source = {
  637. 'https://registry-1.docker.io': 'chaitin',
  638. "https://swr.cn-east-3.myhuaweicloud.com": 'swr.cn-east-3.myhuaweicloud.com/chaitin-safeline'
  639. }
  640. min_delay = -1
  641. image_prefix = ''
  642. for url, prefix in source.items():
  643. if prefix in pull_failed_prefix:
  644. continue
  645. delay = get_avg_delay(url)
  646. if delay > 0 and (min_delay < 0 or delay < min_delay):
  647. min_delay = delay
  648. image_prefix = prefix
  649. log.debug("use image_prefix: "+image_prefix)
  650. return image_prefix
  651. def docker_source():
  652. sources = [
  653. "https://mirrors.aliyun.com/docker-ce/",
  654. "https://mirrors.tencent.com/docker-ce/",
  655. "https://download.docker.com"
  656. ]
  657. min_delay = -1
  658. source = ''
  659. for v in sources:
  660. delay = get_avg_delay(v)
  661. if delay > 0 and (min_delay < 0 or delay < min_delay):
  662. min_delay = delay
  663. source = v
  664. return source
  665. def generate_config(path):
  666. log.info(text('update-config'))
  667. config = {
  668. 'SAFELINE_DIR': path,
  669. 'POSTGRES_PASSWORD': '',
  670. 'MGT_PORT': '',
  671. 'RELEASE': '',
  672. 'REGION': '',
  673. 'IMAGE_PREFIX': '',
  674. 'IMAGE_TAG': '',
  675. 'SUBNET_PREFIX': '',
  676. 'ARCH_SUFFIX': ''
  677. }
  678. env_path = os.path.join(path,'.env')
  679. if os.path.exists(env_path):
  680. with open(env_path, 'r') as f:
  681. for line in f.readlines():
  682. s = line.index('=')
  683. if s > 0:
  684. k = line[:s].strip()
  685. v = line[s + 1:].strip()
  686. config[k] = v
  687. if config['ARCH_SUFFIX'] == '':
  688. if platform.machine() == 'aarch64':
  689. config['ARCH_SUFFIX'] = '-arm'
  690. if config['POSTGRES_PASSWORD'] == '':
  691. config['POSTGRES_PASSWORD'] = ''.join([random.choice(string.ascii_letters + string.digits) for i in range(20)])
  692. if config['SUBNET_PREFIX'] == '':
  693. config['SUBNET_PREFIX'] = rand_subnet()
  694. if config['RELEASE'] == '' and LTS:
  695. config['RELEASE'] = '-lts'
  696. default_try = False
  697. if config['MGT_PORT'] == '9443':
  698. default_try = True
  699. while not config['MGT_PORT'].isnumeric() or int(config['MGT_PORT']) >= 65536 or int(config['MGT_PORT']) <= 0 or not check_port(config['MGT_PORT']):
  700. if not default_try:
  701. config['MGT_PORT'] = '9443'
  702. default_try = True
  703. else:
  704. config['MGT_PORT'] = ui_read(text('input-mgt-port'),None)
  705. if config['REGION'] == '' and EN:
  706. config['REGION'] = '-g'
  707. if not config['POSTGRES_PASSWORD'].isalnum():
  708. log.info(text('pg-pass-contains-invalid-char'))
  709. raise Exception(text('pg-pass-contains-invalid-char'))
  710. if config['IMAGE_PREFIX'] == '' or config['IMAGE_PREFIX'] in pull_failed_prefix:
  711. config['IMAGE_PREFIX'] = image_source()
  712. if config['IMAGE_PREFIX'] == '':
  713. raise Exception(text('fail-to-connect-image-source'))
  714. config['IMAGE_TAG'] = 'latest'
  715. with open(env_path, 'w') as f:
  716. for k in config:
  717. f.write('%s=%s\n' % (k, config[k]))
  718. return config
  719. def show_address(mgt_port):
  720. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  721. s.connect(("8.8.8.8", 80))
  722. local_ip = s.getsockname()[0]
  723. log.info(text('go-to-panel', (local_ip, mgt_port)))
  724. log.info(text('go-to-panel', ('0.0.0.0', mgt_port)))
  725. def reset_admin():
  726. log.info(text('reset-admin'))
  727. while True:
  728. p = exec_command('docker', 'inspect','--format=\'{{.State.Health.Status}}\'', 'safeline-mgt')
  729. if p[0] == 0 and p[1].strip().replace("'",'') == 'healthy':
  730. break
  731. elif p[0] != 0:
  732. log.debug("get safeline-mgt status error: "+str(p[2]))
  733. log.info("wait safeline-mgt healthy, sleep 5s")
  734. time.sleep(5)
  735. proc = exec_command('docker exec safeline-mgt /app/mgt-cli reset-admin --once',shell=True)
  736. if proc[0] != 0:
  737. log.warning(proc[2])
  738. elif proc[1].strip() != '':
  739. log.info('\n'+proc[1].strip())
  740. def install():
  741. global INSTALL
  742. INSTALL = True
  743. log.info(text('prepare-to-install'))
  744. if not precheck():
  745. log.error(text('precheck-failed'))
  746. return
  747. log.info(text('precheck-passed'))
  748. while True:
  749. safeline_path = ui_read(text('input-target-path'), '/data/safeline')
  750. if not safeline_path.startswith('/'):
  751. log.warning(text('invalid-path', safeline_path))
  752. continue
  753. if os.path.exists(safeline_path):
  754. log.warning(text('path-exists', safeline_path))
  755. continue
  756. if free_space(safeline_path) < 5 * 1024 * 1024 * 1024:
  757. log.warning(text('insufficient-disk-capacity'))
  758. continue
  759. break
  760. try:
  761. os.makedirs(safeline_path)
  762. except Exception as e:
  763. log.error(text('fail-to-create-dir', safeline_path) + ' ' + str(e))
  764. return
  765. log.info(text('remain-disk-capacity', (safeline_path, humen_size(free_space(safeline_path)))))
  766. log.info(text('download-compose'))
  767. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/compose.yaml',os.path.join(safeline_path, 'docker-compose.yaml')):
  768. log.error(text('fail-to-download-compose'))
  769. return
  770. if os.path.exists(os.path.join(safeline_path, 'compose.yaml')):
  771. os.rename(os.path.join(safeline_path, 'compose.yaml'),os.path.join(safeline_path, 'compose.yaml.bak'))
  772. log.info(text('download-reset-tengine'))
  773. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/reset_tengine.sh',safeline_path + '/reset_tengine.sh'):
  774. log.error(text('fail-to-download-reset-tengine'))
  775. return
  776. while True:
  777. config = generate_config(safeline_path)
  778. if docker_pull(safeline_path):
  779. break
  780. pull_failed_prefix.append(config['IMAGE_PREFIX'])
  781. log.info(text('try-another-image-source'))
  782. if not docker_up(safeline_path):
  783. log.error(text('fail-to-up'))
  784. return
  785. log.info(text('install-finish'))
  786. reset_admin()
  787. show_address(config['MGT_PORT'])
  788. def get_installed_dir():
  789. safeline_path = ''
  790. safeline_path_proc = exec_command('docker','inspect','--format','\'{{index .Config.Labels "com.docker.compose.project.working_dir"}}\'', 'safeline-mgt')
  791. if safeline_path_proc[0] == 0:
  792. safeline_path = safeline_path_proc[1].strip().replace("'",'')
  793. else:
  794. log.debug("get installed dir error: "+ safeline_path_proc[2])
  795. log.debug("find safeline installed path: " + safeline_path)
  796. if safeline_path == '' or not os.path.exists(safeline_path):
  797. log.warning(text('fail-to-get-installed-dir'))
  798. return ui_read(text('input-target-path'),None)
  799. return safeline_path
  800. def save_file_from_url(url, path):
  801. log.debug('saving '+url+' to '+path)
  802. data = get_url(url)
  803. if data is None:
  804. return False
  805. with open(path, 'w') as f:
  806. f.write(data)
  807. return True
  808. def upgrade():
  809. safeline_path = get_installed_dir()
  810. log.info(text("docker-compose-version"))
  811. if not precheck_docker_compose():
  812. log.error(text('precheck-failed'))
  813. return
  814. log.info(text('download-compose'))
  815. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/compose.yaml', os.path.join(safeline_path, 'docker-compose.yaml')):
  816. log.error(text('fail-to-download-compose'))
  817. return
  818. if os.path.exists(os.path.join(safeline_path, 'compose.yaml')):
  819. os.rename(os.path.join(safeline_path, 'compose.yaml'),os.path.join(safeline_path, 'compose.yaml.bak'))
  820. log.info(text('download-reset-tengine'))
  821. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/reset_tengine.sh',safeline_path + '/reset_tengine.sh'):
  822. log.error(text('fail-to-download-reset-tengine'))
  823. return
  824. while True:
  825. config = generate_config(safeline_path)
  826. if docker_pull(safeline_path):
  827. break
  828. pull_failed_prefix.append(config['IMAGE_PREFIX'])
  829. log.info(text('try-another-image-source'))
  830. if not docker_up(safeline_path):
  831. log.error(text('fail-to-up'))
  832. return
  833. if IMAGE_CLEAN:
  834. image_clean()
  835. log.info(text('upgrade-finish'))
  836. reset_admin()
  837. show_address(config['MGT_PORT'])
  838. pass
  839. def repair():
  840. pass
  841. def backup():
  842. pass
  843. def init_global_config():
  844. global lang
  845. lang = 'zh'
  846. if '--debug' in sys.argv:
  847. global DEBUG
  848. DEBUG = True
  849. if '--lts' in sys.argv:
  850. global LTS
  851. LTS = True
  852. log.info(text('install-channel')+": "+text('lts-release'))
  853. if '--image-clean' in sys.argv:
  854. global IMAGE_CLEAN
  855. IMAGE_CLEAN = True
  856. if '--en' in sys.argv:
  857. global EN
  858. EN = True
  859. lang = 'en'
  860. def main():
  861. banner()
  862. log.info(text('hello1'))
  863. log.info(text('hello2'))
  864. print()
  865. init_global_config()
  866. if sys.version_info.major == 2 or (sys.version_info.major == 3 and sys.version_info.minor <= 5):
  867. log.error(text('python-version-too-low'))
  868. return
  869. if not sys.stdin.isatty():
  870. log.error(text('not-a-tty'))
  871. return
  872. if os.geteuid() != 0:
  873. log.error(text('not-root'))
  874. return
  875. if platform.system() != 'Linux':
  876. log.error(text('not-linux', platform.system()))
  877. return
  878. if platform.machine() not in ('aarch64', 'x86_64', 'AMD64'):
  879. log.error(text('unsupported-arch', platform.machine()))
  880. return
  881. action = ui_choice(text('choice-action'), [
  882. ('1', text('install')),
  883. ('2', text('upgrade')),
  884. # ('3', text('repair')),
  885. # ('4', text('backup'))
  886. ])
  887. if action == '1':
  888. install()
  889. elif action == '2':
  890. upgrade()
  891. # elif action == '3':
  892. # repair()
  893. # elif action == '4':
  894. # backup()
  895. if __name__ == '__main__':
  896. try:
  897. main()
  898. except KeyboardInterrupt:
  899. log.warning(text('keyboard-interrupt'))
  900. pass
  901. except Exception as e:
  902. log.error(e)
  903. finally:
  904. print(color(text('talking-group') + '\n', [GREEN]))