/
nodejsModel.py
1820 lines (1606 loc) · 75.7 KB
/
nodejsModel.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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#coding: utf-8
#-------------------------------------------------------------------
# 宝塔Linux面板
#-------------------------------------------------------------------
# Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
#-------------------------------------------------------------------
# Author: hwliang <hwl@bt.cn>
#-------------------------------------------------------------------
#------------------------------
# node.js模型
#------------------------------
import os,sys,re,json,shutil,psutil,time
from projectModel.base import projectBase
import public
try:
from BTPanel import cache
except:
pass
class main(projectBase):
_panel_path = public.get_panel_path()
_nodejs_plugin_path = public.get_plugin_path('nodejs')
_nodejs_path = '{}/nodejs'.format(public.get_setup_path())
_log_name = 'Project management'
_npm_exec_log = '{}/logs/npm-exec.log'.format(_panel_path)
_node_pid_path = '{}/vhost/pids'.format(_nodejs_path)
_node_logs_path = '{}/vhost/logs'.format(_nodejs_path)
_node_run_scripts = '{}/vhost/scripts'.format(_nodejs_path)
_pids = None
_vhost_path = '{}/vhost'.format(_panel_path)
_www_home = '/home/www'
def __init__(self):
if not os.path.exists(self._node_run_scripts):
os.makedirs(self._node_run_scripts,493)
if not os.path.exists(self._node_pid_path):
os.makedirs(self._node_pid_path,493)
if not os.path.exists(self._node_logs_path):
os.makedirs(self._node_logs_path,493)
if not os.path.exists(self._www_home):
os.makedirs(self._www_home,493)
public.set_own(self._www_home,'www')
def get_exec_logs(self,get):
'''
@name 获取执行日志
@author hwliang<2021-08-09>
@param get<dict_obj>
@return string
'''
if not os.path.exists(self._npm_exec_log): return public.returnMsg(False,'NODE_NOT_EXISTS')
return public.GetNumLines(self._npm_exec_log,20)
def get_project_list(self,get):
'''
@name 获取项目列表
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
}
@return dict
'''
if not 'p' in get: get.p = 1
if not 'limit' in get: get.limit = 20
if not 'callback' in get: get.callback = ''
if not 'order' in get: get.order = 'id desc'
if 'search' in get:
get.project_name = get.search.strip()
search = "%{}%".format(get.project_name)
count = public.M('sites').where('project_type=? AND (name LIKE ? OR ps LIKE ?)',('Node',search,search)).count()
data = public.get_page(count,int(get.p),int(get.limit),get.callback)
data['data'] = public.M('sites').where('project_type=? AND (name LIKE ? OR ps LIKE ?)',('Node',search,search)).limit(data['shift'] + ',' + data['row']).order(get.order).select()
else:
count = public.M('sites').where('project_type=?','Node').count()
data = public.get_page(count,int(get.p),int(get.limit),get.callback)
data['data'] = public.M('sites').where('project_type=?','Node').limit(data['shift'] + ',' + data['row']).order(get.order).select()
for i in range(len(data['data'])):
data['data'][i] = self.get_project_stat(data['data'][i])
return data
def get_ssl_end_date(self,project_name):
'''
@name 获取SSL信息
@author hwliang<2021-08-09>
@param project_name <string> 项目名称
@return dict
'''
import data
return data.data().get_site_ssl_info('node_{}'.format(project_name))
def is_install_nodejs(self,get):
'''
@name 是否安装nodejs版本管理器
@author hwliang<2021-08-09>
@param get<dict_obj> 请求数据
@return bool
'''
return os.path.exists(self._nodejs_plugin_path)
def get_nodejs_version(self,get):
'''
@name 获取已安装的nodejs版本
@author hwliang<2021-08-09>
@param get<dict_obj> 请求数据
@return list
'''
nodejs_list = []
if not os.path.exists(self._nodejs_path): return nodejs_list
for v in os.listdir(self._nodejs_path):
if v[0] != 'v' or v.find('.') == -1: continue
node_path = os.path.join(self._nodejs_path,v)
node_bin = '{}/bin/node'.format(node_path)
if not os.path.exists(node_bin):
if os.path.exists(node_path + '/bin'):
public.ExecShell('rm -rf {}'.format(node_path))
continue
nodejs_list.append(v)
return nodejs_list
def get_run_list(self,get):
'''
@name 获取node项目启动列表
@author hwliang<2021-08-10>
@param get<dict_obj>{
project_cwd: string<项目目录>
}
'''
project_cwd = get.project_cwd.strip()
if not os.path.exists(project_cwd): return public.return_error('The project directory does not exist!')
package_file = '{}/package.json'.format(project_cwd)
if not os.path.exists(package_file): return {} #public.return_error('没有在项目目录中找到package.json配置文件!')
package_info = json.loads(public.readFile(package_file))
if not 'scripts' in package_info: return {}# public.return_error('没有在项目配置文件package.json中找到scripts配置项!')
if not package_info['scripts']: return {}# public.return_error('没有找到可用的启动选项!')
return package_info['scripts']
def get_npm_bin(self,nodejs_version):
'''
@name 获取指定node版本的npm路径
@author hwliang<2021-08-10>
@param nodejs_version<string> nodejs版本
@return string
'''
npm_path = '{}/{}/bin/npm'.format(self._nodejs_path,nodejs_version)
if not os.path.exists(npm_path): return False
return npm_path
def get_yarn_bin(self,nodejs_version):
'''
@name 获取指定node版本的yarn路径
@author hwliang<2021-08-28>
@param nodejs_version<string> nodejs版本
@return string
'''
yarn_path = '{}/{}/bin/yarn'.format(self._nodejs_path,nodejs_version)
if not os.path.exists(yarn_path): return False
return yarn_path
def get_node_bin(self,nodejs_version):
'''
@name 获取指定node版本的node路径
@author hwliang<2021-08-10>
@param nodejs_version<string> nodejs版本
@return string
'''
node_path = '{}/{}/bin/node'.format(self._nodejs_path,nodejs_version)
if not os.path.exists(node_path): return False
return node_path
def get_last_env(self,nodejs_version,project_cwd = None):
'''
@name 获取前置环境变量
@author hwliang<2021-08-25>
@param nodejs_version<string> Node版本
@return string
'''
nodejs_bin_path = '{}/{}/bin'.format(self._nodejs_path,nodejs_version)
if project_cwd:
_bin = '{}/node_modules/.bin'.format(project_cwd)
if os.path.exists(_bin):
nodejs_bin_path = _bin + ':' + nodejs_bin_path
last_env = '''PATH={nodejs_bin_path}:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
'''.format(nodejs_bin_path = nodejs_bin_path)
return last_env
def install_packages(self,get):
'''
@name 安装指定项目的依赖包
@author hwliang<2021-08-10>
@param get<dict_obj>{
project_name: string<项目名称>
}
return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find: return public.return_error('The specified item does not exist!')
if not os.path.exists(project_find['path']): return public.return_error('The project directory does not exist!')
package_file = '{}/package.json'.format(project_find['path'])
if not os.path.exists(package_file): return public.return_error('The package.json configuration file was not found in the project directory!')
nodejs_version = project_find['project_config']['nodejs_version']
package_lock_file = '{}/package-lock.json'.format(project_find['path'])
node_modules_path = '{}/node_modules'.format(project_find['path'])
# 已经安装过的依赖包的情况下,可能存在不同node版本导致的问题,可能需要重新构建依赖包
rebuild = False
if os.path.exists(package_lock_file) and os.path.exists(node_modules_path):
rebuild = True
npm_bin = self.get_npm_bin(nodejs_version)
yarn_bin = self.get_yarn_bin(nodejs_version)
if not npm_bin and not yarn_bin:
return public.return_error('The specified nodejs version does not exist!')
public.writeFile(self._npm_exec_log,"Installing dependencies...\n")
public.writeFile(self._npm_exec_log,"Downloading dependency package, please wait...\n")
if yarn_bin:
if os.path.exists(package_lock_file):
os.remove(package_lock_file)
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} install 2>&1 >> {}".format(project_find['path'],yarn_bin,self._npm_exec_log))
else:
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} install 2>&1 >> {}".format(project_find['path'],npm_bin,self._npm_exec_log))
public.writeFile(self._npm_exec_log,"|-Successify --- Command executed! ---",'a+')
public.WriteLog(self._log_name, 'Node project: {}, the installation of the dependency package is complete!'.format(project_find['name']))
if rebuild: # 重新构建已安装模块?
self.rebuild_project(get.project_name)
return public.return_data(True,'The dependency package is installed successfully!')
def update_packages(self,get):
'''
@name 更新指定项目的依赖包
@author hwliang<2021-08-10>
@param get<dict_obj>{
project_name: string<项目名称>
}
return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find: return public.return_error('The specified item does not exist!')
if not os.path.exists(project_find['path']): return public.return_error('The project directory does not exist!')
package_file = '{}/package.json'.format(project_find['path'])
if not os.path.exists(package_file): return public.return_error('The package.json configuration file was not found in the project directory!')
package_lock_file = '{}/package-lock.json'.format(project_find['path'])
if not os.path.exists(package_lock_file): return public.return_error('Please install the dependency package first!')
nodejs_version = project_find['project_config']['nodejs_version']
npm_bin = self.get_npm_bin(nodejs_version)
if not npm_bin:
return public.return_error('The specified nodejs version does not exist!')
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} update &> {}".format(project_find['path'],npm_bin,self._npm_exec_log))
public.WriteLog(self._log_name, 'Project [{}] update all dependent packages'.format(get.project_name))
return public.return_data(True,'Dependent package updated successfully!')
def reinstall_packages(self,get):
'''
@name 重新安装指定项目的依赖包
@author hwliang<2021-08-10>
@param get<dict_obj>{
project_name: string<项目名称>
}
return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find: return public.return_error('The specified item does not exist!')
if not os.path.exists(project_find['path']): return public.return_error('The project directory does not exist!')
package_file = '{}/package.json'.format(project_find['path'])
if not os.path.exists(package_file): return public.return_error('The package.json configuration file was not found in the project directory!')
package_lock_file = '{}/package-lock.json'.format(project_find['path'])
if os.path.exists(package_lock_file): os.remove(package_lock_file)
package_path = '{}/node_modules'
if os.path.exists(package_path): shutil.rmtree(package_path)
nodejs_version = project_find['project_config']['nodejs_version']
npm_bin = self.get_npm_bin(nodejs_version)
if not npm_bin:
return public.return_error('The specified nodejs version does not exist!')
public.WriteLog(self._log_name,'Node project: {}, all dependent packages have been reinstalled')
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} install &> {}".format(project_find['path'],npm_bin,self._npm_exec_log))
return public.return_data(True,'Dependent package reinstalled successfully!')
def get_project_modules(self,get):
'''
@name 获取指定项目的依赖包列表
@author hwliang<2021-08-10>
@param get<dict_obj>{
project_name: string<项目名称>
project_cwd: string<项目目录> 可选
}
return list
'''
if not 'project_cwd' in get:
project_find = self.get_project_find(get.project_name)
if not project_find: return public.return_error('The specified item does not exist!')
project_cwd = project_find['path']
else:
project_cwd = get.project_cwd
mod_path = os.path.join(project_cwd,'node_modules')
modules = []
if not os.path.exists(mod_path): return modules
for mod_name in os.listdir(mod_path):
try:
mod_pack_file = os.path.join(mod_path,mod_name,'package.json')
if not os.path.exists(mod_pack_file): continue
mod_pack_info = json.loads(public.readFile(mod_pack_file))
pack_info = {
"name": mod_name,
"version": mod_pack_info['version'],
"description":mod_pack_info['description'],
"license": mod_pack_info['license'] if 'license' in mod_pack_info else 'NULL',
"homepage": mod_pack_info['homepage']
}
modules.append(pack_info)
except:
continue
return modules
def install_module(self,get):
'''
@name 安装指定模块
@author hwliang<2021-08-10>
@param get<dict_obj>{
project_name: string<项目名称>
mod_name: string<模块名称>
}
@return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find: return public.return_error('The specified item does not exist!')
project_cwd = project_find['path']
mod_name = get.mod_name
filename = '{}/node_modules/{}/package.json'.format(project_cwd,mod_name)
if os.path.exists(filename): return public.return_error('The specified module has been installed!')
nodejs_version = project_find['project_config']['nodejs_version']
npm_bin = self.get_npm_bin(nodejs_version)
yarn_bin = self.get_yarn_bin(nodejs_version)
if not npm_bin and not yarn_bin:
return public.return_error('The specified nodejs version does not exist!')
if yarn_bin:
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} add {} &> {}".format(project_find['path'],yarn_bin,mod_name,self._npm_exec_log))
else:
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} install {} &> {}".format(project_find['path'],npm_bin,mod_name,self._npm_exec_log))
if not os.path.exists(filename): return public.return_error('Failed to install the specified module!')
public.WriteLog(self._log_name,'Node project {}, {} module installation is complete!'.format(get.project_name,mod_name))
return public.return_data(True,'Successful installation!')
def uninstall_module(self,get):
'''
@name 卸载指定模块
@author hwliang<2021-04-08>
@param get<dict_obj>{
project_name: string<项目名称>
mod_name: string<模块名称>
}
@return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find: return public.return_error('The specified item does not exist!')
project_cwd = project_find['path']
mod_name = get.mod_name
filename = '{}/node_modules/{}/package.json'.format(project_cwd,mod_name)
if not os.path.exists(filename): return public.return_error('The specified module is not installed!')
nodejs_version = project_find['project_config']['nodejs_version']
npm_bin = self.get_npm_bin(nodejs_version)
yarn_bin = self.get_yarn_bin(nodejs_version)
if not npm_bin and not yarn_bin:
return public.return_error('The specified nodejs version does not exist!')
if yarn_bin:
result = public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} remove {}".format(project_find['path'],yarn_bin,mod_name))
else:
result = public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} uninstall {}".format(project_find['path'],npm_bin,mod_name))
if os.path.exists(filename):
result = "\n".join(result)
if result.find('looking for funding') != -1:
return public.return_error("This module is dependent on other installed modules and cannot be uninstalled!")
return public.return_error("Unable to uninstall this module!")
public.WriteLog(self._log_name,'Node project {}, {} module uninstallation completed!'.format(get.project_name,mod_name))
return public.return_data(True,'Module unloaded successfully!')
def upgrade_module(self,get):
'''
@name 更新指定模块
@author hwliang<2021-08-10>
@param get<dict_obj>{
project_name: string<项目名称>
mod_name: string<模块名称>
}
@return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find: return public.return_error('The specified item does not exist!')
project_cwd = project_find['path']
mod_name = get.mod_name
filename = '{}/node_modules/{}/package.json'.format(project_cwd,mod_name)
if not os.path.exists(filename): return public.return_error('The specified module is not installed!')
nodejs_version = project_find['project_config']['nodejs_version']
npm_bin = self.get_npm_bin(nodejs_version)
if not npm_bin:
return public.return_error('The specified nodejs version does not exist!')
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} update {} &> {}".format(project_find['path'],npm_bin,mod_name,self._npm_exec_log))
public.WriteLog(self._log_name,'Node project {}, {} module update completed!'.format(get.project_name,mod_name))
return public.return_data(True,'Module updated successfully!')
def create_project(self,get):
'''
@name 创建新的项目
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
project_cwd: string<项目目录>
project_script: string<项目脚本>
project_ps: string<项目备注信息>
bind_extranet: int<是否绑定外网> 1:是 0:否
domains: list<域名列表> ["domain1:80","domain2:80"] // 在bind_extranet=1时,需要填写
is_power_on: int<是否开机启动> 1:是 0:否
run_user: string<运行用户>
max_memory_limit: int<最大内存限制> // 超出此值项目将被强制重启
nodejs_version: string<nodejs版本>
}
@return dict
'''
if not isinstance(get,public.dict_obj): return public.return_error('The parameter type is wrong, need dict obj object')
if not self.is_install_nodejs(get):
return public.return_error('Please install nodejs version manager first')
project_name = get.project_name.strip()
if not re.match("^\w+$",project_name):
return public.return_error('The project name format is incorrect and supports letters, numbers, underscores, and expressions: ^[0-9A-Za-z_]$')
if public.M('sites').where('name=?',(get.project_name,)).count():
return public.return_error('The specified project name already exists: {}'.format(get.project_name))
get.project_cwd = get.project_cwd.strip()
if not os.path.exists(get.project_cwd):
return public.return_error('The project directory does not exist: {}'.format(get.project_cwd))
# 端口占用检测
if self.check_port_is_used(get.get('port/port')):
return public.return_error('This port is already occupied, please modify your project port, port: {}'.format(get.port))
domains = []
if get.bind_extranet == 1:
domains = get.domains
if not public.is_apache_nginx(): return public.return_error('Please install Nginx or Apache first')
for domain in domains:
domain_arr = domain.split(':')
if public.M('domain').where('name=?',domain_arr[0]).count():
return public.return_error('Domain name already exists: {}'.format(domain))
pdata = {
'name': get.project_name,
'path': get.project_cwd,
'ps': get.project_ps,
'status':1,
'type_id':0,
'project_type': 'Node',
'project_config': json.dumps(
{
'project_name': get.project_name,
'project_cwd': get.project_cwd,
'project_script': get.project_script,
'bind_extranet': get.bind_extranet,
'domains': [],
'is_power_on': get.is_power_on,
'run_user': get.run_user,
'max_memory_limit': get.max_memory_limit,
'nodejs_version': get.nodejs_version,
'port': int(get.port)
}
),
'addtime': public.getDate()
}
project_id = public.M('sites').insert(pdata)
if get.bind_extranet == 1:
format_domains = []
for domain in domains:
if domain.find(':') == -1: domain += ':80'
format_domains.append(domain)
get.domains = format_domains
self.project_add_domain(get)
self.set_config(get.project_name)
public.WriteLog(self._log_name,'Add Node.js project {}'.format(get.project_name))
self.install_packages(get)
self.start_project(get)
return public.return_data(True,'Added project successfully',project_id)
def modify_project(self,get):
'''
@name 修改指定项目
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
project_cwd: string<项目目录>
project_script: string<项目脚本>
project_ps: string<项目备注信息>
is_power_on: int<是否开机启动> 1:是 0:否
run_user: string<运行用户>
max_memory_limit: int<最大内存限制> // 超出此值项目将被强制重启
nodejs_version: string<nodejs版本>
}
@return dict
'''
if not isinstance(get,public.dict_obj): return public.return_error('The parameter type is wrong, need dict obj')
if not self.is_install_nodejs(get):
return public.return_error('Please install nodejs version manager before installing at least one nodejs')
project_find = self.get_project_find(get.project_name)
if not project_find:
return public.return_error('Item does not exist: {}'.format(get.project_name))
if not os.path.exists(get.project_cwd):
return public.return_error('The project directory does not exist: {}'.format(get.project_cwd))
rebuild = False
if hasattr(get,'port'):
if int(project_find['project_config']['port']) != int(get.port):
if self.check_port_is_used(get.get('port/port'),True):
return public.return_error('The port is already occupied, please modify your port, port: {}'.format(get.port))
project_find['project_config']['port'] = int(get.port)
if hasattr(get,'project_cwd'): project_find['project_config']['project_cwd'] = get.project_cwd
if hasattr(get,'project_script'):
if not get.project_script.strip():
return public.return_error('Start command cannot be empty')
project_find['project_config']['project_script'] = get.project_script.strip()
if hasattr(get,'is_power_on'): project_find['project_config']['is_power_on'] = get.is_power_on
if hasattr(get,'run_user'): project_find['project_config']['run_user'] = get.run_user
if hasattr(get,'max_memory_limit'): project_find['project_config']['max_memory_limit'] = get.max_memory_limit
if hasattr(get,'nodejs_version'):
if project_find['project_config']['nodejs_version'] != get.nodejs_version:
rebuild = True
project_find['project_config']['nodejs_version'] = get.nodejs_version
pdata = {
'path': get.project_cwd,
'ps': get.project_ps,
'project_config': json.dumps(project_find['project_config'])
}
public.M('sites').where('name=?',(get.project_name,)).update(pdata)
self.set_config(get.project_name)
public.WriteLog(self._log_name,'Modify Node.js project {}'.format(get.project_name))
if rebuild:
self.rebuild_project(get.project_name)
return public.return_data(True,'Modify the project successfully')
def rebuild_project(self,project_name):
'''
@name 重新构建指定项目
@author hwliang<2021-08-26>
@param project_name: string<项目名称>
@return bool
'''
project_find = self.get_project_find(project_name)
if not project_find: return False
nodejs_version = project_find['project_config']['nodejs_version']
npm_bin = self.get_npm_bin(nodejs_version)
public.ExecShell(self.get_last_env(nodejs_version) + "cd {} && {} rebuild 2>&1 >> {}".format(project_find['path'],npm_bin,self._npm_exec_log))
return True
def remove_project(self,get):
'''
@name 删除指定项目
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
}
@return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find:
return public.return_error('The specified item does not exist: {}'.format(get.project_name))
self.stop_project(get)
self.clear_config(get.project_name)
public.M('domain').where('pid=?',(project_find['id'],)).delete()
public.M('sites').where('name=?',(get.project_name,)).delete()
pid_file = "{}/{}.pid".format(self._node_pid_path,get.project_name)
if os.path.exists(pid_file): os.remove(pid_file)
script_file = '{}/{}.sh'.format(self._node_run_scripts,get.project_name)
if os.path.exists(script_file): os.remove(script_file)
log_file = '{}/{}.log'.format(self._node_logs_path,get.project_name)
if os.path.exists(log_file): os.remove(log_file)
public.WriteLog(self._log_name,'Delete Node.js project {}'.format(get.project_name))
return public.return_data(True,'Successfully deleted item')
def project_get_domain(self,get):
'''
@name 获取指定项目的域名列表
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
}
@return dict
'''
project_id = public.M('sites').where('name=?',(get.project_name,)).getField('id')
domains = public.M('domain').where('pid=?',(project_id,)).order('id desc').select()
project_find = self.get_project_find(get.project_name)
if len(domains) != len(project_find['project_config']['domains']):
public.M('domain').where('pid=?',(project_id,)).delete()
if not project_find: return []
for d in project_find['project_config']['domains']:
domain = {}
arr = d.split(':')
if len(arr) < 2: arr.append(80)
domain['name'] = arr[0]
domain['port'] = int(arr[1])
domain['pid'] = project_id
domain['addtime'] = public.getDate()
public.M('domain').insert(domain)
if project_find['project_config']['domains']:
domains = public.M('domain').where('pid=?',(project_id,)).select()
return domains
def project_add_domain(self,get):
'''
@name 为指定项目添加域名
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
domains: list<域名列表>
}
@return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find:
return public.return_error('The specified item does not exist',data='')
project_id = project_find['id']
domains = get.domains
success_list = []
error_list = []
for domain in domains:
domain = domain.strip()
if not domain: return public.return_error('Domain name cannot be empty',data='')
domain_arr = domain.split(':')
if len(domain_arr) == 1:
domain_arr.append(80)
domain += ':80'
if not public.M('domain').where('name=?',(domain_arr[0],)).count():
public.M('domain').add('name,pid,port,addtime',(domain_arr[0],project_id,domain_arr[1],public.getDate()))
if not domain in project_find['project_config']['domains']:
project_find['project_config']['domains'].append(domain)
public.WriteLog(self._log_name,'Successfully added the domain [{}] to the project [{}]'.format(domain,get.project_name))
success_list.append(domain)
else:
public.WriteLog(self._log_name,'Domain [{}] already exists'.format(domain))
error_list.append(domain)
if success_list:
public.M('sites').where('id=?',(project_id,)).save('project_config',json.dumps(project_find['project_config']))
self.set_config(get.project_name)
return public.return_data(True,"[{}] domain names added successfully, [{}] failed!".format(len(success_list),len(error_list)),error_msg=error_list)
return public.return_data(False,"[{}] domain names added successfully, [{}] failed!".format(len(success_list),len(error_list)),error_msg=error_list)
def project_remove_domain(self,get):
'''
@name 为指定项目删除域名
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
domain: string<域名>
}
@return dict
'''
project_find = self.get_project_find(get.project_name)
if not project_find:
return public.return_error('The specified item does not exist')
last_domain = get.domain
domain_arr = get.domain.split(':')
if len(domain_arr) == 1:
domain_arr.append(80)
project_id = public.M('sites').where('name=?',(get.project_name,)).getField('id')
if project_find['project_config']['bind_extranet']:
if len(project_find['project_config']['domains']) == 1: return public.return_error('At least one domain name is required for the mapped project')
domain_id = public.M('domain').where('name=? AND pid=?',(domain_arr[0],project_id)).getField('id')
if not domain_id:
return public.return_error('The specified domain name does not exist')
public.M('domain').where('id=?',(domain_id,)).delete()
if get.domain in project_find['project_config']['domains']:
project_find['project_config']['domains'].remove(get.domain)
if get.domain+":80" in project_find['project_config']['domains']:
project_find['project_config']['domains'].remove(get.domain + ":80")
public.M('sites').where('id=?',(project_id,)).save('project_config',json.dumps(project_find['project_config']))
public.WriteLog(self._log_name,'From project: [{}], delete domain name [{}]'.format(get.project_name,get.domain))
self.set_config(get.project_name)
return public.return_data(True,'Domain name deleted successfully')
def bind_extranet(self,get):
'''
@name 绑定外网
@author hwliang<2021-08-09>
@param get<dict_obj>{
project_name: string<项目名称>
}
@return dict
'''
if not public.is_apache_nginx(): return public.return_error('Please install Nginx or Apache first')
project_name = get.project_name.strip()
project_find = self.get_project_find(project_name)
if not project_find: return public.return_error('Item does not exist')
if not project_find['project_config']['domains']: return public.return_error('Please add at least one domain name in the [Domain Management] option')
project_find['project_config']['bind_extranet'] = 1
public.M('sites').where("id=?",(project_find['id'],)).setField('project_config',json.dumps(project_find['project_config']))
self.set_config(project_name)
public.WriteLog(self._log_name,'Node project{}, enable mapping'.format(project_name))
return public.return_data(True,'Enable the mapping successfully')
def set_config(self,project_name):
'''
@name 设置项目配置
@author hwliang<2021-08-09>
@param project_name: string<项目名称>
@return bool
'''
project_find = self.get_project_find(project_name)
if not project_find: return False
if not project_find['project_config']: return False
if not project_find['project_config']['bind_extranet']: return False
if not project_find['project_config']['domains']: return False
self.set_nginx_config(project_find)
self.set_apache_config(project_find)
public.serviceReload()
return True
def clear_config(self,project_name):
'''
@name 清除项目配置
@author hwliang<2021-08-09>
@param project_name: string<项目名称>
@return bool
'''
project_find = self.get_project_find(project_name)
if not project_find: return False
self.clear_nginx_config(project_find)
self.clear_apache_config(project_find)
public.serviceReload()
return True
def clear_apache_config(self,project_find):
'''
@name 清除apache配置
@author hwliang<2021-08-09>
@param project_find: dict<项目信息>
@return bool
'''
project_name = project_find['name']
config_file = "{}/apache/node_{}.conf".format(self._vhost_path,project_name)
if os.path.exists(config_file):
os.remove(config_file)
return True
def clear_nginx_config(self,project_find):
'''
@name 清除nginx配置
@author hwliang<2021-08-09>
@param project_find: dict<项目信息>
@return bool
'''
project_name = project_find['name']
config_file = "{}/nginx/node_{}.conf".format(self._vhost_path,project_name)
if os.path.exists(config_file):
os.remove(config_file)
rewrite_file = "{panel_path}/vhost/rewrite/node_{project_name}.conf".format(panel_path = self._panel_path,project_name = project_name)
if os.path.exists(rewrite_file):
os.remove(rewrite_file)
return True
def set_nginx_config(self,project_find):
'''
@name 设置Nginx配置
@author hwliang<2021-08-09>
@param project_find: dict<项目信息>
@return bool
'''
project_name = project_find['name']
ports = []
domains = []
for d in project_find['project_config']['domains']:
domain_tmp = d.split(':')
if len(domain_tmp) == 1: domain_tmp.append(80)
if not int(domain_tmp[1]) in ports:
ports.append(int(domain_tmp[1]))
if not domain_tmp[0] in domains:
domains.append(domain_tmp[0])
listen_ipv6 = public.listen_ipv6()
listen_ports = ''
for p in ports:
listen_ports += " listen {};\n".format(p)
if listen_ipv6:
listen_ports += " listen [::]:{};\n".format(p)
listen_ports = listen_ports.strip()
is_ssl,is_force_ssl = self.exists_nginx_ssl(project_name)
ssl_config = ''
if is_ssl:
listen_ports += "\n listen 443 ssl http2;"
if listen_ipv6: listen_ports += "\n listen [::]:443 ssl http2;"
ssl_config = '''ssl_certificate {vhost_path}/cert/{priject_name}/fullchain.pem;
ssl_certificate_key {vhost_path}/cert/{priject_name}/privkey.pem;
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
add_header Strict-Transport-Security "max-age=31536000";
error_page 497 https://$host$request_uri;'''.format(vhost_path = self._vhost_path,priject_name = project_name)
if is_force_ssl:
ssl_config += '''
#HTTP_TO_HTTPS_START
if ($server_port !~ 443){
rewrite ^(/.*)$ https://$host$1 permanent;
}
#HTTP_TO_HTTPS_END'''
config_file = "{}/nginx/node_{}.conf".format(self._vhost_path,project_name)
template_file = "{}/template/nginx/node_http.conf".format(self._vhost_path)
config_body = public.readFile(template_file)
config_body = config_body.format(
site_path = project_find['path'],
domains = ' '.join(domains),
project_name = project_name,
panel_path = self._panel_path,
log_path = public.get_logs_path(),
url = 'http://127.0.0.1:{}'.format(project_find['project_config']['port']),
host = '$host',
listen_ports = listen_ports,
ssl_config = ssl_config
)
# # 恢复旧的SSL配置
# ssl_config = self.get_nginx_ssl_config(project_name)
# if ssl_config:
# config_body.replace('#error_page 404/404.html;',ssl_config)
rewrite_file = "{panel_path}/vhost/rewrite/node_{project_name}.conf".format(panel_path = self._panel_path,project_name = project_name)
if not os.path.exists(rewrite_file): public.writeFile(rewrite_file,'# Please fill in the URLrewrite or custom NGINX config here\n')
public.writeFile(config_file,config_body)
return True
def get_nginx_ssl_config(self,project_name):
'''
@name 获取项目Nginx SSL配置
@author hwliang<2021-08-09>
@param project_name: string<项目名称>
@return string
'''
result = ''
config_file = "{}/nginx/node_{}".format(self._vhost_path,project_name)
if not os.path.exists(config_file):
return result
config_body = public.readFile(config_file)
if not config_body:
return result
if config_body.find('ssl_certificate') == -1:
return result
ssl_body = re.search("#SSL-START(.|\n)+#SSL-END",config_body)
if not ssl_body: return result
result = ssl_body.group()
return result
def exists_nginx_ssl(self,project_name):
'''
@name 判断项目是否配置Nginx SSL配置
@author hwliang<2021-08-09>
@param project_name: string<项目名称>
@return tuple
'''
config_file = "{}/nginx/node_{}.conf".format(public.get_vhost_path(),project_name)
if not os.path.exists(config_file):
return False,False
config_body = public.readFile(config_file)
if not config_body:
return False,False
is_ssl,is_force_ssl = False,False
if config_body.find('ssl_certificate') != -1:
is_ssl = True
if config_body.find('HTTP_TO_HTTPS_START') != -1:
is_force_ssl = True
return is_ssl,is_force_ssl
def exists_apache_ssl(self,project_name):
'''
@name 判断项目是否配置Apache SSL配置
@author hwliang<2021-08-09>
@param project_name: string<项目名称>
@return bool
'''
config_file = "{}/apache/node_{}.conf".format(public.get_vhost_path(),project_name)
if not os.path.exists(config_file):
return False,False
config_body = public.readFile(config_file)
if not config_body:
return False,False
is_ssl,is_force_ssl = False,False
if config_body.find('SSLCertificateFile') != -1:
is_ssl = True
if config_body.find('HTTP_TO_HTTPS_START') != -1:
is_force_ssl = True
return is_ssl,is_force_ssl
def set_apache_config(self,project_find):
'''
@name 设置Apache配置
@author hwliang<2021-08-09>
@param project_find: dict<项目信息>
@return bool
'''
project_name = project_find['name']
# 处理域名和端口
ports = []
domains = []
for d in project_find['project_config']['domains']:
domain_tmp = d.split(':')
if len(domain_tmp) == 1: domain_tmp.append(80)
if not int(domain_tmp[1]) in ports:
ports.append(int(domain_tmp[1]))
if not domain_tmp[0] in domains:
domains.append(domain_tmp[0])
config_file = "{}/apache/node_{}.conf".format(self._vhost_path,project_name)
template_file = "{}/template/apache/node_http.conf".format(self._vhost_path)
config_body = public.readFile(template_file)
apache_config_body = ''
# 旧的配置文件是否配置SSL
is_ssl,is_force_ssl = self.exists_apache_ssl(project_name)
if is_ssl:
if not 443 in ports: ports.append(443)
from panelSite import panelSite
s = panelSite()
# 根据端口列表生成配置
for p in ports:
# 生成SSL配置
ssl_config = ''
if p == 443 and is_ssl:
ssl_key_file = "{vhost_path}/cert/{project_name}/privkey.pem".format(project_name = project_name,vhost_path = public.get_vhost_path())