Ahenk/opt/ahenk/base/registration/Registration.py

175 lines
6.9 KiB
Python
Raw Normal View History

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
import datetime
import json
import socket
import uuid
2016-04-13 15:24:15 +03:00
import os
2016-05-06 16:43:18 +03:00
import platform
import psutil
from uuid import getnode as get_mac
from base.Scope import Scope
2016-05-16 17:28:58 +03:00
from base.system.system import System
from base.messaging.AnonymousMessager import AnonymousMessager
class Registration():
def __init__(self):
scope = Scope().getInstance()
self.logger = scope.getLogger()
self.message_manager = scope.getMessageManager()
self.event_manager = scope.getEventManager()
self.messager = scope.getMessager()
2016-04-08 15:54:26 +03:00
self.conf_manager = scope.getConfigurationManager()
self.db_service = scope.getDbService()
2016-04-08 15:54:26 +03:00
self.event_manager.register_event('REGISTRATION_RESPONSE', self.registration_process)
if self.is_registered():
self.logger.debug('[Registration] Ahenk already registered')
else:
2016-03-07 12:55:14 +02:00
self.register(True)
2016-03-07 12:55:14 +02:00
def registration_request(self):
self.logger.debug('[Registration] Requesting registration')
anon_messager = AnonymousMessager(self.message_manager.registration_msg(), None)
anon_messager.connect_to_server()
2016-03-10 09:53:51 +02:00
def ldap_registration_request(self):
self.logger.debug('[Registration] Requesting LDAP registration')
self.messager.send_Direct_message(self.message_manager.ldap_registration_msg())
2016-03-10 09:53:51 +02:00
2016-04-08 15:54:26 +03:00
def registration_process(self, reg_reply):
self.logger.debug('[Registration] Reading registration reply')
j = json.loads(reg_reply)
self.logger.debug('[Registration]' + j['message'])
status = str(j['status']).lower()
dn = str(j['agentDn']).lower()
2016-04-08 15:54:26 +03:00
self.logger.debug('[Registration] Registration status: ' + str(status))
2016-04-08 15:54:26 +03:00
if 'already_exists' == str(status) or 'registered' == str(status) or 'registered_without_ldap' == str(status):
self.logger.debug('dn:' + dn)
2016-04-08 15:54:26 +03:00
self.update_registration_attrs(dn)
elif 'registration_error' == str(status):
self.logger.info('[Registration] Registration is failed. New registration request will send')
self.re_register()
self.registration_request()
2016-04-08 15:54:26 +03:00
else:
self.logger.error('[Registration] Bad message type of registration response ')
2016-04-08 15:54:26 +03:00
def update_registration_attrs(self, dn=None):
self.logger.debug('[Registration] Registration configuration is updating...')
self.db_service.update('registration', ['dn', 'registered'], [dn, 1], ' registered = 0')
2016-03-10 09:53:51 +02:00
2016-03-23 17:34:12 +02:00
if self.conf_manager.has_section('CONNECTION'):
2016-04-08 15:54:26 +03:00
self.conf_manager.set('CONNECTION', 'uid', self.db_service.select_one_result('registration', 'jid', ' registered=1'))
self.conf_manager.set('CONNECTION', 'password', self.db_service.select_one_result('registration', 'password', ' registered=1'))
# TODO get file path?
2016-03-23 17:34:12 +02:00
with open('/etc/ahenk/ahenk.conf', 'w') as configfile:
self.conf_manager.write(configfile)
self.logger.debug('[Registration] Registration configuration file is updated')
def is_registered(self):
registered = self.db_service.select_one_result('registration', 'registered', 'registered = 1')
if registered == 1:
return True
else:
return False
2016-03-10 09:53:51 +02:00
def is_ldap_registered(self):
dn = self.db_service.select_one_result('registration', 'dn', 'registered = 1')
if dn is not None and dn != '':
2016-03-10 09:53:51 +02:00
return True
else:
return False
def register(self, uuid_depend_mac=False):
cols = ['jid', 'password', 'registered', 'params', 'timestamp']
vals = [str(self.generate_uuid(uuid_depend_mac)), str(self.generate_password()), 0, str(self.get_registration_params()), str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M"))]
self.db_service.delete('registration', ' 1==1 ')
self.db_service.update('registration', cols, vals)
self.logger.debug('[Registration] Registration parameters were created')
def get_registration_params(self):
2016-05-16 17:28:58 +03:00
print(System.Hardware.Network.ip_addresses())
params = {
2016-05-16 17:28:58 +03:00
'ipAddresses': self.get_ip_address(),
'macAddresses': System.Hardware.mac_address(),
2016-05-06 16:43:18 +03:00
'hostname': str(socket.gethostname()),
2016-05-16 17:28:58 +03:00
'system': str(platform.system()),
'node': str(platform.node()),
'release': str(platform.release()),
'version': str(platform.version()),
'machine': str(platform.machine()),
'processor': str(platform.processor()),
'architecture': str(platform.architecture()),
'cpuCount': str(psutil.cpu_count()),
'diskInfo': self.get_disks()
}
return json.dumps(params)
2016-05-16 17:28:58 +03:00
def get_ip_address(self):
arr = []
for ip in System.Hardware.Network.ip_addresses():
if ip is not 'localhost' and ip is not '127.0.0.1':
arr.append(ip)
return str(arr).replace('[','').replace(']','')
2016-05-06 16:43:18 +03:00
def get_disks(self):
disk_info = []
for _disk in psutil.disk_partitions():
disk = {}
disk['device'] = str(_disk[0])
disk['mountPoint'] = str(_disk[1])
disk['fsType'] = str(_disk[2])
disk['opts'] = str(_disk[3])
json_data = json.dumps(disk)
disk_info.append(json_data)
return disk_info
def unregister(self):
self.logger.debug('[Registration] Ahenk is unregistering...')
self.db_service.delete('registration', ' 1==1 ')
self.logger.debug('[Registration] Ahenk is unregistered')
2016-03-07 12:55:14 +02:00
def re_register(self):
self.logger.debug('[Registration] Reregistrating...')
2016-03-07 12:55:14 +02:00
self.unregister()
self.register(False)
def generate_uuid(self, depend_mac=True):
if depend_mac is False:
self.logger.debug('[Registration] uuid creating randomly')
return uuid.uuid4() # make a random UUID
else:
self.logger.debug('[Registration] uuid creating according to mac address')
return uuid.uuid3(uuid.NAMESPACE_DNS, str(get_mac())) # make a UUID using an MD5 hash of a namespace UUID and a mac address
def generate_password(self):
return uuid.uuid4()
2016-05-16 17:28:58 +03:00
"""
2016-04-13 15:24:15 +03:00
def get_ip_address(self):
f = os.popen('ifconfig eth0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1')
return f.read()
2016-05-16 17:28:58 +03:00
2016-04-13 15:24:15 +03:00
#TODO disabled because of netifaces dependency
def get_ipAddresses(self):
self.logger.debug('[Registration] looking for network interfaces')
ip_address = ""
for interface in netifaces.interfaces():
if (str(interface) != "lo"):
ip_address += str(netifaces.ifaddresses(interface)[netifaces.AF_INET])
self.logger.debug('[Registration] returning ip addresses from every interfaces')
return ip_address
2016-04-13 15:24:15 +03:00
"""