File size: 14,991 Bytes
08c964e | 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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | import copy
import json
import os.path
import sys
import time
import traceback
from typing import List, Tuple, Optional
from .bt_formater import _ConfileLink
_VHOST_PATH = "/www/server/panel/vhost"
_NGINX_PATH = "/www/server/nginx"
if "/www/server/panel/class" not in sys.path:
sys.path.insert(0, "/www/server/panel/class")
import public
class ConfigFileUtil:
def __init__(self, tmp_config_path: str):
site_data = []
with open(os.path.join(tmp_config_path, "site_conf.json"), "r") as f:
site_data = json.load(f)
self.site_data = site_data
self._tmp_path = tmp_config_path
self.test_filter_file = []
for site in site_data:
for o_file in site["other_files"]:
self.test_filter_file.append(o_file)
self.test_filter_file.append(site["config_file"])
def test_env(self) -> _ConfileLink:
return _ConfileLink(
(os.path.join(self._tmp_path, "conf"), _NGINX_PATH + "/conf"),
(os.path.join(self._tmp_path, "vhost"), _VHOST_PATH),
files_filter=self.test_filter_file
)
# 将除了网站之外的配置文件也应用上
def use2panel(self):
_ConfileLink(
(os.path.join(self._tmp_path, "conf"), _NGINX_PATH + "/conf"),
(os.path.join(self._tmp_path, "vhost"), _VHOST_PATH),
files_filter=self.test_filter_file
).set_to()
def unuse(self):
_ConfileLink(
(os.path.join(self._tmp_path, "conf"), _NGINX_PATH + "/conf"),
(os.path.join(self._tmp_path, "vhost"), _VHOST_PATH),
files_filter=self.test_filter_file
).reset_from()
class CreateSiteUtil:
def __init__(self, tmp_config_path: str):
self._proxy_main = None
self.tmp_config_path = tmp_config_path
def create_proxy_site(self, proxy_site: dict):
site_id = 0
site_nginx_config_file = "/www/server/panel/vhost/nginx/{}.conf".format(proxy_site["name"])
def remove_site():
if site_id:
public.M("sites").where("id=?", [site_id]).delete()
public.M("domain").where("pid=?", [site_id]).delete()
try:
for o_file in proxy_site["other_files"]:
_real_file = o_file.replace(os.path.join(self.tmp_config_path, "vhost"), _VHOST_PATH)
if os.path.exists(_real_file):
os.remove(_real_file)
if os.path.exists(site_nginx_config_file):
os.remove(site_nginx_config_file)
except:
traceback.print_exc()
try:
init_proxy_conf = self._proxy_init_config()
init_proxy_conf["subs_filter"] = False
init_proxy_conf["site_name"] = proxy_site["name"]
init_proxy_conf["domain_list"] = proxy_site["domains"]
init_proxy_conf["site_port"] = [str(i) for i in proxy_site["ports"]]
init_proxy_conf["site_path"] = proxy_site["site_path"]
init_proxy_conf["proxy_log"]["log_conf"] = init_proxy_conf["proxy_log"]["log_conf"].format(
log_path="/www/wwwlogs", site_name=proxy_site["name"]
)
init_proxy_conf["remark"] = ""
init_proxy_conf["http_block"] = ""
init_proxy_conf["proxy_info"] = []
init_proxy_conf["proxy_cache"]["cache_zone"] = proxy_site["name"].replace(".", "_") + "_cache"
if 80 in proxy_site["ports"]:
init_proxy_conf["primary_port"] = "80"
elif 443 in proxy_site["ports"]:
init_proxy_conf["primary_port"] = "443"
else:
init_proxy_conf["primary_port"] = str(proxy_site["ports"][0])
if 443 in proxy_site["ports"]:
init_proxy_conf["https_port"] = "443"
init_proxy_conf["ssl_info"]["ssl_status"] = True
add_time = time.strftime('%Y-%m-%d %X', time.localtime())
pdata = {
'name': proxy_site["name"],
'path': proxy_site["site_path"],
'ps': "nginx配置解析并添加",
'status': 1,
'type_id': 0,
'project_type': 'proxy',
'project_config': json.dumps(init_proxy_conf),
'addtime': add_time
}
site_id = public.M('sites').insert(pdata)
if 443 in proxy_site["ports"]:
proxy_site["ports"].remove(443)
domain_len = max(len(proxy_site["domains"]), len(proxy_site["ports"]))
proxy_site["domains"].extend([proxy_site["domains"][0]] * (domain_len - len(proxy_site["domains"])))
proxy_site["ports"].extend([80] * (domain_len - len(proxy_site["ports"])))
for i in range(domain_len):
public.M('domain').insert({
'name': proxy_site["domains"][i], 'pid': str(site_id),
'port': str(proxy_site["ports"][i]), 'addtime': add_time
})
site_proxy_conf_path = "/www/server/proxy_project/sites/{n}/{n}.json".format(n=proxy_site["name"])
if not os.path.exists(os.path.dirname(site_proxy_conf_path)):
os.makedirs(os.path.dirname(site_proxy_conf_path), mode=0o755)
public.writeFile(site_proxy_conf_path, json.dumps(init_proxy_conf))
proxy_cache_dir = "/www/wwwroot/{}/proxy_cache_dir".format(proxy_site["name"])
if not os.path.isdir(proxy_cache_dir):
os.makedirs(proxy_cache_dir)
config_data = public.readFile(proxy_site["config_file"])
if "proxy_cache_path" not in config_data:
proxy_cache = "proxy_cache_path {proxy_cache_dir} levels=1:2 keys_zone={cache_name}:20m inactive=1d max_size=5g;".format(
proxy_cache_dir=proxy_cache_dir, cache_name=init_proxy_conf["proxy_cache"]["cache_zone"])
config_data = proxy_cache + "\n" + config_data
public.writeFile(site_nginx_config_file, "")
for file in proxy_site["other_files"]:
real_file = file.replace(os.path.join(self.tmp_config_path, "vhost") , _VHOST_PATH)
public.writeFile(real_file, public.readFile(file))
proxy_main = self._get_proxy_main()
res = proxy_main.save_nginx_config(public.to_dict_obj({
"site_name": proxy_site["name"],
"conf_data": config_data,
}))
if res["status"]:
return None
else:
remove_site()
return res["msg"]
except Exception as e:
traceback.print_exc()
remove_site()
return str(e)
def _get_proxy_main(self):
if self._proxy_main is not None:
return self._proxy_main
from mod.project.proxy.comMod import main as proxyMod
self._proxy_main = proxyMod()
return self._proxy_main
def _proxy_init_config(self) -> dict:
proxy_main = self._get_proxy_main()
init_proxy_conf = getattr(proxy_main, "_init_proxy_conf")
return copy.deepcopy(init_proxy_conf)
def create_html_site(self, html_site: dict):
site_id = 0
site_nginx_config_file = "/www/server/panel/vhost/nginx/html_{}.conf".format(html_site["name"])
ngx_open_basedir_path = _VHOST_PATH + '/open_basedir/nginx'
if not os.path.exists(ngx_open_basedir_path):
os.makedirs(ngx_open_basedir_path, 384)
ngx_open_basedir_file = ngx_open_basedir_path + '/{}.conf'.format(html_site["name"])
def remove_site():
if site_id:
public.M("sites").where("id=?", [site_id]).delete()
public.M("domain").where("pid=?", [site_id]).delete()
try:
if os.path.exists(site_nginx_config_file):
os.remove(site_nginx_config_file)
if os.path.exists(ngx_open_basedir_file):
os.remove(ngx_open_basedir_file)
for o_file in html_site["other_files"]:
_real_file = o_file.replace(os.path.join(self.tmp_config_path, "vhost"), _VHOST_PATH)
if os.path.exists(_real_file):
os.remove(_real_file)
except:
traceback.print_exc()
try:
ngx_open_basedir_body = '''set $bt_safe_dir "open_basedir";\nset $bt_safe_open "{}/:/tmp/";'''.format(
html_site["site_path"]
)
public.writeFile(ngx_open_basedir_file, ngx_open_basedir_body)
user_ini_file = html_site["site_path"] + '/.user.ini'
if not os.path.exists(user_ini_file):
public.writeFile(user_ini_file, 'open_basedir=' + html_site["site_path"] + '/:/tmp/')
public.ExecShell('chmod 644 ' + user_ini_file)
public.ExecShell('chown root:root ' + user_ini_file)
public.ExecShell('chattr +i ' + user_ini_file)
add_time = time.strftime('%Y-%m-%d %X', time.localtime())
pdata = {
'name': html_site["name"],
'path': html_site["site_path"],
'ps': "nginx配置解析并添加",
'status': 1,
'type_id': 0,
'project_type': 'html',
'project_config': "{}",
'addtime': add_time
}
site_id = public.M('sites').insert(pdata)
if 443 in html_site["ports"]:
html_site["ports"].remove(443)
domain_len = max(len(html_site["domains"]), len(html_site["ports"]))
html_site["ports"].extend([80] * (domain_len - len(html_site["ports"])))
html_site["domains"].extend([html_site["domains"][0]] * (domain_len - len(html_site["domains"])))
for i in range(domain_len):
public.M('domain').insert({
'name': html_site["domains"][i], 'pid': str(site_id),
'port': str(html_site["ports"][i]), 'addtime': add_time
})
for file in html_site["other_files"]:
real_file = file.replace(os.path.join(self.tmp_config_path, "vhost"), _VHOST_PATH)
public.writeFile(real_file, public.readFile(file))
config_data = public.readFile(html_site["config_file"])
public.writeFile(site_nginx_config_file, "")
ret = self.save_main_file(site_nginx_config_file, config_data)
if ret:
remove_site()
return ret
else:
return None
except Exception as e:
traceback.print_exc()
remove_site()
return str(e)
@staticmethod
def save_main_file(path: str, data: str) -> Optional[str]:
import files, public
args = public.to_dict_obj({})
args.data = data
args.encoding = "utf-8"
args.path = path
f = files.files()
save_result = f.SaveFileBody(args)
if save_result["status"] is False:
return save_result["msg"]
return None
def create_php_site(self, php_site: dict):
site_id = 0
site_nginx_config_file = "/www/server/panel/vhost/nginx/{}.conf".format(php_site["name"])
ngx_open_basedir_path = _VHOST_PATH + '/open_basedir/nginx'
if not os.path.exists(ngx_open_basedir_path):
os.makedirs(ngx_open_basedir_path, 0o755)
ngx_open_basedir_file = ngx_open_basedir_path + '/{}.conf'.format(php_site["name"])
def remove_site():
if site_id:
public.M("sites").where("id=?", [site_id]).delete()
public.M("domain").where("pid=?", [site_id]).delete()
try:
if os.path.exists(site_nginx_config_file):
os.remove(site_nginx_config_file)
if os.path.exists(ngx_open_basedir_file):
os.remove(ngx_open_basedir_file)
for o_file in php_site["other_files"]:
_real_file = o_file.replace(os.path.join(self.tmp_config_path, "vhost"), _VHOST_PATH)
if os.path.exists(_real_file):
os.remove(_real_file)
except:
traceback.print_exc()
try:
ngx_open_basedir_body = '''set $bt_safe_dir "open_basedir";\nset $bt_safe_open "{}/:/tmp/";'''.format(
php_site["site_path"]
)
public.writeFile(ngx_open_basedir_file, ngx_open_basedir_body)
user_ini_file = php_site["site_path"] + '/.user.ini'
if not os.path.exists(user_ini_file):
public.writeFile(user_ini_file, 'open_basedir=' + php_site["site_path"] + '/:/tmp/')
public.ExecShell('chmod 644 ' + user_ini_file)
public.ExecShell('chown root:root ' + user_ini_file)
public.ExecShell('chattr +i ' + user_ini_file)
add_time = time.strftime('%Y-%m-%d %X', time.localtime())
pdata = {
'name': php_site["name"],
'path': php_site["site_path"],
'ps': "nginx配置解析并添加",
'status': 1,
'type_id': 0,
'project_type': 'PHP',
'project_config': "{}",
'addtime': add_time
}
site_id = public.M('sites').insert(pdata)
if 443 in php_site["ports"]:
php_site["ports"].remove(443)
domain_len = max(len(php_site["domains"]), len(php_site["ports"]))
php_site["ports"].extend([80] * (domain_len - len(php_site["ports"])))
php_site["domains"].extend([php_site["domains"][0]] * (domain_len - len(php_site["domains"])))
for i in range(domain_len):
public.M('domain').insert({
'name': php_site["domains"][i], 'pid': str(site_id),
'port': str(php_site["ports"][i]), 'addtime': add_time
})
for file in php_site["other_files"]:
real_file = file.replace(os.path.join(self.tmp_config_path, "vhost"), _VHOST_PATH)
if not os.path.isdir(os.path.dirname(real_file)):
os.makedirs(os.path.dirname(real_file), 0o755)
public.writeFile(real_file, public.readFile(file))
config_data = public.readFile(php_site["config_file"])
public.writeFile(site_nginx_config_file, "")
ret = self.save_main_file(site_nginx_config_file, config_data)
if ret:
remove_site()
return ret
else:
return None
except Exception as e:
traceback.print_exc()
remove_site()
return str(e) |