docker.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import os, io, sys, platform, shutil, time, json, datetime
  2. import re, docker, requests
  3. from api.utils import shell_execute
  4. from dotenv import load_dotenv, find_dotenv
  5. import dotenv
  6. from pathlib import Path
  7. from api.utils.common_log import myLogger
  8. from api.utils import shell_execute, const
  9. def pull_images(app_name):
  10. # 备用方法
  11. # 为了防止安装前,用户服务器已经有了镜像。导致安装时镜像不重新拉取,镜像是老的(根据docker-compose.yml 和 .env 获取)
  12. myLogger.info_logger("Pull images complete ...")
  13. def delete_images(app_id):
  14. # 备用方法
  15. # 卸载APP时同时删除dockercompose里面对应的镜像(根据docker-compose.yml 和 .env 获取)
  16. myLogger.info_logger("Delete images complete ...")
  17. def get_process_perc(app_name, real_name):
  18. process_now = "pulling"
  19. if if_app_exits(app_name):
  20. process_now = "creating"
  21. if if_app_running(app_name):
  22. process_now = "initing"
  23. if if_app_access(app_name):
  24. process_now = "running"
  25. return process_now
  26. # 已经是running的app怎么知道它已经能够访问,如页面能进入,如mysql能被客户端连接
  27. def if_app_access(app_name):
  28. return True
  29. def if_app_exits(app_name):
  30. cmd = "docker compose ls -a | grep \'" + app_name + "\\b\'"
  31. output = shell_execute.execute_command_output_all(cmd)
  32. if int(output["code"]) == -1:
  33. return False
  34. else:
  35. return True
  36. def if_app_running(app_name):
  37. cmd = "docker compose ls -a |grep running | grep \'" + app_name + "\\b\'"
  38. output = shell_execute.execute_command_output_all(cmd)
  39. if int(output["code"]) == -1:
  40. return False
  41. else:
  42. return True
  43. def check_appid_exist(app_id):
  44. myLogger.info_logger("Checking check_appid_exist ...")
  45. appList = manage.get_my_app()
  46. find = False
  47. for app in appList:
  48. if app_id == app.app_id:
  49. find = True
  50. break
  51. myLogger.info_logger("Check complete.")
  52. return find
  53. def check_appid_include_rq(app_id):
  54. message = ""
  55. code = None
  56. if app_id == None:
  57. code = const.ERROR_CLIENT_PARAM_BLANK
  58. message = "AppID is null"
  59. elif re.match('^[a-zA-Z0-9]+_[a-z0-9]+$', app_id):
  60. code = const.ERROR_CLIENT_PARAM_Format
  61. message = "APP name can only be composed of numbers and lowercase letters"
  62. elif not docker.check_appid_exist(app_id):
  63. code = const.ERROR_CLIENT_PARAM_NOTEXIST
  64. message = "AppID is not exist"
  65. return code, message
  66. def check_app_id(app_id):
  67. message = ""
  68. code = None
  69. if app_id == None:
  70. code = const.ERROR_CLIENT_PARAM_BLANK
  71. message = "AppID is null"
  72. elif re.match('^[a-zA-Z0-9]+_[a-z0-9]+$', app_id):
  73. code = const.ERROR_CLIENT_PARAM_Format
  74. message = "APP name can only be composed of numbers and lowercase letters"
  75. # elif not docker.check_appid_exist(app_id):
  76. # code = const.ERROR_CLIENT_PARAM_NOTEXIST
  77. # message = "AppID is not exist"
  78. return code, message
  79. def check_app_id(app_id):
  80. message = ""
  81. code = None
  82. if app_id == None:
  83. code = const.ERROR_CLIENT_PARAM_BLANK
  84. message = "AppID is null"
  85. elif re.match('^[a-zA-Z0-9]+_[a-z0-9]+$', app_id):
  86. code = const.ERROR_CLIENT_PARAM_Format
  87. message = "APP name can only be composed of numbers and lowercase letters"
  88. # elif not docker.check_appid_exist(app_id):
  89. # code = const.ERROR_CLIENT_PARAM_NOTEXIST
  90. # message = "AppID is not exist"
  91. return code, message
  92. def check_vm_resource(app_name):
  93. myLogger.info_logger("Checking virtual memory resource ...")
  94. var_path = "/data/library/apps/" + app_name + "/variables.json"
  95. requirements_var = read_var(var_path, 'requirements')
  96. need_cpu_count = int(requirements_var['cpu'])
  97. cpu_count = int(shell_execute.execute_command_output_all("cat /proc/cpuinfo | grep \'core id\'| wc -l")["result"])
  98. if cpu_count < need_cpu_count:
  99. myLogger.info_logger("Check complete: The number of CPU cores is insufficient!")
  100. return False
  101. need_mem_total = int(requirements_var['memory'])
  102. mem = shell_execute.execute_command_output_all("free -m | grep Mem")["result"].split()
  103. mem_total = float(mem[1]) / 1024
  104. if round(mem_total) < need_mem_total:
  105. myLogger.info_logger("Check complete: The total amount of memory is insufficient!")
  106. return False
  107. mem_free = float(mem[3]) / 1024
  108. if need_mem_total > 4 and round(mem_free) < 4:
  109. myLogger.info_logger("Check complete: There is not enough memory left!")
  110. return False
  111. need_disk = int(requirements_var['disk'])
  112. disk_free = float(
  113. shell_execute.execute_command_output_all("df -m --output=avail /")["result"].split("\n")[1]) / 1024
  114. if round(disk_free) < need_disk - 17:
  115. myLogger.info_logger("Check complete: There are not enough disks left!")
  116. return False
  117. myLogger.info_logger("Check complete.")
  118. return True
  119. def check_app_websoft9(app_name):
  120. # websoft9's support applist
  121. myLogger.info_logger("Checking dir...")
  122. path = "/data/library/apps/" + app_name
  123. is_exists = check_directory(path)
  124. return is_exists
  125. def check_directory(path):
  126. try:
  127. shell_execute.execute_command_output_all("ls " + path)
  128. return True
  129. except CommandException as ce:
  130. return False
  131. def check_app_compose(path):
  132. myLogger.info_logger("Checking port...")
  133. port_dic = read_env(path, "APP_.*_PORT")
  134. # 1.判断/data/apps/app_name/.env中的port是否占用,没有被占用,方法结束(get_start_port方法)
  135. for port_name in port_dic:
  136. port_value = get_start_port(port_dic[port_name])
  137. modify_env(path, port_name, port_value)
  138. myLogger.info_logger("Port check complete")
  139. return
  140. def check_app_url(customer_app_name):
  141. myLogger.info_logger("Checking app url...")
  142. # 如果app的.env文件中含有HTTP_URL项目,需要如此设置 HTTP_URL=ip:port
  143. env_path = "/data/apps/" + customer_app_name + "/.env"
  144. if read_env(env_path, "HTTP_URL") != {}:
  145. ip = shell_execute.execute_command_output_all("curl ifconfig.me")["result"]
  146. http_port = list(read_env(path, "APP_HTTP_PORT").values())[0]
  147. url = ip + ":" + http_port
  148. modify_env(path, "HTTP_URL", url)
  149. myLogger.info_logger("App url check complete")
  150. return
  151. def read_env(path, key):
  152. myLogger.info_logger("Read " + path)
  153. output = shell_execute.execute_command_output_all("cat " + path + "|grep " + key)
  154. code = output["code"]
  155. env_dic = {}
  156. if int(code) == 0 and output["result"] != "":
  157. ret = output["result"]
  158. env_list = ret.split()
  159. for env in env_list:
  160. env_dic[env.split("=")[0]] = env.split("=")[1]
  161. myLogger.info_logger("Read " + path + ": " + str(env_dic))
  162. return env_dic
  163. def modify_env(path, env_name, value):
  164. myLogger.info_logger("Modify " + path + "...")
  165. output = shell_execute.execute_command_output_all("sed -n \'/^" + env_name + "/=\' " + path)
  166. if int(output["code"]) == 0 and output["result"] != "":
  167. line_num = output["result"].split("\n")[0]
  168. s = env_name + "=" + value
  169. output = shell_execute.execute_command_output_all("sed -i \'" + line_num + "c " + s + "\' " + path)
  170. if int(output["code"]) == 0:
  171. myLogger.info_logger("Modify " + path + ": Change " + env_name + " to " + value)
  172. def read_var(var_path, var_name):
  173. value = ""
  174. myLogger.info_logger("Read " + var_path)
  175. output = shell_execute.execute_command_output_all("cat " + var_path)
  176. if int(output["code"]) == 0:
  177. var = json.loads(output["result"])
  178. try:
  179. value = var[var_name]
  180. except KeyError:
  181. myLogger.warning_logger("Read " + var_path + ": No key " + var_name)
  182. else:
  183. myLogger.warning_logger(var_path + " not found")
  184. return value
  185. def get_start_port(port):
  186. use_port = port
  187. while True:
  188. cmd = "netstat -ntlp | grep -v only"
  189. output = shell_execute.execute_command_output_all(cmd)
  190. if output["result"].find(use_port) == -1:
  191. break
  192. else:
  193. use_port = str(int(use_port) + 1)
  194. return use_port