File size: 32,559 Bytes
f50d35d
1d87183
 
ba84e2e
1d87183
 
 
 
 
 
 
 
 
677e436
1d87183
 
677e436
 
1d87183
 
 
ba84e2e
1d87183
677e436
1d87183
 
ba84e2e
e865ef4
1d87183
 
 
 
 
677e436
1d87183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd5128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d87183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c56e7de
1d87183
 
 
 
 
 
 
 
 
284ce91
1d87183
 
2329fdd
1d87183
 
 
 
 
 
 
 
 
c56e7de
91a463b
1d87183
 
 
e014909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d87183
 
 
 
 
 
 
 
 
 
91a463b
0b67b58
1d87183
 
 
 
91a463b
f6d3e7b
e014909
 
 
 
 
3190745
 
0b61216
3190745
e014909
 
3190745
 
1d87183
91a463b
 
1d87183
91a463b
1d87183
 
91a463b
 
 
 
 
 
 
 
 
 
1d87183
 
91a463b
 
1d87183
91a463b
 
1d87183
 
 
c9be20a
 
 
 
6cfe052
 
 
 
 
 
 
 
c9be20a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d87183
c9be20a
 
dcae0c8
f5ea8ab
c9be20a
6cfe052
 
 
 
 
 
 
 
 
c9be20a
 
 
dcae0c8
 
c9be20a
 
dcae0c8
 
 
 
 
c9be20a
dcae0c8
 
 
 
 
 
c9be20a
 
 
 
dcae0c8
c9be20a
 
 
 
 
 
 
dcae0c8
 
 
c9be20a
 
 
 
 
 
 
 
 
 
dcae0c8
 
 
1d87183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91a463b
1d87183
 
 
 
91a463b
1d87183
91a463b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d87183
 
 
 
39bf7c6
1d87183
c9be20a
 
 
dcae0c8
 
 
 
 
 
c9be20a
f5ea8ab
 
 
df08812
 
 
 
 
 
 
 
 
dcae0c8
df08812
 
 
 
 
 
 
 
f5ea8ab
c9be20a
42d8a15
1d87183
 
 
c9be20a
1d87183
 
f5ea8ab
 
 
df08812
 
 
 
f5ea8ab
 
df08812
 
f5ea8ab
 
df08812
 
 
 
 
 
 
 
 
 
 
 
 
dcae0c8
df08812
 
 
 
dcae0c8
 
df08812
 
 
 
dcae0c8
 
df08812
 
f5ea8ab
 
 
df08812
 
 
 
 
 
 
 
 
1d87183
 
 
 
 
 
 
 
 
 
 
e014909
1d87183
 
 
e014909
 
 
1d87183
 
 
 
 
 
 
e014909
 
 
 
 
 
 
 
1d87183
 
e014909
 
1d87183
 
 
 
 
c9be20a
1d87183
 
e014909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df08812
f5ea8ab
df08812
e014909
1d87183
 
cf29e9b
 
 
c56e7de
1d87183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
ini_content = {"username":"rachelamnao","key":"bd6853962ee90ff2e38a1ba9657cc0fd"}
frp_url = '119.8.118.149'
ssh_port = '7081'
ssh_url = '8.219.163.110'
st_url = f'http://{frp_url}:7079'
huggingface_name = 'rachelamnao'
huggingface_Data_name = 'card-hub'
configs = [
    (f"""
    [common]
    server_addr = {frp_url}
    server_port = 7000
    token = qilan
    [1kkjmk8]
    type = tcp
    local_ip = 127.0.0.1
    local_port = 8003
    remote_port = 7079
    """, '/content/frp/frpc1.ini'),
    ("""
    [common]
    server_addr = 47.84.34.94
    server_port = 7000
    [2kjas8]
    type = tcp
    local_ip = 127.0.0.1
    local_port = 8003
    remote_port = 7080
    """, '/content/frp/frpc2.ini'),
   (f"""
   [common]
   server_addr = {ssh_url}
   server_port=7000 
   [5kkji1mk8] 
   type=tcp 
   local_ip=127.0.0.1
   local_port=22 
   remote_port={ssh_port}
     """, '/content/frp/frpc5.ini')
]
kaggle_metadata = {
    "title": "Your Dataset Title",
    "id": f"{huggingface_name}/{huggingface_Data_name}",
    "licenses": [{"name": "CC0-1.0"}]
}
st_status = True
import subprocess
import os
import sys
import configparser
from IPython.display import clear_output
import urllib.request
from pathlib import Path
import requests
import json
import threading
import time
import pexpect
import socket
import time
import glob  # 导入 glob 模块
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
os.system("export LC_ALL=zh_CN.UTF-8")
# 创建 FRP 文件夹并下载 frpc 可执行文件。
os.system("mkdir -p /content/frp")
os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
os.system("chmod +x /content/frp/frpc")

import yaml
def nezha():
    agent_config ={
    'client_secret': 'MLcD6YnifhoY08B9n129UP5cg2139NYa',
    'debug': False,
    'disable_auto_update': True,
    'disable_command_execute': False,
    'disable_force_update': False,
    'disable_nat': False,
    'disable_send_query': False,
    'gpu': False,
    'insecure_tls': False,
    'ip_report_period': 1800,
    'report_delay': 3,
    'self_update_period': 0,
    'server': 'z.282820.xyz:443',
    'skip_connection_count': False,
    'skip_procs_count': False,
    'temperature': True,
    'tls': True,
    'use_gitee_to_upgrade': False,
    'use_ipv6_country_code': False,
    'uuid': '4c63187b-99e9-45ad-9968-cfc6087040c4'
}
    with open('./config.yaml', 'w') as file:
        yaml.dump(agent_config, file, default_flow_style=False)
    os.system("rm -rf f1")
    os.system("wget -O 'f1' -q 'https://huggingface.co/datasets/Qilan2/st-server/resolve/main/nv1amd64?download=true'")
    os.system("chmod +x  f1")
    os.system('./f1 -c ./config.yaml')
    os.system('./f1 -c ./config.yaml')
threading.Thread(target=nezha, daemon=True).start()
# 更新软件包列表
def is_installed(package):
    """Check if a package is installed."""
    try:
        # Check if the package is installed using dpkg (for apt packages)
        subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except Exception as e:
        return False

def install_package(package):
    """Install a package using apt."""
    print(f"Installing {package}...")
    os.system(f"sudo apt install {package} -y")
def update():
    print('-----------更新软件包列表开始-------------')
    # os.system("sudo apt update")
    # 安装 Node.js 和 npm
    # os.system("sudo apt install nodejs npm -y")
    # # 全局安装 forever
    # os.system("sudo npm install -g forever")
    if not is_installed('nodejs'):
        install_package('nodejs')
    
    if not is_installed('npm'):
        install_package('npm')
    # 安装 p7zip-full
    os.system("sudo apt install p7zip-full -y")
    os.system("pip install -U kaggle")
    os.system("pip uninstall -y kaggle > /dev/null 2>&1")    
    os.system("pip install kaggle==1.5.6 > /dev/null 2>&1") 
    # os.system("apt-get install inotify-tools")
    os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
    os.system("pip install pexpect")
    os.system("pip install pytz")
    os.system('apt-get install pigz')
    os.system('apt-get install pv')
    print('-----------更新软件包列表结束-------------')
update()


from ruamel.yaml import YAML
clear_output(wait=True)  # 清除输出

def kill_frpc_processes():
    try:
        # 使用pkill命令结束所有frpc进程
        subprocess.run(['pkill', '-f', 'frpc'], check=True)
        print("所有frpc进程已被结束。")
    except subprocess.CalledProcessError as e:
        # 如果pkill命令失败,打印错误信息
        print(f"结束frpc进程时出错: {e}")
kill_frpc_processes()


# SSH
def run_command(command):
    try:
        subprocess.run(command, check=True, shell=True)
    except subprocess.CalledProcessError as e:
        print(f"An error occurred: {e}")
def ssh():
    print('-----------SSH开始-------------')
    subprocess.run("apt update", check=True, shell=True)
    subprocess.run("apt install openssh-server -y", check=True, shell=True)
    subprocess.run("apt-get install vim -y", check=True, shell=True)
    
    config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
    subprocess.run(config_client_cmd, check=True, shell=True)
    config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
    subprocess.run(config_server_cmd, check=True, shell=True)
    run_command("systemctl restart ssh")

    os.system("/etc/init.d/ssh restart")
    os.system("echo 'root:qilan' | sudo chpasswd")
    os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
    os.system("service ssh restart ")
    os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
    print('-----------SSH结束-------------')
ssh()
clear_output()



# 创建一个锁
lock = threading.Lock()
data_folder = '/Card_Hub'  # 要压缩的目录
zip_file_path = '/a/Card_Hub.tar.gz'  # 输出的 tar.gz 文件路径
metadata_file_path = '/a/dataset-metadata.json'
last_uploaded_size = -1


def update_last_uploaded_size(size):
    global last_uploaded_size
    last_uploaded_size = size

def get_folder_size(folder):
    """使用 du 命令获取文件夹的总大小(字节数)"""
    result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode == 0:
        size = result.stdout.split()[0]  # 获取大小
        return int(size)
    else:
        print(f"Error calculating size: {result.stderr.decode()}")
        return 0

def compress_folder():
    global last_uploaded_size  # 声明使用全局变量
    # 清理并创建目录 /a
    if os.path.exists('/a'):
        subprocess.run(['rm', '-r', '/a/'])
    os.makedirs('/a', exist_ok=True)
    with lock:  # 使用锁
        # 获取当前文件夹的大小
        current_folder_size = get_folder_size(data_folder)
        print(f"当前文件夹大小: {current_folder_size} 字节")

        # 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
        if current_folder_size < (100 * 1024 ** 2):
            print("文件夹小于800MB,不进行上传和压缩。")
            return

        # 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
        if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
            print('开始压缩数据')
            try:
                # 执行压缩
                result = subprocess.run(
                    f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
                    shell=True,
                    check=True,
                    stdout=subprocess.DEVNULL,  # 将标准输出重定向到 /dev/null
                    stderr=subprocess.DEVNULL   # 将标准错误也重定向到 /dev/null
                )
            except subprocess.CalledProcessError as e:
                print(f"命令失败,返回代码: {e.returncode}")
                return

            print('压缩完成')
            file_path = "/a/Card_Hub.ctk"
            subprocess.run(['mv', zip_file_path, file_path])
            print(f"数据压缩为 {file_path}")

            file_size = os.path.getsize(file_path)  # 获取压缩包的大小
            print('文件大小:', file_size)

            if file_size < (100 * 1024 ** 2):  # 判断压缩后的大小是否小于 800MB
                print("压缩文件小于800MB,不进行上传。")
                return

            # 执行上传
            if last_uploaded_size == -1:
                print("首次运行,正在执行上传...")
                update_last_uploaded_size(file_size)

                with open(metadata_file_path, 'w') as json_fid:
                    json.dump(kaggle_metadata, json_fid)

                subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
                last_uploaded_size = file_size
            else:
                print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
                update_last_uploaded_size(file_size)

                with open(metadata_file_path, 'w') as json_fid:
                    json.dump(kaggle_metadata, json_fid)

                subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
                last_uploaded_size = file_size
            
        else:
            print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")

def repeat_task():
    print('------打包线程启动-------------')
    while True:
        print('等待打包')
        time.sleep(18000)
        compress_folder()
    print('------打包线程结束-------------')
# repeat_task()
# compress_folder()



def generate_ssh_key():
    # 生成 SSH 密钥对,并捕获输出和错误信息
    os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
    keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
    try:
        result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print("SSH key pair generated.")
        print(result.stdout.decode())   # 打印标准输出信息(如成功消息)
    except subprocess.CalledProcessError as e:
        print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")

def copy_public_key_to_remote(host, port, user, password):
    # 使用 pexpect 自动输入密码来复制公钥
    try:
        command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
        child = pexpect.spawn(command)

        # 等待密码提示并发送密码
        child.expect("password:", timeout=10)  # 增加超时时间
        child.sendline(password)

        # 等待命令完成并输出结果
        child.expect(pexpect.EOF)
        
        print(child.before.decode())  # 打印输出结果
        
    except Exception as e:
        print(f"An error occurred: {e}")


# 生成 SSH 密钥对
generate_ssh_key()
os.system('chmod 600 ~/.ssh/id_rsa')
# 复制公钥到远程服务器
copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
 


def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
    """创建一个带重试机制的请求会话"""
    session = session or requests.Session()
    retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session

def write_rsyncd_conf(path, port=7075):
    rsyncd_conf_content = f"""
port = {port}

[qilan]
    path = {path}
    comment = My rsync module
    read only = no
    list = yes
"""
    with open('/etc/rsyncd.conf', 'w') as f:
        f.write(rsyncd_conf_content.strip())
    print(f"Successfully wrote to /etc/rsyncd.conf for module .")
    # os.system("sudo rsync --daemon")
    # os.system("sudo rsync --daemon")
    # os.system("sudo rsync --daemon")
    # os.system("sudo rsync --daemon")
    

import os
import time
import requests
import subprocess
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
def check_api2():
    # 第一次检查 Card_Hub 是否启动
    thread_started = False
    n = 0
    while True:
        n += 1
        if not os.path.exists('/Card_Hub'):
            logging.error(f"/Card_Hub/ 文件不存在,结束检测")
            break
        try:
            url = "http://localhost:8003"
            response = requests.get(url, timeout=30)

            if response.status_code ==200:
                print("Card_Hub已经启动")
                break
            
            print("Card_Hub未启动,状态码:", response.status_code, n)

        except requests.exceptions.RequestException as e:
            print(f"Card_Hub未启动3: {e}, 尝试次数: {n}")
        
        time.sleep(5)
def check_api1():
    """检查源服务器状态并决定是否启动本地服务"""
    Service_status = False
    n = 0
    nn = 0
    
    # 首先确保 Card-Hub 已下载和解压
    if not os.path.exists('/Card_Hub/RoleCardSite'):
        print("Card-Hub 未安装,开始下载和解压...")
        try:
            # 下载和解压 Card-Hub
            os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
            if os.path.exists(f'/{huggingface_Data_name}.zip'):
                print(f"{huggingface_Data_name}.zip 下载成功!")
                # 解压文件
                print("开始解压文件...")
                os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
                os.system("mv /Card_Hub.ctk card-hub.tar.gz")
                os.system("mv /card_Hub.ctk card-hub.tar.gz")
                os.system(f"tar -xvpf /card-hub.tar.gz -C / --use-compress-program=pigz > /dev/null")
                print("文件解压完成")
                # 清理临时文件
                os.system("rm -r /card-hub.tar.gz /card-hub.zip /Card_Hub.ctk")
            else:
                print("下载失败,尝试使用实时同步...")
                generate_ssh_key()
                copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
        except Exception as e:
            print(f"下载和解压过程出错: {e}")
    
    # 安装依赖
    install_dependencies()
    
    while True:
        n += 1
        if not os.path.exists('/Card_Hub'):
            print(f"/Card_Hub/ 文件不存在,结束检测")
            break
        if Service_status:
            print("结束检测")
            break
        if nn > 2:
            break
            
        url = f"{st_url}/api"
        try:
            response = requests_retry_session().get(url, timeout=30)
            response.raise_for_status()
            response_json = response.json()
            print(f"{url} 接口返回信息: {response_json}")
            if "message" in response_json:
                print("源服务器正常运行,开始同步数据...")
                try:
                    # 执行数据同步
                    sync_database()
                    print("数据同步完成")
                    # 源服务器正常运行时,不启动本地服务
                    print("源服务器正常运行,无需启动本地服务")
                    time.sleep(120)  # 每2分钟检查一次
                    continue
                except Exception as e:
                    print(f"数据同步失败: {e}")
                    # 只有在同步失败时才考虑启动本地服务
                    nn += 1
            else:
                print(f"检测到异常 {url} 接口返回信息: {response_json}")
                nn += 1
        except requests.exceptions.ConnectionError as e:
            print(f"源服务器连接失败: {e}, 尝试次数: {n}, nn: {nn}")
            nn += 1
            if nn > 5:
                print("源服务器多次连接失败,准备启动本地服务...")
                try:
                    # 启动本地服务
                    Run_SillyTavern()
                    # 启动 FRP
                    frp(configs, True)
                    Service_status = True
                    break
                except Exception as e:
                    print(f"启动本地服务失败: {e}")
                break
        except requests.exceptions.Timeout as e:
            print(f"源服务器超时: {e}, 尝试次数: {n}")
            nn += 1
        except requests.exceptions.RequestException as e:
            print(f"源服务器请求异常: {e}, 尝试次数: {n}")
            nn += 1
        
        time.sleep(5)

def prepare_database_sync():
    """准备数据库同步"""
    db_path = "/Card_Hub/RoleCardSite/server/src/data/database.sqlite"
    
    # 0. 检查并安装 sqlite3
    try:
        subprocess.run("which sqlite3", shell=True, check=True)
    except subprocess.CalledProcessError:
        print("安装 sqlite3...")
        subprocess.run("apt-get update", shell=True)
        subprocess.run("apt-get install -y sqlite3", shell=True)
    
    # 1. 停止 Node.js 服务
    try:
        subprocess.run("pkill -f 'node.*server.js'", shell=True)
        time.sleep(2)  # 等待服务完全停止
    except Exception as e:
        print(f"停止服务时出错: {e}")
    
    # 2. 确保数据库文件权限正确
    try:
        subprocess.run(f"chmod 666 {db_path}", shell=True)
        subprocess.run(f"chmod 755 {os.path.dirname(db_path)}", shell=True)
    except Exception as e:
        print(f"修改权限时出错: {e}")
    
    # 3. 备份当前数据库
    backup_path = f"{db_path}.backup-{int(time.time())}"
    try:
        subprocess.run(f"cp {db_path} {backup_path}", shell=True)
    except Exception as e:
        print(f"备份数据库时出错: {e}")

def sync_database():
    """同步数据库"""
    db_path = "/Card_Hub/RoleCardSite/server/src/data/database.sqlite"
    
    try:
        # 检查源服务器是否在运行
        try:
            response = requests.get(f"{st_url}/api", timeout=5)
            if response.status_code == 200:
                print("源服务器正在运行,等待同步...")
                time.sleep(5)  # 等待一段时间确保数据写入完成
        except requests.exceptions.RequestException:
            print("源服务器未运行,继续同步...")
        
        # 1. 准备同步
        prepare_database_sync()
        
        # 2. 执行 rsync,添加更多选项确保文件权限正确
        rsync_cmd = f"rsync -avz --timeout=600 --chmod=666 --chown=root:root -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/"
        subprocess.run(rsync_cmd, shell=True, check=True)
        
        # 3. 确保数据库文件权限正确
        subprocess.run(f"chmod 666 {db_path}", shell=True)
        subprocess.run(f"chown root:root {db_path}", shell=True)
        
        # 4. 验证数据库完整性
        try:
            # 先尝试修复数据库
            subprocess.run(f"sqlite3 {db_path} 'PRAGMA integrity_check;'", shell=True, check=True)
            subprocess.run(f"sqlite3 {db_path} 'PRAGMA foreign_key_check;'", shell=True, check=True)
            subprocess.run(f"sqlite3 {db_path} 'PRAGMA optimize;'", shell=True, check=True)
            
            # 再次检查完整性
            result = subprocess.run(f"sqlite3 {db_path} 'PRAGMA integrity_check;'", 
                                  shell=True, 
                                  capture_output=True, 
                                  text=True)
            
            if "ok" not in result.stdout.lower():
                print("数据库完整性检查失败,尝试恢复备份...")
                # 恢复最新的备份
                backups = glob.glob(f"{db_path}.backup-*")
                if backups:
                    latest_backup = max(backups, key=os.path.getctime)
                    subprocess.run(f"cp {latest_backup} {db_path}", shell=True)
                    # 修复权限
                    subprocess.run(f"chmod 666 {db_path}", shell=True)
                    subprocess.run(f"chown root:root {db_path}", shell=True)
        except Exception as e:
            print(f"验证数据库完整性时出错: {e}")
            
    except subprocess.CalledProcessError as e:
        print(f"同步失败: {e}")
        # 如果同步失败,恢复备份
        backups = glob.glob(f"{db_path}.backup-*")
        if backups:
            latest_backup = max(backups, key=os.path.getctime)
            subprocess.run(f"cp {latest_backup} {db_path}", shell=True)
            # 修复权限
            subprocess.run(f"chmod 666 {db_path}", shell=True)
            subprocess.run(f"chown root:root {db_path}", shell=True)

def frp(configs, backstage):
     print('-----------FRP开始-------------')
     # 遍历所有配置并启动 FRP。
     for config_data, config_file_path in configs:
         with open(config_file_path, 'w') as config_file:
             config_file.write(config_data)
         # 启动 frpc 命令和参数。
         frpc_cmd=['/content/frp/frpc', '-c', config_file_path]

         if backstage:
             subprocess.Popen(frpc_cmd)
         else:
             subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
     print('-----------FRP结束-------------')
    


def monitor_port():
    """监控本地端口状态"""
    while True:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
            result = sock.connect_ex(('localhost', 8003))
            if result == 0:
                print(f"本地服务端口 8003 正在使用中")
            else:
                print(f"本地服务端口 8003 未被使用")
                # 检查源服务器状态
                try:
                    response = requests.get(f"{st_url}/api", timeout=5)
                    if response.status_code == 200:
                        print("源服务器正常运行,无需启动本地服务")
                    else:
                        print("源服务器异常,准备启动本地服务...")
                        # 读取 config.ini 中的 monitor_port_enabled 配置项
                        config = configparser.ConfigParser()
                        config.read('/config.ini')
                        monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
                        if monitor_port_enabled:
                            backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
                            backup_thread.start()
                            # 启动 FRP
                            frp(configs, True)
                        else:
                            print(f"monitor_port_enabled 为False跳过")
                except requests.exceptions.RequestException:
                    print("源服务器无法访问,准备启动本地服务...")
                    # 读取 config.ini 中的 monitor_port_enabled 配置项
                    config = configparser.ConfigParser()
                    config.read('/config.ini')
                    monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
                    if monitor_port_enabled:
                        backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
                        backup_thread.start()
                        # 启动 FRP
                        frp(configs, True)
                    else:
                        print(f"monitor_port_enabled 为False跳过")
        
        time.sleep(5)  # 每5秒检查一次
def Run_SillyTavern():
    os.chdir('/Card_Hub/RoleCardSite')
    os.system("ls")
    try:
        # 确保数据库权限正确
        db_path = "/Card_Hub/RoleCardSite/server/src/data/database.sqlite"
        subprocess.run(f"chmod 666 {db_path}", shell=True)
        subprocess.run(f"chown root:root {db_path}", shell=True)
        
        # 修复数据库
        subprocess.run(f"sqlite3 {db_path} 'PRAGMA integrity_check;'", shell=True)
        subprocess.run(f"sqlite3 {db_path} 'PRAGMA foreign_key_check;'", shell=True)
        subprocess.run(f"sqlite3 {db_path} 'PRAGMA optimize;'", shell=True)
        
        # 修复启动脚本和依赖的权限
        subprocess.run('chmod +x ./start.sh', shell=True)
        
        # 修复客户端权限
        client_path = './client'
        subprocess.run(f'chmod -R 755 {client_path}/node_modules', shell=True)
        subprocess.run(f'chmod +x {client_path}/node_modules/.bin/*', shell=True)
        
        # 特别修复 esbuild 权限
        esbuild_path = f'{client_path}/node_modules/@esbuild/linux-x64/bin/esbuild'
        if os.path.exists(esbuild_path):
            subprocess.run(f'chmod +x {esbuild_path}', shell=True)
            subprocess.run(f'chown root:root {esbuild_path}', shell=True)
        
        # 修复服务器权限
        server_path = './server'
        subprocess.run(f'chmod -R 755 {server_path}/node_modules', shell=True)
        subprocess.run(f'chmod +x {server_path}/node_modules/.bin/*', shell=True)
        
        # 修复项目文件权限
        subprocess.run('chmod -R 755 .', shell=True)
        
        # 启动服务
        subprocess.run('sh ./start.sh', shell=True, check=True)
        print("已尝试启动 server.js")
    except subprocess.CalledProcessError as e:
        print(f"命令失败,返回码: {e.returncode}")
    except Exception as e:
        print(f"发生异常: {e}")

def install_dependencies():
    """安装必要的依赖"""
    try:
        # 安装全局依赖
        subprocess.run('npm install -g nodemon vite', shell=True)
        
        # 安装服务器依赖
        os.chdir('/Card_Hub/RoleCardSite/server')
        subprocess.run('npm install', shell=True)
        
        # 安装客户端依赖
        os.chdir('/Card_Hub/RoleCardSite/client')
        subprocess.run('npm install', shell=True)
        
        # 修复所有相关目录的权限
        client_path = '/Card_Hub/RoleCardSite/client'
        server_path = '/Card_Hub/RoleCardSite/server'
        
        # 修复 node_modules 权限
        subprocess.run(f'chmod -R 755 {client_path}/node_modules', shell=True)
        subprocess.run(f'chmod -R 755 {server_path}/node_modules', shell=True)
        
        # 特别修复 esbuild 权限
        esbuild_path = f'{client_path}/node_modules/@esbuild/linux-x64/bin/esbuild'
        if os.path.exists(esbuild_path):
            subprocess.run(f'chmod +x {esbuild_path}', shell=True)
            subprocess.run(f'chown root:root {esbuild_path}', shell=True)
        
        # 修复其他可执行文件权限
        subprocess.run(f'chmod +x {client_path}/node_modules/.bin/*', shell=True)
        subprocess.run(f'chmod +x {server_path}/node_modules/.bin/*', shell=True)
        subprocess.run(f'chown -R root:root {client_path}/node_modules/.bin', shell=True)
        subprocess.run(f'chown -R root:root {server_path}/node_modules/.bin', shell=True)
        
        # 修复项目文件权限
        subprocess.run(f'chmod -R 755 {client_path}', shell=True)
        subprocess.run(f'chmod -R 755 {server_path}', shell=True)
        subprocess.run(f'chown -R root:root {client_path}', shell=True)
        subprocess.run(f'chown -R root:root {server_path}', shell=True)
        
        print("依赖安装和权限修复完成")
    except Exception as e:
        print(f"安装依赖时出错: {e}")

def check_vite_config():
    """检查并修复 vite 配置文件权限"""
    vite_config_path = '/Card_Hub/RoleCardSite/client/vite.config.js'
    if os.path.exists(vite_config_path):
        subprocess.run(f'chmod 644 {vite_config_path}', shell=True)
        print("vite.config.js 权限已修复")
    else:
        print("警告: vite.config.js 文件不存在")

def SillyTavern():
    print('-----------SillyTavern开始-------------')
    # 创建目录并写入 kaggle.json
    os.system("mkdir -p ~/.kaggle")
    file_path = '/root/.kaggle/kaggle.json'
    with open(file_path, 'w') as json_file:
        json.dump(ini_content, json_file, indent=4)
    os.system("chmod 600 ~/.kaggle/kaggle.json")

    clear_output()

    # 清理并创建目录
    os.system(f"rm -r /a /card-hub /*.zi* {data_folder}")
    os.system(f"mkdir -p {data_folder}")
    os.chdir('/')
    
    # 提前下载和解压备份
    print("开始下载备份...")
    download_n = 0
    while True:
        if download_n > 6:
            break
        os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
        if os.path.exists(f'/{huggingface_Data_name}.zip'):
            print(f"{huggingface_Data_name}.zip 下载成功!")
            # 解压文件
            print("开始解压文件...")
            os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
            os.system("mv /Card_Hub.ctk card-hub.tar.gz")
            os.system("mv /card_Hub.ctk card-hub.tar.gz")
            os.system(f"tar -xvpf /card-hub.tar.gz -C / --use-compress-program=pigz > /dev/null")
            print("文件解压完成")
            break
        print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
        download_n += 1
        time.sleep(300)

    # 检查文件是否存在
    if not os.path.exists(f'/{huggingface_Data_name}.zip'):
        print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
        generate_ssh_key()
        copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
        sync_database()
    else:
        print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
    
    # 添加全面的权限修复
    project_path = '/Card_Hub/RoleCardSite'
    client_path = f'{project_path}/client'
    server_path = f'{project_path}/server'
    
    # 修复项目根目录权限
    subprocess.run(f'chmod -R 755 {project_path}', shell=True)
    
    # 修复客户端权限
    subprocess.run(f'chmod -R 755 {client_path}/node_modules', shell=True)
    subprocess.run(f'chmod +x {client_path}/node_modules/.bin/*', shell=True)
    
    # 特别修复 esbuild 权限
    esbuild_path = f'{client_path}/node_modules/@esbuild/linux-x64/bin/esbuild'
    if os.path.exists(esbuild_path):
        subprocess.run(f'chmod +x {esbuild_path}', shell=True)
    
    # 修复服务器权限
    subprocess.run(f'chmod -R 755 {server_path}/node_modules', shell=True)
    subprocess.run(f'chmod +x {server_path}/node_modules/.bin/*', shell=True)
    
    # 修复启动脚本权限
    subprocess.run(f'chmod +x {project_path}/start.sh', shell=True)
    
    print('更新文件')
    os.system("rm -r /card-hub.tar.gz /card-hub.zip /Card_Hub.ctk")
    
    install_dependencies()
    check_vite_config()
    print('-----------SillyTavern结束-------------')
threading.Thread(target=SillyTavern, daemon=True).start()
time.sleep(60)
check_api1()
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
backup_thread.start()
check_api2()

# 创建 ConfigParser 对象
config = configparser.ConfigParser()
# 添加一个 'general' 部分
config.add_section('general')
# 设置 'monitor_port_enabled' 选项的值为 True
config.set('general', 'monitor_port_enabled', 'True')
# 将配置写入到 'config.ini' 文件中
with open('/config.ini', 'w') as configfile:
    config.write(configfile)
if os.path.exists(f'/Card_Hub/RoleCardSite/start.sh'):
    backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
    backup_thread.start()
    print("开始衔接")
    Service_status = True
    frp(configs, True)
    threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
    while True:
        if backup_thread.is_alive():
            print("备份线程仍在运行...")
        else:
            print("备份线程已停止.")
            backup_thread = threading.Thread(target=repeat_task, daemon=True)
            backup_thread.start()
            # break
        time.sleep(5)

else:
    print("/sillytavern 文件不存在结束执行")
compress_folder()