Skip to content

Commit 46b95fd

Browse files
authored
Merge pull request #243 from yungwine/mytonctrl2_dev
dev
2 parents ab9d500 + 78f32e5 commit 46b95fd

File tree

3 files changed

+158
-148
lines changed

3 files changed

+158
-148
lines changed

mytoncore/functions.py

Lines changed: 12 additions & 145 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,16 @@
1010
import subprocess
1111

1212
from mytoncore.mytoncore import MyTonCore
13-
from mytoncore.utils import parse_db_stats
1413
from mytoninstaller.config import GetConfig
1514
from mypylib.mypylib import (
1615
b2mb,
1716
get_timestamp,
1817
get_internet_interface_name,
1918
get_git_hash,
20-
get_service_pid,
2119
get_load_avg,
2220
thr_sleep,
23-
Dict
2421
)
22+
from mytoncore.telemetry import *
2523
from mytoninstaller.node_args import get_node_args
2624

2725

@@ -382,141 +380,6 @@ def Domains(local, ton):
382380
# end define
383381

384382

385-
def GetUname():
386-
data = os.uname()
387-
result = dict(
388-
zip('sysname nodename release version machine'.split(), data))
389-
result.pop("nodename")
390-
return result
391-
# end define
392-
393-
394-
def GetMemoryInfo():
395-
result = dict()
396-
data = psutil.virtual_memory()
397-
result["total"] = round(data.total / 10**9, 2)
398-
result["usage"] = round(data.used / 10**9, 2)
399-
result["usagePercent"] = data.percent
400-
return result
401-
# end define
402-
403-
404-
def GetSwapInfo():
405-
result = dict()
406-
data = psutil.swap_memory()
407-
result["total"] = round(data.total / 10**9, 2)
408-
result["usage"] = round(data.used / 10**9, 2)
409-
result["usagePercent"] = data.percent
410-
return result
411-
# end define
412-
413-
414-
def GetValidatorProcessInfo():
415-
pid = get_service_pid("validator")
416-
if pid == None or pid == 0:
417-
return
418-
p = psutil.Process(pid)
419-
mem = p.memory_info()
420-
result = dict()
421-
result["cpuPercent"] = p.cpu_percent()
422-
memory = dict()
423-
memory["rss"] = mem.rss
424-
memory["vms"] = mem.vms
425-
memory["shared"] = mem.shared
426-
memory["text"] = mem.text
427-
memory["lib"] = mem.lib
428-
memory["data"] = mem.data
429-
memory["dirty"] = mem.dirty
430-
result["memory"] = memory
431-
# io = p.io_counters() # Permission denied: '/proc/{pid}/io'
432-
return result
433-
# end define
434-
435-
436-
def get_db_stats():
437-
result = {
438-
'rocksdb': {
439-
'ok': True,
440-
'message': '',
441-
'data': {}
442-
},
443-
'celldb': {
444-
'ok': True,
445-
'message': '',
446-
'data': {}
447-
},
448-
}
449-
rocksdb_stats_path = '/var/ton-work/db/db_stats.txt'
450-
celldb_stats_path = '/var/ton-work/db/celldb/db_stats.txt'
451-
if os.path.exists(rocksdb_stats_path):
452-
try:
453-
result['rocksdb']['data'] = parse_db_stats(rocksdb_stats_path)
454-
except Exception as e:
455-
result['rocksdb']['ok'] = False
456-
result['rocksdb']['message'] = f'failed to fetch db stats: {e}'
457-
else:
458-
result['rocksdb']['ok'] = False
459-
result['rocksdb']['message'] = 'db stats file is not exists'
460-
# end if
461-
462-
if os.path.exists(celldb_stats_path):
463-
try:
464-
result['celldb']['data'] = parse_db_stats(celldb_stats_path)
465-
except Exception as e:
466-
result['celldb']['ok'] = False
467-
result['celldb']['message'] = f'failed to fetch db stats: {e}'
468-
else:
469-
result['celldb']['ok'] = False
470-
result['celldb']['message'] = 'db stats file is not exists'
471-
# end if
472-
473-
return result
474-
# end define
475-
476-
477-
def get_cpu_name():
478-
with open('/proc/cpuinfo') as f:
479-
for line in f:
480-
if line.strip():
481-
if line.rstrip('\n').startswith('model name'):
482-
return line.rstrip('\n').split(':')[1].strip()
483-
return None
484-
485-
486-
def is_host_virtual():
487-
try:
488-
with open('/sys/class/dmi/id/product_name') as f:
489-
product_name = f.read().strip().lower()
490-
if 'virtual' in product_name or 'kvm' in product_name or 'qemu' in product_name or 'vmware' in product_name:
491-
return {'virtual': True, 'product_name': product_name}
492-
return {'virtual': False, 'product_name': product_name}
493-
except FileNotFoundError:
494-
return {'virtual': None, 'product_name': None}
495-
496-
497-
def do_beacon_ping(host, count, timeout):
498-
args = ['ping', '-c', str(count), '-W', str(timeout), host]
499-
process = subprocess.run(args, stdin=subprocess.PIPE,
500-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
501-
output = process.stdout.decode("utf-8")
502-
avg = output.split('\n')[-2].split('=')[1].split('/')[1]
503-
return float(avg)
504-
505-
506-
def get_pings_values():
507-
return {
508-
'beacon-eu-01.toncenter.com': do_beacon_ping('beacon-eu-01.toncenter.com', 5, 10),
509-
'beacon-apac-01.toncenter.com': do_beacon_ping('beacon-apac-01.toncenter.com', 5, 10)
510-
}
511-
512-
513-
def get_validator_disk_name():
514-
process = subprocess.run("df -h /var/ton-work/ | sed -n '2 p' | awk '{print $1}'", stdin=subprocess.PIPE,
515-
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3, shell=True)
516-
output = process.stdout.decode("utf-8")
517-
return output.strip()
518-
519-
520383
def Telemetry(local, ton):
521384
sendTelemetry = local.db.get("sendTelemetry")
522385
if sendTelemetry is not True:
@@ -540,13 +403,11 @@ def Telemetry(local, ton):
540403
data["swap"] = GetSwapInfo()
541404
data["uname"] = GetUname()
542405
data["vprocess"] = GetValidatorProcessInfo()
543-
data["dbStats"] = get_db_stats()
544-
data["nodeArgs"] = get_node_args()
545-
data["cpuInfo"] = {'cpuName': get_cpu_name(), 'virtual': is_host_virtual()}
546-
data["validatorDiskName"] = get_validator_disk_name()
547-
data["pings"] = get_pings_values()
548-
elections = local.try_function(ton.GetElectionEntries)
549-
complaints = local.try_function(ton.GetComplaints)
406+
data["dbStats"] = local.try_function(get_db_stats)
407+
data["nodeArgs"] = local.try_function(get_node_args)
408+
data["cpuInfo"] = {'cpuName': local.try_function(get_cpu_name), 'virtual': local.try_function(is_host_virtual)}
409+
data["validatorDiskName"] = local.try_function(get_validator_disk_name)
410+
data["pings"] = local.try_function(get_pings_values)
550411

551412
# Get git hashes
552413
gitHashes = dict()
@@ -645,6 +506,11 @@ def Slashing(local, ton):
645506
# end define
646507

647508

509+
def save_past_events(local, ton):
510+
local.try_function(ton.GetElectionEntries)
511+
local.try_function(ton.GetComplaints)
512+
513+
648514
def ScanLiteServers(local, ton):
649515
# Считать список серверов
650516
filePath = ton.liteClient.configPath
@@ -679,6 +545,7 @@ def General(local):
679545
local.start_cycle(Elections, sec=600, args=(local, ton, ))
680546
local.start_cycle(Statistics, sec=10, args=(local, ))
681547
local.start_cycle(Offers, sec=600, args=(local, ton, ))
548+
local.start_cycle(save_past_events, sec=300, args=(local, ton, ))
682549

683550
t = 600
684551
if ton.GetNetworkName() != 'mainnet':

mytoncore/telemetry.py

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
import os
2+
import subprocess
3+
4+
import psutil
5+
6+
from mytoncore.utils import parse_db_stats
7+
from mypylib.mypylib import get_service_pid
8+
9+
10+
def GetUname():
11+
data = os.uname()
12+
result = dict(
13+
zip('sysname nodename release version machine'.split(), data))
14+
result.pop("nodename")
15+
return result
16+
# end define
17+
18+
19+
def GetMemoryInfo():
20+
result = dict()
21+
data = psutil.virtual_memory()
22+
result["total"] = round(data.total / 10**9, 2)
23+
result["usage"] = round(data.used / 10**9, 2)
24+
result["usagePercent"] = data.percent
25+
return result
26+
# end define
27+
28+
29+
def GetSwapInfo():
30+
result = dict()
31+
data = psutil.swap_memory()
32+
result["total"] = round(data.total / 10**9, 2)
33+
result["usage"] = round(data.used / 10**9, 2)
34+
result["usagePercent"] = data.percent
35+
return result
36+
# end define
37+
38+
39+
def GetValidatorProcessInfo():
40+
pid = get_service_pid("validator")
41+
if pid == None or pid == 0:
42+
return
43+
p = psutil.Process(pid)
44+
mem = p.memory_info()
45+
result = dict()
46+
result["cpuPercent"] = p.cpu_percent()
47+
memory = dict()
48+
memory["rss"] = mem.rss
49+
memory["vms"] = mem.vms
50+
memory["shared"] = mem.shared
51+
memory["text"] = mem.text
52+
memory["lib"] = mem.lib
53+
memory["data"] = mem.data
54+
memory["dirty"] = mem.dirty
55+
result["memory"] = memory
56+
# io = p.io_counters() # Permission denied: '/proc/{pid}/io'
57+
return result
58+
# end define
59+
60+
61+
def get_db_stats():
62+
result = {
63+
'rocksdb': {
64+
'ok': True,
65+
'message': '',
66+
'data': {}
67+
},
68+
'celldb': {
69+
'ok': True,
70+
'message': '',
71+
'data': {}
72+
},
73+
}
74+
rocksdb_stats_path = '/var/ton-work/db/db_stats.txt'
75+
celldb_stats_path = '/var/ton-work/db/celldb/db_stats.txt'
76+
if os.path.exists(rocksdb_stats_path):
77+
try:
78+
result['rocksdb']['data'] = parse_db_stats(rocksdb_stats_path)
79+
except Exception as e:
80+
result['rocksdb']['ok'] = False
81+
result['rocksdb']['message'] = f'failed to fetch db stats: {e}'
82+
else:
83+
result['rocksdb']['ok'] = False
84+
result['rocksdb']['message'] = 'db stats file is not exists'
85+
# end if
86+
87+
if os.path.exists(celldb_stats_path):
88+
try:
89+
result['celldb']['data'] = parse_db_stats(celldb_stats_path)
90+
except Exception as e:
91+
result['celldb']['ok'] = False
92+
result['celldb']['message'] = f'failed to fetch db stats: {e}'
93+
else:
94+
result['celldb']['ok'] = False
95+
result['celldb']['message'] = 'db stats file is not exists'
96+
# end if
97+
98+
return result
99+
# end define
100+
101+
102+
def get_cpu_name():
103+
with open('/proc/cpuinfo') as f:
104+
for line in f:
105+
if line.strip():
106+
if line.rstrip('\n').startswith('model name'):
107+
return line.rstrip('\n').split(':')[1].strip()
108+
return None
109+
110+
111+
def is_host_virtual():
112+
try:
113+
with open('/sys/class/dmi/id/product_name') as f:
114+
product_name = f.read().strip().lower()
115+
if 'virtual' in product_name or 'kvm' in product_name or 'qemu' in product_name or 'vmware' in product_name:
116+
return {'virtual': True, 'product_name': product_name}
117+
return {'virtual': False, 'product_name': product_name}
118+
except FileNotFoundError:
119+
return {'virtual': None, 'product_name': None}
120+
121+
122+
def do_beacon_ping(host, count, timeout):
123+
args = ['ping', '-c', str(count), '-W', str(timeout), host]
124+
process = subprocess.run(args, stdin=subprocess.PIPE,
125+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
126+
output = process.stdout.decode("utf-8")
127+
avg = output.split('\n')[-2].split('=')[1].split('/')[1]
128+
return float(avg)
129+
130+
131+
def get_pings_values():
132+
return {
133+
'beacon-eu-01.toncenter.com': do_beacon_ping('beacon-eu-01.toncenter.com', 5, 10),
134+
'beacon-apac-01.toncenter.com': do_beacon_ping('beacon-apac-01.toncenter.com', 5, 10)
135+
}
136+
137+
138+
def get_validator_disk_name():
139+
process = subprocess.run("df -h /var/ton-work/ | sed -n '2 p' | awk '{print $1}'", stdin=subprocess.PIPE,
140+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3, shell=True)
141+
output = process.stdout.decode("utf-8")
142+
return output.strip()
143+

mytonctrl/mytonctrl.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ def about(local, ton, args):
223223
#end define
224224

225225

226-
def check_installer_user():
226+
def check_installer_user(local):
227227
args = ["whoami"]
228228
process = subprocess.run(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=3)
229229
username = process.stdout.decode("utf-8").strip()
@@ -234,13 +234,13 @@ def check_installer_user():
234234
actual_user = output.split('\n')[1].split()[2]
235235

236236
if username != actual_user:
237-
raise Exception(f'mytonctrl was installed by another user. Probably you need to launch mtc with `{actual_user}` user.')
237+
local.add_log(f'mytonctrl was installed by another user. Probably you need to launch mtc with `{actual_user}` user.', 'error')
238238
#end define
239239

240240

241241
def PreUp(local, ton):
242242
CheckMytonctrlUpdate(local)
243-
check_installer_user()
243+
check_installer_user(local)
244244
check_vport(local, ton)
245245
warnings(local, ton)
246246
# CheckTonUpdate()

0 commit comments

Comments
 (0)