106 lines
3 KiB
Python
106 lines
3 KiB
Python
import time
|
|
import datetime
|
|
import json
|
|
import os
|
|
import sys
|
|
|
|
# for network
|
|
import socket
|
|
import fcntl
|
|
import struct
|
|
import array
|
|
import urllib
|
|
|
|
|
|
class Common:
|
|
def load_config(self):
|
|
self.settings_node = self.settings_node()
|
|
self.settings_vm = self.settings_vm()
|
|
|
|
def time(self):
|
|
"""
|
|
используется для вывода времени на экран в консоли
|
|
"""
|
|
return str(datetime.datetime.now())
|
|
|
|
def error(self, code):
|
|
"""
|
|
вывод ошибки по error.id
|
|
"""
|
|
if code == 1:
|
|
message = "Invalid JSON-RPC. Unknown RPC version"
|
|
print(time.time() + " - " + message)
|
|
return {"error": {"code": code, "message": message}}
|
|
|
|
def settings_node(self):
|
|
"""
|
|
конфигурация ноды
|
|
"""
|
|
if os.path.isfile('/etc/gocloud/node/node.json'):
|
|
with open('/etc/gocloud/node/node.json') as nodesettings_file:
|
|
conf = json.load(nodesettings_file)
|
|
else:
|
|
print("[Errno 2] No such file or directory: '/etc/gocloud/node/node.json'")
|
|
sys.exit(2)
|
|
|
|
return conf
|
|
|
|
def settings_vm(self):
|
|
"""
|
|
конфигурационные параметры для виртуальных машин
|
|
"""
|
|
if os.path.isfile('/etc/gocloud/node/vmsettings.json'):
|
|
with open('/etc/gocloud/node/vmsettings.json') as vmsettings_file:
|
|
conf = json.load(vmsettings_file)
|
|
else:
|
|
print("[Errno 2] No such file or directory: '/etc/gocloud/node/vmsettings.json'")
|
|
sys.exit(2)
|
|
|
|
return conf
|
|
|
|
def linux_distribution(self):
|
|
try:
|
|
return platform.linux_distribution()
|
|
except:
|
|
return 0
|
|
|
|
# network
|
|
def all_interfaces(self):
|
|
# arbitrary. raise if needed.
|
|
max_possible = 128
|
|
bytes = max_possible * 32
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
names = array.array('B', '\0' * bytes)
|
|
outbytes = struct.unpack('iL', fcntl.ioctl(
|
|
s.fileno(),
|
|
0x8912, # SIOCGIFCONF
|
|
struct.pack('iL', bytes, names.buffer_info()[0])
|
|
))[0]
|
|
namestr = names.tostring()
|
|
lst = []
|
|
for i in range(0, outbytes, 40):
|
|
name = namestr[i:i+16].split('\0', 1)[0]
|
|
ip = namestr[i+20:i+24]
|
|
lst.append((name, ip))
|
|
return lst
|
|
|
|
def format_ip(self, addr):
|
|
return str(ord(addr[0])) + '.' + str(ord(addr[1])) + '.' + str(ord(addr[2])) + '.' + str(ord(addr[3]))
|
|
|
|
def check_file_exists(self, filename):
|
|
if os.path.isfile(filename):
|
|
return True
|
|
else:
|
|
return False
|
|
|
|
def server_request(self, server_url, request):
|
|
params = {
|
|
"request": json.dumps(request)
|
|
}
|
|
return urllib.urlopen(server_url, urllib.urlencode(params)).read()
|
|
|
|
@staticmethod
|
|
def is_root_user():
|
|
if os.getuid() == 0:
|
|
return True
|
|
return False
|