Skip to content

Commit f1d4947

Browse files
authored
Merge pull request #269 from ton-blockchain/mytonctrl2_dev
merge mytonctrl2_dev into mytonctrl2_testnet
2 parents 28804e7 + fe744ec commit f1d4947

File tree

10 files changed

+145
-85
lines changed

10 files changed

+145
-85
lines changed

modules/liteserver.py

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,8 @@
55

66
class LiteserverModule(MtcModule):
77

8-
description = 'For liteserver usage only - can\'t be used with validator.'
8+
description = 'For liteserver usage only without validator.'
99
default_value = False
1010

11-
def enable(self):
12-
from mytoninstaller.mytoninstaller import set_node_argument
13-
set_node_argument(self.local, ["--celldb-no-preload-all"])
14-
data = psutil.virtual_memory()
15-
ram = data.total / 2**30
16-
if ram < 100:
17-
set_node_argument(self.local, ["--celldb-cache-size", "1073741824"])
18-
19-
def disable(self):
20-
from mytoninstaller.mytoninstaller import set_node_argument
21-
from mytoninstaller.node_args import get_node_args
22-
set_node_argument(self.local, ["--celldb-no-preload-all", "-d"])
23-
if get_node_args()['--celldb-cache-size']:
24-
set_node_argument(self.local, ["--celldb-cache-size", "-d"])
25-
2611
def add_console_commands(self, console):
2712
...

modules/nominator_pool.py

Lines changed: 0 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -78,42 +78,6 @@ def activate_pool(self, args):
7878
self.do_activate_pool(pool)
7979
color_print("ActivatePool - {green}OK{endc}")
8080

81-
def do_deposit_to_pool(self, pool_addr, amount):
82-
wallet = self.ton.GetValidatorWallet()
83-
bocPath = self.ton.local.buffer.my_temp_dir + wallet.name + "validator-deposit-query.boc"
84-
fiftScript = self.ton.contractsDir + "nominator-pool/func/validator-deposit.fif"
85-
args = [fiftScript, bocPath]
86-
result = self.ton.fift.Run(args)
87-
resultFilePath = self.ton.SignBocWithWallet(wallet, bocPath, pool_addr, amount)
88-
self.ton.SendFile(resultFilePath, wallet)
89-
90-
def deposit_to_pool(self, args):
91-
try:
92-
poll_addr = args[0]
93-
amount = float(args[1])
94-
except:
95-
color_print("{red}Bad args. Usage:{endc} deposit_to_pool <pool-addr> <amount>")
96-
return
97-
self.do_deposit_to_pool(poll_addr, amount)
98-
color_print("DepositToPool - {green}OK{endc}")
99-
100-
def do_withdraw_from_pool(self, pool_addr, amount):
101-
pool_data = self.ton.GetPoolData(pool_addr)
102-
if pool_data["state"] == 0:
103-
self.ton.WithdrawFromPoolProcess(pool_addr, amount)
104-
else:
105-
self.ton.PendWithdrawFromPool(pool_addr, amount)
106-
107-
def withdraw_from_pool(self, args):
108-
try:
109-
pool_addr = args[0]
110-
amount = float(args[1])
111-
except:
112-
color_print("{red}Bad args. Usage:{endc} withdraw_from_pool <pool-addr> <amount>")
113-
return
114-
self.do_withdraw_from_pool(pool_addr, amount)
115-
color_print("WithdrawFromPool - {green}OK{endc}")
116-
11781
def update_validator_set(self, args):
11882
try:
11983
pool_addr = args[0]
@@ -127,8 +91,4 @@ def update_validator_set(self, args):
12791
def add_console_commands(self, console):
12892
console.AddItem("new_pool", self.new_pool, self.local.translate("new_pool_cmd"))
12993
console.AddItem("activate_pool", self.activate_pool, self.local.translate("activate_pool_cmd"))
130-
console.AddItem("deposit_to_pool", self.deposit_to_pool, self.local.translate("deposit_to_pool_cmd"))
131-
console.AddItem("withdraw_from_pool", self.withdraw_from_pool, self.local.translate("withdraw_from_pool_cmd"))
13294
console.AddItem("update_validator_set", self.update_validator_set, self.local.translate("update_validator_set_cmd"))
133-
134-

modules/pool.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,45 @@ def check_download_pool_contract_scripts(self):
5858
if not os.path.isdir(contract_path):
5959
self.ton.DownloadContract("https://github.com/ton-blockchain/nominator-pool")
6060

61+
def do_deposit_to_pool(self, pool_addr, amount):
62+
wallet = self.ton.GetValidatorWallet()
63+
bocPath = self.ton.local.buffer.my_temp_dir + wallet.name + "validator-deposit-query.boc"
64+
fiftScript = self.ton.contractsDir + "nominator-pool/func/validator-deposit.fif"
65+
args = [fiftScript, bocPath]
66+
result = self.ton.fift.Run(args)
67+
resultFilePath = self.ton.SignBocWithWallet(wallet, bocPath, pool_addr, amount)
68+
self.ton.SendFile(resultFilePath, wallet)
69+
70+
def deposit_to_pool(self, args):
71+
try:
72+
poll_addr = args[0]
73+
amount = float(args[1])
74+
except:
75+
color_print("{red}Bad args. Usage:{endc} deposit_to_pool <pool-addr> <amount>")
76+
return
77+
self.do_deposit_to_pool(poll_addr, amount)
78+
color_print("DepositToPool - {green}OK{endc}")
79+
80+
def do_withdraw_from_pool(self, pool_addr, amount):
81+
pool_data = self.ton.GetPoolData(pool_addr)
82+
if pool_data["state"] == 0:
83+
self.ton.WithdrawFromPoolProcess(pool_addr, amount)
84+
else:
85+
self.ton.PendWithdrawFromPool(pool_addr, amount)
86+
87+
def withdraw_from_pool(self, args):
88+
try:
89+
pool_addr = args[0]
90+
amount = float(args[1])
91+
except:
92+
color_print("{red}Bad args. Usage:{endc} withdraw_from_pool <pool-addr> <amount>")
93+
return
94+
self.do_withdraw_from_pool(pool_addr, amount)
95+
color_print("WithdrawFromPool - {green}OK{endc}")
96+
6197
def add_console_commands(self, console):
6298
console.AddItem("pools_list", self.print_pools_list, self.local.translate("pools_list_cmd"))
6399
console.AddItem("delete_pool", self.delete_pool, self.local.translate("delete_pool_cmd"))
64100
console.AddItem("import_pool", self.import_pool, self.local.translate("import_pool_cmd"))
101+
console.AddItem("deposit_to_pool", self.deposit_to_pool, self.local.translate("deposit_to_pool_cmd"))
102+
console.AddItem("withdraw_from_pool", self.withdraw_from_pool, self.local.translate("withdraw_from_pool_cmd"))

mytoncore/functions.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import subprocess
1111

1212
from mytoncore.mytoncore import MyTonCore
13+
from mytonctrl.utils import fix_git_config
1314
from mytoninstaller.config import GetConfig
1415
from mypylib.mypylib import (
1516
b2mb,
@@ -420,7 +421,9 @@ def Telemetry(local, ton):
420421

421422
# Get git hashes
422423
gitHashes = dict()
423-
gitHashes["mytonctrl"] = get_git_hash("/usr/src/mytonctrl")
424+
mtc_path = "/usr/src/mytonctrl"
425+
local.try_function(fix_git_config, args=[mtc_path])
426+
gitHashes["mytonctrl"] = get_git_hash(mtc_path)
424427
gitHashes["validator"] = GetBinGitHash(
425428
"/usr/bin/ton/validator-engine/validator-engine")
426429
data["gitHashes"] = gitHashes

mytoncore/mytoncore.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2280,6 +2280,9 @@ def GetComplaints(self, electionId=None, past=False):
22802280
complaints[chash] = item
22812281
#end for
22822282

2283+
# sort complaints by their creation time and hash
2284+
complaints = dict(sorted(complaints.items(), key=lambda item: (item[1]["createdTime"], item[0])))
2285+
22832286
# Set buffer
22842287
self.SetFunctionBuffer(bname, complaints)
22852288

@@ -3266,7 +3269,6 @@ def check_enable_mode(self, name):
32663269
if self.using_validator():
32673270
raise Exception(f'Cannot enable liteserver mode while validator mode is enabled. '
32683271
f'Use `disable_mode validator` first.')
3269-
MODES['liteserver'](self, self.local).enable()
32703272
if name == 'validator':
32713273
if self.using_liteserver():
32723274
raise Exception(f'Cannot enable validator mode while liteserver mode is enabled. '
@@ -3284,8 +3286,6 @@ def disable_mode(self, name):
32843286
current_modes = self.get_modes()
32853287
if name not in current_modes:
32863288
raise Exception(f'Unknown module name: {name}. Available modes: {", ".join(MODES)}')
3287-
if name == 'liteserver':
3288-
MODES['liteserver'](self, self.local).disable()
32893289
current_modes[name] = False
32903290
self.local.save()
32913291

mytonctrl/mytonctrl.py

Lines changed: 35 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,9 @@
3939
GetSwapInfo,
4040
GetBinGitHash,
4141
)
42+
from mytoncore.telemetry import is_host_virtual
4243
from mytonctrl.migrate import run_migrations
43-
from mytonctrl.utils import GetItemFromList, timestamp2utcdatetime
44+
from mytonctrl.utils import GetItemFromList, timestamp2utcdatetime, fix_git_config
4445

4546
import sys, getopt, os
4647

@@ -237,7 +238,7 @@ def check_installer_user(local):
237238
#end define
238239

239240

240-
def PreUp(local, ton):
241+
def PreUp(local: MyPyClass, ton: MyTonCore):
241242
CheckMytonctrlUpdate(local)
242243
check_installer_user(local)
243244
check_vport(local, ton)
@@ -249,8 +250,10 @@ def PreUp(local, ton):
249250

250251
def Installer(args):
251252
# args = ["python3", "/usr/src/mytonctrl/mytoninstaller.py"]
252-
args = ["python3", "-m", "mytoninstaller"]
253-
subprocess.run(args)
253+
cmd = ["python3", "-m", "mytoninstaller"]
254+
if args:
255+
cmd += ["-c", *args]
256+
subprocess.run(cmd)
254257
#end define
255258

256259

@@ -290,21 +293,6 @@ def check_vport(local, ton):
290293
#end define
291294

292295

293-
def fix_git_config(git_path: str):
294-
args = ["git", "status"]
295-
try:
296-
process = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=git_path, timeout=3)
297-
err = process.stderr.decode("utf-8")
298-
except Exception as e:
299-
err = str(e)
300-
if err:
301-
if 'git config --global --add safe.directory' in err:
302-
args = ["git", "config", "--global", "--add", "safe.directory", git_path]
303-
subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3)
304-
else:
305-
raise Exception(f'Failed to check git status: {err}')
306-
#end define
307-
308296
def check_git(input_args, default_repo, text):
309297
src_dir = "/usr/src"
310298
git_path = f"{src_dir}/{default_repo}"
@@ -467,8 +455,34 @@ def check_disk_usage(local, ton):
467455
print_warning(local, "disk_usage_warning")
468456
#end define
469457

458+
def check_sync(local, ton):
459+
validator_status = ton.GetValidatorStatus()
460+
if not validator_status.is_working or validator_status.out_of_sync >= 20:
461+
print_warning(local, "sync_warning")
462+
#end define
463+
464+
def check_validator_balance(local, ton):
465+
if ton.using_validator():
466+
validator_wallet = ton.GetValidatorWallet()
467+
validator_account = local.try_function(ton.GetAccount, args=[validator_wallet.addrB64])
468+
if validator_account is None:
469+
local.add_log(f"Failed to check validator wallet balance", "warning")
470+
return
471+
if validator_account.balance < 100:
472+
print_warning(local, "validator_balance_warning")
473+
#end define
474+
475+
def check_vps(local, ton):
476+
if ton.using_validator():
477+
data = local.try_function(is_host_virtual)
478+
if data and data["virtual"]:
479+
color_print(f"Virtualization detected: {data['product_name']}")
480+
470481
def warnings(local, ton):
471482
check_disk_usage(local, ton)
483+
check_sync(local, ton)
484+
check_validator_balance(local, ton)
485+
check_vps(local, ton)
472486
#end define
473487

474488
def CheckTonUpdate(local):
@@ -708,6 +722,8 @@ def PrintLocalStatus(local, adnlAddr, validatorIndex, validatorEfficiency, valid
708722
validatorBinGitPath = "/usr/bin/ton/validator-engine/validator-engine"
709723
mtcGitHash = get_git_hash(mtcGitPath, short=True)
710724
validatorGitHash = GetBinGitHash(validatorBinGitPath, short=True)
725+
fix_git_config(mtcGitPath)
726+
fix_git_config(validatorGitPath)
711727
mtcGitBranch = get_git_branch(mtcGitPath)
712728
validatorGitBranch = get_git_branch(validatorGitPath)
713729
mtcGitHash_text = bcolors.yellow_text(mtcGitHash)

mytonctrl/resources/translate.json

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,26 @@
419419
"ru": "{green}Доступно обновление TON. {red}Пожалуйста, обновите его с помощью команды `upgrade`.{endc}",
420420
"zh_TW": "{green}TON 有可用更新. {red}請使用 `upgrade` 命令進行更新.{endc}"
421421
},
422+
"disk_usage_warning": {
423+
"en": "{red} Disk is almost full, clean the TON database immediately: https://docs.ton.org/participate/nodes/node-maintenance-and-security#database-grooming {endc}",
424+
"ru": "{red} Диск почти заполнен, немедленно очистите базу данных TON: https://docs.ton.org/participate/nodes/node-maintenance-and-security#database-grooming {endc}",
425+
"zh_TW": "{red} 磁盤幾乎滿了,立即清理 TON 數據庫: https://docs.ton.org/participate/nodes/node-maintenance-and-security#database-grooming {endc}"
426+
},
427+
"sync_warning": {
428+
"en": "{red} Node is out of sync. The displayed status is incomplete. {endc}",
429+
"ru": "{red} Нода не синхронизирована с сетью. Отображаемый статус не полный. {endc}",
430+
"zh_TW": "{red} 节点不与网络同步。顯示的狀態不完整。 {endc}"
431+
},
432+
"validator_balance_warning": {
433+
"en": "{red} Validator wallet balance is low. {endc}",
434+
"ru": "{red} Баланс кошелька валидатора низкий. {endc}",
435+
"zh_TW": "{red} 驗證者錢包餘額不足。 {endc}"
436+
},
437+
"vps_warning": {
438+
"en": "{red} Validator is running on a VPS. Use a dedicated server for better performance. {endc}",
439+
"ru": "{red} Валидатор работает на VPS. Используйте выделенный сервер (дедик) для лучшей производительности. {endc}",
440+
"zh_TW": "{red} 驗證者在 VPS 上運行。使用專用服務器以獲得更好的性能。 {endc}"
441+
},
422442
"vport_error": {
423443
"en": "{red}Error - UDP port of the validator is not accessible from the outside.{endc}",
424444
"ru": "{red}Ошибка - UDP порт валидатора недоступен извне.{endc}",

mytonctrl/utils.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import subprocess
12
import time
23

34

@@ -12,3 +13,19 @@ def GetItemFromList(data, index):
1213
return data[index]
1314
except:
1415
pass
16+
17+
18+
def fix_git_config(git_path: str):
19+
args = ["git", "status"]
20+
try:
21+
process = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=git_path, timeout=3)
22+
err = process.stderr.decode("utf-8")
23+
except Exception as e:
24+
err = str(e)
25+
if err:
26+
if 'git config --global --add safe.directory' in err:
27+
args = ["git", "config", "--global", "--add", "safe.directory", git_path]
28+
subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3)
29+
else:
30+
raise Exception(f'Failed to check git status: {err}')
31+
#end define

mytoninstaller/mytoninstaller.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,29 @@ def Event(local, name):
238238
#end define
239239

240240

241-
def General(local):
241+
def Command(local, args, console):
242+
cmd = args[0]
243+
args = args[1:]
244+
for item in console.menu_items:
245+
if cmd == item.cmd:
246+
console._try(item.func, args)
247+
print()
248+
local.exit()
249+
print(console.unknown_cmd)
250+
local.exit()
251+
#end define
252+
253+
254+
def General(local, console):
242255
if "-u" in sys.argv:
243256
ux = sys.argv.index("-u")
244257
user = sys.argv[ux+1]
245258
local.buffer.user = user
246259
Refresh(local)
260+
if "-c" in sys.argv:
261+
cx = sys.argv.index("-c")
262+
args = sys.argv[cx+1:]
263+
Command(local, args, console)
247264
if "-e" in sys.argv:
248265
ex = sys.argv.index("-e")
249266
name = sys.argv[ex+1]
@@ -282,7 +299,7 @@ def mytoninstaller():
282299

283300
Init(local, console)
284301
if len(sys.argv) > 1:
285-
General(local)
302+
General(local, console)
286303
else:
287304
console.Run()
288305
local.exit()

mytoninstaller/settings.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ def FirstNodeSettings(local):
3434
validatorAppPath = local.buffer.validator_app_path
3535
globalConfigPath = local.buffer.global_config_path
3636
vconfig_path = local.buffer.vconfig_path
37+
archive_ttl = 2592000 if local.buffer.mode == 'liteserver' else 86400
3738

3839
# Проверить конфигурацию
3940
if os.path.isfile(vconfig_path):
@@ -57,8 +58,7 @@ def FirstNodeSettings(local):
5758

5859
# Прописать автозагрузку
5960
cpus = psutil.cpu_count() - 1
60-
cmd = "{validatorAppPath} --threads {cpus} --daemonize --global-config {globalConfigPath} --db {ton_db_dir} --logname {tonLogPath} --state-ttl 604800 --verbosity 1"
61-
cmd = cmd.format(validatorAppPath=validatorAppPath, globalConfigPath=globalConfigPath, ton_db_dir=ton_db_dir, tonLogPath=tonLogPath, cpus=cpus)
61+
cmd = f"{validatorAppPath} --threads {cpus} --daemonize --global-config {globalConfigPath} --db {ton_db_dir} --logname {tonLogPath} --state-ttl 604800 --archive-ttl {archive_ttl} --verbosity 1"
6262
add2systemd(name="validator", user=vuser, start=cmd) # post="/usr/bin/python3 /usr/src/mytonctrl/mytoncore.py -e \"validator down\""
6363

6464
# Получить внешний ip адрес
@@ -891,6 +891,10 @@ def CreateSymlinks(local):
891891

892892

893893
def EnableMode(local):
894+
args = ["python3", "-m", "mytoncore", "-e"]
894895
if local.buffer.mode == 'liteserver':
895-
args = ["python3", "-m", "mytoncore", "-e", "enable_liteserver_mode"]
896-
subprocess.run(args)
896+
args.append("enable_liteserver_mode")
897+
else:
898+
return
899+
args = ["su", "-l", local.buffer.user, "-c", ' '.join(args)]
900+
subprocess.run(args)

0 commit comments

Comments
 (0)