manage.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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. }
  286. lang = ''
  287. def text(label, var=()):
  288. t = texts.get(label, {
  289. 'en': 'Unknown "%s" (%s)' % (label, var),
  290. 'zh': '未知变量 "%s" (%s)' % (label, var)
  291. })
  292. return t[lang if lang in t else 'en'] % var
  293. BOLD = 1
  294. DIM = 1
  295. BLINK = 5
  296. REVERSE = 7
  297. RED = 31
  298. GREEN = 32
  299. YELLOW = 33
  300. BLUE = 34
  301. CYAN = 36
  302. DEBUG = False
  303. LTS = False
  304. IMAGE_CLEAN = False
  305. EN = False
  306. INSTALL = False
  307. def color(t, attrs=[], end=True):
  308. t = '\x1B[%sm%s' % (';'.join([str(i) for i in attrs]), t)
  309. if end:
  310. t = t + '\x1B[m'
  311. return t
  312. def banner():
  313. t = r'''
  314. ______ ___ _____ _ ____ ____ _ ________
  315. .' ____ \ .' ..] |_ _| (_) |_ _| |_ _| / \ |_ __ |
  316. | (___ \_| ,--. _| |_ .---. | | __ _ .--. .---. \ \ /\ / / / _ \ | |_ \_|
  317. _.____`. `'_\ : '-| |-' / /__\\ | | _ [ | [ `.-. | / /__\\ \ \/ \/ / / ___ \ | _|
  318. | \____) | // | |, | | | \__., _| |__/ | | | | | | | | \__., \ /\ / _/ / \ \_ _| |_
  319. \______.' \'-;__/ [___] '.__.' |________| [___] [___||__] '.__.' \/ \/ |____| |____| |_____|
  320. '''.strip('\n')
  321. print(color(t + '\n', [GREEN, BLINK]))
  322. class log():
  323. @staticmethod
  324. def _log(c, l, s):
  325. t = datetime.datetime.now().strftime('%H:%M:%S')
  326. print('\r\033[0;%dm[%-5s %s]: %s\033[0m' % (c, l, t, s))
  327. @staticmethod
  328. def debug(s):
  329. if DEBUG:
  330. log._log(DIM, 'DEBUG', s)
  331. @staticmethod
  332. def info(s):
  333. log._log(CYAN, 'INFO', s)
  334. @staticmethod
  335. def warning(s):
  336. log._log(YELLOW, 'WARN', s)
  337. @staticmethod
  338. def error(s):
  339. log._log(RED, 'ERROR', s)
  340. def get_url(url):
  341. try:
  342. response = urlopen(url)
  343. content = response.read()
  344. return content.decode('utf-8')
  345. except Exception as e:
  346. log.error(e)
  347. def ui_read(question, default):
  348. while True:
  349. if default is None:
  350. sys.stdout.write('%s: ' % (
  351. color(question, [GREEN]),
  352. ))
  353. else:
  354. sys.stdout.write('%s %s: ' % (
  355. color(question, [GREEN]),
  356. color('(%s %s)' % (text('default-value'), default), [YELLOW]),
  357. ))
  358. r = input().strip()
  359. if len(r) == 0:
  360. if default is None or len(default) == 0:
  361. continue
  362. r = default
  363. return r
  364. def ui_choice(question, options):
  365. while True:
  366. s_options = '[ %s ]' % ' '.join(['%s.%s' % option for option in options])
  367. s_choices = '(%s)' % '/'.join([option[0] for option in options])
  368. sys.stdout.write('%s %s %s: ' % (color(question, [GREEN]), color(s_options, [YELLOW]), color(s_choices, [YELLOW])))
  369. r = input().strip()
  370. if r in [i[0] for i in options]:
  371. return r
  372. def humen_size(x):
  373. if x >= 1024 * 1024 * 1024 * 1024:
  374. return '%.02f TB' % (x / 1024 / 1024 / 1024 / 1024)
  375. elif x >= 1024 * 1024 * 1024:
  376. return '%.02f GB' % (x / 1024 / 1024 / 1024)
  377. elif x >= 1024 * 1024:
  378. return '%.02f MB' % (x / 1024 / 1024)
  379. elif x >= 1024:
  380. return '%.02f KB' % (x / 1024)
  381. else:
  382. return '%d Bytes'
  383. def rand_subnet():
  384. routes = []
  385. try:
  386. with open('/proc/net/route', 'r') as f:
  387. next(f)
  388. for line in f:
  389. parts = line.split()
  390. if len(parts) < 8:
  391. continue
  392. destination = int(parts[1], 0x10)
  393. if destination == 0:
  394. continue
  395. mask = int(parts[7], 0x10)
  396. routes.append((destination, mask))
  397. except Exception as e:
  398. log.error(text('fail-to-parse-route') + ' ' + str(e))
  399. for i in range(256):
  400. t = 192
  401. t += 168 << 8
  402. t += i << 16
  403. for route in routes:
  404. if t & route[1] == route[0]:
  405. break
  406. else:
  407. return '%d.%d.%d' % (t & 0xFF, (t >> 8) & 0xFF, (t >> 16) & 0xFF)
  408. return '172.22.222'
  409. def free_space(path):
  410. while not os.path.exists(path) and path != '/':
  411. path = os.path.dirname(path)
  412. try:
  413. st = os.statvfs(path)
  414. free_bytes = st.f_bavail * st.f_frsize
  415. return free_bytes
  416. except Exception as e:
  417. log.error(text('get-space-failed', path) + ' ' + str(e))
  418. return None
  419. def free_memory():
  420. t = filter(lambda x: 'MemAvailable' in x, open('/proc/meminfo', 'r').readlines())
  421. return int(next(t).split()[1]) * 1024
  422. def exec_command(*args,shell=False):
  423. try:
  424. proc = subprocess.run(args, check=False, capture_output=True, universal_newlines=True,shell=shell)
  425. subprocess_output(proc.stdout.strip())
  426. return proc.returncode, proc.stdout, proc.stderr
  427. except Exception as e:
  428. return -1, '', str(e)
  429. def exec_command_with_loading(*args, cwd=None, env=None):
  430. try:
  431. with subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, env=env, cwd=cwd) as proc:
  432. if not DEBUG:
  433. loading = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"]
  434. iloading = 0
  435. while proc.poll() is None:
  436. sys.stderr.write('\r' + loading[iloading])
  437. sys.stderr.flush()
  438. iloading = (iloading + 1) % len(loading)
  439. time.sleep(0.1)
  440. sys.stderr.write('\r')
  441. sys.stderr.flush()
  442. else:
  443. for line in iter(proc.stdout.readline, b''):
  444. if line.strip() != '':
  445. log.debug(" -->> "+line.strip())
  446. if proc.poll() is not None and line == '':
  447. break
  448. return proc.returncode, proc.stdout.read(), proc.stderr.read()
  449. except Exception as e:
  450. return -1, '', str(e)
  451. def subprocess_output(stdout):
  452. if stdout != '':
  453. log.debug(" -->> "+stdout)
  454. else:
  455. log.debug(" -->> subprocess empty output")
  456. def start_docker():
  457. return exec_command('systemctl enable docker && systemctl daemon-reload && systemctl restart docker',shell=True)
  458. def check_port(port):
  459. if not INSTALL:
  460. return True
  461. try:
  462. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  463. s.bind(('0.0.0.0', int(port)))
  464. return True
  465. except Exception as e:
  466. log.debug("try listen mgt port failed: "+str(e))
  467. return False
  468. def install_docker():
  469. log.info(text('install-docker'))
  470. log.debug("downloading get-docker.sh")
  471. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/get-docker.sh','get-docker.sh'):
  472. raise Exception(text('fail-to-download-docker-installation'))
  473. source = docker_source()
  474. if source == '':
  475. raise Exception(text('fail-to-connect-docker-source'))
  476. log.debug(text('docker-source')+': '+source)
  477. env = {
  478. "DOWNLOAD_URL": source,
  479. "https_proxy": os.environ.get('https_proxy',''),
  480. }
  481. log.debug("installing docker")
  482. r = exec_command_with_loading('bash get-docker.sh',env=env)
  483. if r[0] == 0:
  484. p = start_docker()
  485. subprocess_output(p[1].strip())
  486. if p[0] != 0:
  487. log.error("start docker failed: "+p[2].strip())
  488. return p[0] == 0
  489. else:
  490. log.error("install docker error: "+r[2].strip())
  491. return False
  492. compose_command = ''
  493. def precheck_docker_compose():
  494. log.info(text("docker-compose-version"))
  495. global compose_command
  496. while True:
  497. version_output = ''
  498. proc = exec_command('docker', 'compose', 'version')
  499. if proc[0] == 0:
  500. help_proc = exec_command('docker', 'compose', 'up', '--help')
  501. if help_proc[0] == 0 and '--detach' in help_proc[1]:
  502. compose_command = 'docker compose'
  503. version_output = proc[1].strip()
  504. else:
  505. log.debug('docker compose can not find detach argument')
  506. else:
  507. compose_proc = exec_command('docker-compose', 'version')
  508. if compose_proc[0] == 0:
  509. help_proc = exec_command('docker-compose', 'up', '--help')
  510. if help_proc[0] == 0 and '--detach' in help_proc[1]:
  511. compose_command = 'docker-compose'
  512. version_output = compose_proc[1].strip()
  513. else:
  514. log.debug('docker-compose can not find detach argument')
  515. else:
  516. log.warning(text('docker-compose-not-installed'))
  517. if version_output != '':
  518. t = re.findall(r'^Docker Compose version v(\d+)\.', version_output)
  519. if len(t) == 0:
  520. log.warning(text('docker-compose-not-installed'))
  521. elif int(t[0]) < 2:
  522. log.warning(text('docker-version-too-low'))
  523. else:
  524. return True
  525. action = ui_choice(text('if-update-docker'), [
  526. ('y', text('yes')),
  527. ('n', text('no')),
  528. ])
  529. if action.lower() == 'n':
  530. return False
  531. elif action.lower() == 'y':
  532. if not install_docker():
  533. log.warning(text('install-docker-failed'))
  534. return False
  535. def precheck():
  536. if platform.machine() in ('x86_64', 'AMD64') and 'ssse3' not in open('/proc/cpuinfo', 'r').read().lower():
  537. log.warning(text('ssse3-not-support'))
  538. return False
  539. if free_memory() < 1024 * 1024 * 1024:
  540. log.warning(text('insufficient-memory'))
  541. return False
  542. log.info(text("docker-version"))
  543. while True:
  544. proc = exec_command('docker', '--version')
  545. if proc[0] == 0:
  546. t = re.findall(r'^Docker version (\d+)\.', proc[1])
  547. if len(t) == 0:
  548. log.warning(text('docker-not-installed'))
  549. elif int(t[0]) < 20:
  550. log.warning(text('docker-version-too-low'))
  551. else:
  552. break
  553. else:
  554. log.warning(text('docker-not-installed'))
  555. action = ui_choice(text('if-install-docker'), [
  556. ('y', text('yes')),
  557. ('n', text('no')),
  558. ])
  559. if action.lower() == 'n':
  560. return False
  561. elif action.lower() == 'y':
  562. if not install_docker():
  563. log.warning(text('install-docker-failed'))
  564. return False
  565. log.info(text("docker-compose-version"))
  566. if not precheck_docker_compose():
  567. return False
  568. return True
  569. def docker_pull(cwd):
  570. log.info(text('docker-pull'))
  571. try:
  572. subprocess.check_call(compose_command+' pull', cwd=cwd, shell=True)
  573. return True
  574. except Exception as e:
  575. log.warning("docker pull error: "+str(e))
  576. return False
  577. def image_clean():
  578. log.info(text('image-clean'))
  579. proc = exec_command('docker image prune -f --filter="label=maintainer=SafeLine-CE"', shell=True)
  580. if proc[0] != 0:
  581. log.warning("remove docker image failed: "+proc[2])
  582. def docker_up(cwd):
  583. log.info(text('docker-up'))
  584. while True:
  585. p = exec_command_with_loading(compose_command+' up -d --remove-orphans', cwd=cwd)
  586. if p[0] == 0:
  587. return True
  588. if 'iptables failed' in p[2]:
  589. log.warning("docker up error: "+p[2])
  590. while True:
  591. action = ui_choice(text('docker-up-iptables-failed'),[
  592. ('y', text('yes')),
  593. ('n', text('no')),
  594. ])
  595. if action.lower() == 'y':
  596. start_docker()
  597. break
  598. elif action.lower() == 'n':
  599. return False
  600. else:
  601. log.error("docker up error: "+p[2])
  602. def get_url_time(url):
  603. now = datetime.datetime.now()
  604. try:
  605. urlopen(url)
  606. except HTTPError as e:
  607. log.debug("get url "+url+" status: "+str(e.status))
  608. if e.status > 499:
  609. return 999999
  610. except Exception as e:
  611. log.debug("get url "+url+" failed: "+str(e))
  612. return 999999
  613. return (datetime.datetime.now() - now).microseconds / 1000
  614. def get_avg_delay(url):
  615. log.debug("test url avg delay: "+url)
  616. total_delay = 0
  617. for i in range(3):
  618. total_delay += get_url_time(url)
  619. avg_delay = total_delay / 3
  620. log.debug("url "+url+" avg delay: "+str(avg_delay))
  621. return avg_delay
  622. pull_failed_prefix = []
  623. def image_source():
  624. source = {
  625. 'https://registry-1.docker.io': 'chaitin',
  626. "https://swr.cn-east-3.myhuaweicloud.com": 'swr.cn-east-3.myhuaweicloud.com/chaitin-safeline'
  627. }
  628. min_delay = -1
  629. image_prefix = ''
  630. for url, prefix in source.items():
  631. if prefix in pull_failed_prefix:
  632. continue
  633. delay = get_avg_delay(url)
  634. if delay > 0 and (min_delay < 0 or delay < min_delay):
  635. min_delay = delay
  636. image_prefix = prefix
  637. log.debug("use image_prefix: "+image_prefix)
  638. return image_prefix
  639. def docker_source():
  640. sources = [
  641. "https://mirrors.aliyun.com/docker-ce/",
  642. "https://mirrors.tencent.com/docker-ce/",
  643. "https://download.docker.com"
  644. ]
  645. min_delay = -1
  646. source = ''
  647. for v in sources:
  648. delay = get_avg_delay(v)
  649. if delay > 0 and (min_delay < 0 or delay < min_delay):
  650. min_delay = delay
  651. source = v
  652. return source
  653. def generate_config(path):
  654. log.info(text('update-config'))
  655. config = {
  656. 'SAFELINE_DIR': path,
  657. 'POSTGRES_PASSWORD': '',
  658. 'MGT_PORT': '',
  659. 'RELEASE': '',
  660. 'REGION': '',
  661. 'IMAGE_PREFIX': '',
  662. 'IMAGE_TAG': '',
  663. 'SUBNET_PREFIX': '',
  664. 'ARCH_SUFFIX': ''
  665. }
  666. env_path = os.path.join(path,'.env')
  667. if os.path.exists(env_path):
  668. with open(env_path, 'r') as f:
  669. for line in f.readlines():
  670. s = line.index('=')
  671. if s > 0:
  672. k = line[:s].strip()
  673. v = line[s + 1:].strip()
  674. config[k] = v
  675. if config['ARCH_SUFFIX'] == '':
  676. if platform.machine() == 'aarch64':
  677. config['ARCH_SUFFIX'] = '-arm'
  678. if config['POSTGRES_PASSWORD'] == '':
  679. config['POSTGRES_PASSWORD'] = ''.join([random.choice(string.ascii_letters + string.digits) for i in range(20)])
  680. if config['SUBNET_PREFIX'] == '':
  681. config['SUBNET_PREFIX'] = rand_subnet()
  682. if config['RELEASE'] == '' and LTS:
  683. config['RELEASE'] = '-lts'
  684. default_try = False
  685. if config['MGT_PORT'] == '9443':
  686. default_try = True
  687. 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']):
  688. if not default_try:
  689. config['MGT_PORT'] = '9443'
  690. default_try = True
  691. else:
  692. config['MGT_PORT'] = ui_read(text('input-mgt-port'),None)
  693. if config['REGION'] == '' and EN:
  694. config['REGION'] = '-g'
  695. if not config['POSTGRES_PASSWORD'].isalnum():
  696. log.info(text('pg-pass-contains-invalid-char'))
  697. raise Exception(text('pg-pass-contains-invalid-char'))
  698. if config['IMAGE_PREFIX'] == '' or config['IMAGE_PREFIX'] in pull_failed_prefix:
  699. config['IMAGE_PREFIX'] = image_source()
  700. if config['IMAGE_PREFIX'] == '':
  701. raise Exception(text('fail-to-connect-image-source'))
  702. config['IMAGE_TAG'] = 'latest'
  703. with open(env_path, 'w') as f:
  704. for k in config:
  705. f.write('%s=%s\n' % (k, config[k]))
  706. return config
  707. def show_address(mgt_port):
  708. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  709. s.connect(("8.8.8.8", 80))
  710. local_ip = s.getsockname()[0]
  711. log.info(text('go-to-panel', (local_ip, mgt_port)))
  712. log.info(text('go-to-panel', ('0.0.0.0', mgt_port)))
  713. def reset_admin():
  714. log.info(text('reset-admin'))
  715. while True:
  716. p = exec_command('docker', 'inspect','--format=\'{{.State.Health.Status}}\'', 'safeline-mgt')
  717. if p[0] == 0 and p[1].strip().replace("'",'') == 'healthy':
  718. break
  719. elif p[0] != 0:
  720. log.debug("get safeline-mgt status error: "+str(p[2]))
  721. log.info("wait safeline-mgt healthy, sleep 5s")
  722. time.sleep(5)
  723. proc = exec_command('docker exec safeline-mgt /app/mgt-cli reset-admin --once',shell=True)
  724. if proc[0] != 0:
  725. log.warning(proc[2])
  726. elif proc[1].strip() != '':
  727. log.info('\n'+proc[1].strip())
  728. def install():
  729. global INSTALL
  730. INSTALL = True
  731. log.info(text('prepare-to-install'))
  732. if not precheck():
  733. log.error(text('precheck-failed'))
  734. return
  735. log.info(text('precheck-passed'))
  736. while True:
  737. safeline_path = ui_read(text('input-target-path'), '/data/safeline')
  738. if not safeline_path.startswith('/'):
  739. log.warning(text('invalid-path', safeline_path))
  740. continue
  741. if os.path.exists(safeline_path):
  742. log.warning(text('path-exists', safeline_path))
  743. continue
  744. if free_space(safeline_path) < 5 * 1024 * 1024 * 1024:
  745. log.warning(text('insufficient-disk-capacity'))
  746. continue
  747. break
  748. try:
  749. os.makedirs(safeline_path)
  750. except Exception as e:
  751. log.error(text('fail-to-create-dir', safeline_path) + ' ' + str(e))
  752. return
  753. log.info(text('remain-disk-capacity', (safeline_path, humen_size(free_space(safeline_path)))))
  754. log.info(text('download-compose'))
  755. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/compose.yaml',os.path.join(safeline_path, 'docker-compose.yaml')):
  756. log.error(text('fail-to-download-compose'))
  757. return
  758. if os.path.exists(os.path.join(safeline_path, 'compose.yaml')):
  759. os.rename(os.path.join(safeline_path, 'compose.yaml'),os.path.join(safeline_path, 'compose.yaml.bak'))
  760. log.info(text('download-reset-tengine'))
  761. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/reset_tengine.sh',safeline_path + '/reset_tengine.sh'):
  762. log.error(text('fail-to-download-reset-tengine'))
  763. return
  764. while True:
  765. config = generate_config(safeline_path)
  766. if docker_pull(safeline_path):
  767. break
  768. pull_failed_prefix.append(config['IMAGE_PREFIX'])
  769. log.info(text('try-another-image-source'))
  770. if not docker_up(safeline_path):
  771. log.error(text('fail-to-up'))
  772. return
  773. log.info(text('install-finish'))
  774. reset_admin()
  775. show_address(config['MGT_PORT'])
  776. def get_installed_dir():
  777. safeline_path = ''
  778. safeline_path_proc = exec_command('docker','inspect','--format','\'{{index .Config.Labels "com.docker.compose.project.working_dir"}}\'', 'safeline-mgt')
  779. if safeline_path_proc[0] == 0:
  780. safeline_path = safeline_path_proc[1].strip().replace("'",'')
  781. else:
  782. log.debug("get installed dir error: "+ safeline_path_proc[2])
  783. log.debug("find safeline installed path: " + safeline_path)
  784. if safeline_path == '' or not os.path.exists(safeline_path):
  785. log.warning(text('fail-to-get-installed-dir'))
  786. return ui_read(text('input-target-path'),None)
  787. return safeline_path
  788. def save_file_from_url(url, path):
  789. log.debug('saving '+url+' to '+path)
  790. data = get_url(url)
  791. if data is None:
  792. return False
  793. with open(path, 'w') as f:
  794. f.write(data)
  795. return True
  796. def upgrade():
  797. safeline_path = get_installed_dir()
  798. log.info(text("docker-compose-version"))
  799. if not precheck_docker_compose():
  800. log.error(text('precheck-failed'))
  801. return
  802. log.info(text('download-compose'))
  803. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/compose.yaml', os.path.join(safeline_path, 'docker-compose.yaml')):
  804. log.error(text('fail-to-download-compose'))
  805. return
  806. if os.path.exists(os.path.join(safeline_path, 'compose.yaml')):
  807. os.rename(os.path.join(safeline_path, 'compose.yaml'),os.path.join(safeline_path, 'compose.yaml.bak'))
  808. log.info(text('download-reset-tengine'))
  809. if not save_file_from_url('https://waf-ce.chaitin.cn/release/latest/reset_tengine.sh',safeline_path + '/reset_tengine.sh'):
  810. log.error(text('fail-to-download-reset-tengine'))
  811. return
  812. while True:
  813. config = generate_config(safeline_path)
  814. if docker_pull(safeline_path):
  815. break
  816. pull_failed_prefix.append(config['IMAGE_PREFIX'])
  817. log.info(text('try-another-image-source'))
  818. if not docker_up(safeline_path):
  819. log.error(text('fail-to-up'))
  820. return
  821. if IMAGE_CLEAN:
  822. image_clean()
  823. log.info(text('upgrade-finish'))
  824. reset_admin()
  825. show_address(config['MGT_PORT'])
  826. pass
  827. def repair():
  828. pass
  829. def backup():
  830. pass
  831. def init_global_config():
  832. global lang
  833. lang = 'zh'
  834. if '--debug' in sys.argv:
  835. global DEBUG
  836. DEBUG = True
  837. if '--lts' in sys.argv:
  838. global LTS
  839. LTS = True
  840. if '--image-clean' in sys.argv:
  841. global IMAGE_CLEAN
  842. IMAGE_CLEAN = True
  843. if '--en' in sys.argv:
  844. global EN
  845. EN = True
  846. lang = 'en'
  847. def main():
  848. init_global_config()
  849. banner()
  850. log.info(text('hello1'))
  851. log.info(text('hello2'))
  852. print()
  853. if sys.version_info.major == 2 or (sys.version_info.major == 3 and sys.version_info.minor <= 5):
  854. log.error(text('python-version-too-low'))
  855. return
  856. if not sys.stdin.isatty():
  857. log.error(text('not-a-tty'))
  858. return
  859. if os.geteuid() != 0:
  860. log.error(text('not-root'))
  861. return
  862. if platform.system() != 'Linux':
  863. log.error(text('not-linux', platform.system()))
  864. return
  865. if platform.machine() not in ('aarch64', 'x86_64', 'AMD64'):
  866. log.error(text('unsupported-arch', platform.machine()))
  867. return
  868. action = ui_choice(text('choice-action'), [
  869. ('1', text('install')),
  870. ('2', text('upgrade')),
  871. # ('3', text('repair')),
  872. # ('4', text('backup'))
  873. ])
  874. if action == '1':
  875. install()
  876. elif action == '2':
  877. upgrade()
  878. # elif action == '3':
  879. # repair()
  880. # elif action == '4':
  881. # backup()
  882. if __name__ == '__main__':
  883. try:
  884. main()
  885. except KeyboardInterrupt:
  886. log.warning(text('keyboard-interrupt'))
  887. pass
  888. except Exception as e:
  889. log.error(e)
  890. finally:
  891. print(color(text('talking-group') + '\n', [GREEN]))