Skip to content

Commit 2272a49

Browse files
authored
Merge pull request #455 from yungwine/storage
Installation of segment archive node via TON Storage
2 parents 72d4357 + b8ea7ce commit 2272a49

File tree

10 files changed

+619
-249
lines changed

10 files changed

+619
-249
lines changed

modules/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,8 @@ class Setting:
6262
'auto_backup': Setting('validator', None, 'Make validator backup every election'),
6363
'auto_backup_path': Setting('validator', '/tmp/mytoncore/auto_backups/', 'Path to store auto-backups'),
6464
'prometheus_url': Setting('prometheus', None, 'Prometheus pushgateway url'),
65-
'onlyNode': Setting(None, None, 'MyTonCtrl will work only for collecting validator telemetry (if `sendTelemetry` is True), without participating in Elections and etc.')
65+
'onlyNode': Setting(None, None, 'MyTonCtrl will work only for collecting validator telemetry (if `sendTelemetry` is True), without participating in Elections and etc.'),
66+
'importGc': Setting(None, None, 'Delete imported archive blocks files. Restart mytoncore to apply this setting'),
6667
}
6768

6869

mytoncore/functions.py

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,6 @@ def Event(local, event_name):
5353
EnableVcEvent(local)
5454
elif event_name == "validator down":
5555
ValidatorDownEvent(local)
56-
elif event_name == "enable_ton_storage_provider":
57-
enable_ton_storage_provider_event(local)
5856
elif event_name.startswith("enable_mode"):
5957
enable_mode(local, event_name)
6058
local.exit()
@@ -84,15 +82,6 @@ def ValidatorDownEvent(local):
8482
# end define
8583

8684

87-
def enable_ton_storage_provider_event(local):
88-
config_path = local.db.ton_storage.provider.config_path
89-
config = GetConfig(path=config_path)
90-
key_bytes = base64.b64decode(config.ProviderKey)
91-
ton = MyTonCore(local)
92-
ton.import_wallet_with_version(key_bytes[:32], version="v3r2", wallet_name="provider_wallet_001")
93-
#end define
94-
95-
9685
def enable_mode(local, event_name):
9786
ton = MyTonCore(local)
9887
mode = event_name.split("_")[-1]
@@ -613,6 +602,35 @@ def check_initial_sync(local, ton):
613602
return
614603

615604

605+
def gc_import(local, ton):
606+
if not ton.local.db.get('importGc', False):
607+
return
608+
local.add_log("GC import is running", "debug")
609+
import_path = '/var/ton-work/db/import'
610+
files = os.listdir(import_path)
611+
if not files:
612+
local.add_log("No files left to import", "debug")
613+
ton.local.db['importGc'] = False
614+
return
615+
try:
616+
status = ton.GetValidatorStatus()
617+
node_seqno = int(status.shardclientmasterchainseqno)
618+
except Exception as e:
619+
local.add_log(f"Failed to get shardclientmasterchainseqno: {e}", "warning")
620+
return
621+
removed = 0
622+
for file in files:
623+
file_seqno = int(file.split('.')[1])
624+
if node_seqno > file_seqno + 101:
625+
try:
626+
os.remove(os.path.join(import_path, file))
627+
removed += 1
628+
except PermissionError:
629+
local.add_log(f"Failed to remove file {file}: Permission denied", "error")
630+
continue
631+
local.add_log(f"Removed {removed} import files up to {node_seqno} seqno", "debug")
632+
633+
616634
def General(local):
617635
local.add_log("start General function", "debug")
618636
ton = MyTonCore(local)
@@ -653,6 +671,9 @@ def General(local):
653671
if ton.in_initial_sync():
654672
local.start_cycle(check_initial_sync, sec=120, args=(local, ton))
655673

674+
if ton.local.db.get('importGc'):
675+
local.start_cycle(gc_import, sec=300, args=(local, ton))
676+
656677
thr_sleep()
657678
# end define
658679

mytonctrl/mytonctrl.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,6 @@ def inject_globals(func):
143143
module.add_console_commands(console)
144144

145145
console.AddItem("benchmark", inject_globals(run_benchmark), local.translate("benchmark_cmd"))
146-
# console.AddItem("activate_ton_storage_provider", inject_globals(activate_ton_storage_provider), local.translate("activate_ton_storage_provider_cmd"))
147146

148147
# Process input parameters
149148
opts, args = getopt.getopt(argv,"hc:w:",["config=","wallets="])
@@ -176,23 +175,6 @@ def inject_globals(func):
176175
#end define
177176

178177

179-
def activate_ton_storage_provider(local, ton, args):
180-
wallet_name = "provider_wallet_001"
181-
wallet = ton.GetLocalWallet(wallet_name)
182-
account = ton.GetAccount(wallet.addrB64)
183-
if account.status == "active":
184-
color_print("activate_ton_storage_provider - {green}Already activated{endc}")
185-
#return
186-
ton.ActivateWallet(wallet)
187-
destination = "0:7777777777777777777777777777777777777777777777777777777777777777"
188-
ton_storage = ton.GetSettings("ton_storage")
189-
comment = f"tsp-{ton_storage.provider.pubkey}"
190-
flags = ["-n", "-C", comment]
191-
ton.MoveCoins(wallet, destination, 0.01, flags=flags)
192-
color_print("activate_ton_storage_provider - {green}OK{endc}")
193-
#end define
194-
195-
196178
def about(local, ton, args):
197179
from modules import get_mode, get_mode_settings
198180
if len(args) != 1:

mytoninstaller/mytoninstaller.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
CreateSymlinks,
3030
enable_ls_proxy,
3131
enable_ton_storage,
32-
enable_ton_storage_provider,
3332
EnableMode, ConfigureFromBackup, ConfigureOnlyNode, SetInitialSync
3433
)
3534
from mytoninstaller.config import (
@@ -94,11 +93,13 @@ def Refresh(local):
9493
ton_work_dir = "/var/ton-work/"
9594
ton_bin_dir = bin_dir + "ton/"
9695
ton_src_dir = src_dir + "ton/"
96+
mtc_src_dir = src_dir + "mytonctrl/"
9797
local.buffer.bin_dir = bin_dir
9898
local.buffer.src_dir = src_dir
9999
local.buffer.ton_work_dir = ton_work_dir
100100
local.buffer.ton_bin_dir = ton_bin_dir
101101
local.buffer.ton_src_dir = ton_src_dir
102+
local.buffer.mtc_src_dir = mtc_src_dir
102103
ton_db_dir = ton_work_dir + "db/"
103104
keys_dir = ton_work_dir + "keys/"
104105
local.buffer.ton_db_dir = ton_db_dir
@@ -162,7 +163,7 @@ def Enable(local, args):
162163
print("'JR' - jsonrpc")
163164
print("'THA' - ton-http-api")
164165
print("'LSP' - ls-proxy")
165-
print("'TSP' - ton-storage + ton-storage-provider")
166+
print("'TS' - ton-storage")
166167
print("Example: 'enable FN'")
167168
return
168169
if name == "THA":
@@ -227,9 +228,8 @@ def Event(local, name):
227228
enable_ton_http_api(local)
228229
if name == "enableLSP":
229230
enable_ls_proxy(local)
230-
if name == "enableTSP":
231+
if name == "enableTS":
231232
enable_ton_storage(local)
232-
enable_ton_storage_provider(local)
233233
if name == "clc":
234234
ix = sys.argv.index("-i")
235235
initBlock_b64 = sys.argv[ix+1]
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import argparse
2+
import json
3+
import subprocess
4+
import sys
5+
import time
6+
import logging
7+
8+
9+
def run_vc(cmd: str):
10+
if binary:
11+
return subprocess.run([binary, '-k', client, '-p', server, '-a', address, '--cmd', cmd],
12+
stdout=subprocess.PIPE).stdout.decode()
13+
else: # use symlink
14+
return subprocess.run(['bash', 'validator-console', '--cmd', cmd],
15+
stdout=subprocess.PIPE).stdout.decode()
16+
17+
def get_last_mc_seqno():
18+
stats = run_vc('getstats')
19+
for line in stats.split('\n'):
20+
if line.startswith('masterchainblock'):
21+
return int(line.split()[1].split(',')[2].split(')')[0])
22+
23+
def restart_node():
24+
return subprocess.run(['systemctl', 'restart', 'validator']).returncode
25+
26+
def get_config():
27+
with open(config_path) as f:
28+
return json.load(f)
29+
30+
def set_config(config: dict):
31+
with open(config_path, 'w') as f:
32+
f.write(json.dumps(config, indent=4))
33+
34+
def set_hardforks(hfks: list):
35+
c = get_config()
36+
c['validator']['hardforks'] = hfks
37+
set_config(c)
38+
39+
def add_hardfork(hfk: dict):
40+
c = get_config()
41+
c['validator']['hardforks'].append(hfk)
42+
set_config(c)
43+
44+
45+
logger = logging.getLogger(__name__)
46+
logging.basicConfig(
47+
level=logging.DEBUG,
48+
format='%(asctime)s - %(levelname)s - %(message)s',
49+
datefmt='%Y-%m-%d %H:%M:%S'
50+
)
51+
52+
parser = argparse.ArgumentParser(description="Python script to process hardforks when syncing archive node.")
53+
parser.add_argument('--from-seqno', type=int, required=True, help='Global config path')
54+
parser.add_argument('--config-path', type=str, required=True, help='Global config path')
55+
parser.add_argument('--bin', type=str, help='VC bin')
56+
parser.add_argument('--client', type=str, help='VC Client')
57+
parser.add_argument('--server', type=str, help='VC Server')
58+
parser.add_argument('--address', type=str, help='VC Address')
59+
60+
args = parser.parse_args()
61+
config_path = args.config_path
62+
binary = args.bin
63+
client = args.client
64+
server = args.server
65+
address = args.address
66+
from_seqno = args.from_seqno
67+
68+
69+
hardforks = get_config()['validator']['hardforks']
70+
keep_hardforks = [h for h in hardforks if h['seqno'] <= from_seqno]
71+
hardforks = [h for h in hardforks if h['seqno'] > from_seqno]
72+
if len(hardforks) == 0:
73+
logger.info("No hardforks to process.")
74+
sys.exit(0)
75+
set_hardforks(keep_hardforks)
76+
77+
while True:
78+
if len(hardforks) == 0:
79+
break
80+
try:
81+
last_mc_seqno = get_last_mc_seqno()
82+
if not last_mc_seqno:
83+
logger.info("Waiting for last mc seqno...")
84+
time.sleep(300)
85+
continue
86+
if last_mc_seqno != hardforks[0]['seqno'] - 1:
87+
logger.info(f"Waiting for hardfork {hardforks[0]['seqno']}...")
88+
time.sleep(300)
89+
continue
90+
hardfork = hardforks.pop(0)
91+
logger.info(f"Processing hardfork {hardfork['seqno']}.")
92+
add_hardfork(hardfork)
93+
logger.info(f"Hardfork {hardfork['seqno']} has been added.")
94+
restart_node()
95+
logger.info(f"Node is restarted")
96+
except Exception as e:
97+
import traceback
98+
logger.error(f"Exception occurred: {e}\n{traceback.format_exc()}")
99+
time.sleep(60)
100+
101+
logger.info(f"All done.")

mytoninstaller/scripts/ton_storage_provider_installer.sh

Lines changed: 0 additions & 70 deletions
This file was deleted.

0 commit comments

Comments
 (0)