Commit 56bbc183 by Bach Dániel

refactor agent

parent e72cd95e
...@@ -6,13 +6,18 @@ from twisted.internet.task import LoopingCall ...@@ -6,13 +6,18 @@ from twisted.internet.task import LoopingCall
from twisted.internet.serialport import SerialPort from twisted.internet.serialport import SerialPort
import uptime import uptime
import logging
import subprocess import subprocess
import fileinput import fileinput
import platform import platform
from shutil import rmtree
# from os import path
from datetime import datetime from datetime import datetime
from utils import SerialLineReceiverBase from utils import SerialLineReceiverBase
logger = logging.getLogger()
fstab_template = ('sshfs#%(username)s@%(host)s:home /home/cloud/sshfs ' fstab_template = ('sshfs#%(username)s@%(host)s:home /home/cloud/sshfs '
'fuse defaults,idmap=user,reconnect,_netdev,uid=1000,' 'fuse defaults,idmap=user,reconnect,_netdev,uid=1000,'
'gid=1000,allow_other,StrictHostKeyChecking=no,' 'gid=1000,allow_other,StrictHostKeyChecking=no,'
...@@ -51,16 +56,16 @@ def linux_set_time(time): ...@@ -51,16 +56,16 @@ def linux_set_time(time):
class Context(object): class Context(object):
@staticmethod @staticmethod
def change_password(new_password): def change_password(password):
if system == 'Linux': if system == 'Linux':
proc = subprocess.Popen(['/usr/sbin/chpasswd'], proc = subprocess.Popen(['/usr/sbin/chpasswd'],
stdin=subprocess.PIPE) stdin=subprocess.PIPE)
proc.communicate('cloud:%s\n' % new_password) proc.communicate('cloud:%s\n' % password)
elif system == 'Windows': elif system == 'Windows':
from win32com import adsi from win32com import adsi
ads_obj = adsi.ADsGetObject('WinNT://localhost/%s,user' % 'cloud') ads_obj = adsi.ADsGetObject('WinNT://localhost/%s,user' % 'cloud')
ads_obj.Getinfo() ads_obj.Getinfo()
ads_obj.SetPassword(new_password) ads_obj.SetPassword(password)
@staticmethod @staticmethod
def restart_networking(): def restart_networking():
...@@ -86,41 +91,41 @@ class Context(object): ...@@ -86,41 +91,41 @@ class Context(object):
assert nic.EnableDHCP()[0] == 0 assert nic.EnableDHCP()[0] == 0
@staticmethod @staticmethod
def set_time(new_time): def set_time(time):
if system == 'Linux': if system == 'Linux':
linux_set_time(float(new_time)) linux_set_time(float(time))
try: try:
subprocess.call(['/etc/init.d/ntp', 'restart']) subprocess.call(['/etc/init.d/ntp', 'restart'])
except: except:
pass pass
elif system == 'Windows': elif system == 'Windows':
import win32api import win32api
t = datetime.utcfromtimestamp(float(new_time)) t = datetime.utcfromtimestamp(float(time))
win32api.SetSystemTime(t.year, t.month, 0, t.day, t.hour, win32api.SetSystemTime(t.year, t.month, 0, t.day, t.hour,
t.minute, t.second, 0) t.minute, t.second, 0)
@staticmethod @staticmethod
def set_hostname(new_hostname): def set_hostname(hostname):
if system == 'Linux': if system == 'Linux':
if distro == 'debian': if distro == 'debian':
with open('/etc/hostname', 'w') as f: with open('/etc/hostname', 'w') as f:
f.write(new_hostname) f.write(hostname)
elif distro == 'rhel': elif distro == 'rhel':
for line in fileinput.input('/etc/sysconfig/network', for line in fileinput.input('/etc/sysconfig/network',
inplace=1): inplace=1):
if line.startswith('HOSTNAME='): if line.startswith('HOSTNAME='):
print 'HOSTNAME=%s' % new_hostname print 'HOSTNAME=%s' % hostname
else: else:
print line.rstrip() print line.rstrip()
with open('/etc/hosts', 'w') as f: with open('/etc/hosts', 'w') as f:
f.write('127.0.0.1 localhost' f.write('127.0.0.1 localhost'
'127.0.1.1 %s\n' % new_hostname) '127.0.1.1 %s\n' % hostname)
subprocess.call(['/bin/hostname', new_hostname]) subprocess.call(['/bin/hostname', hostname])
elif system == 'Windows': elif system == 'Windows':
import wmi import wmi
wmi.WMI().Win32_ComputerSystem()[0].Rename(new_hostname) wmi.WMI().Win32_ComputerSystem()[0].Rename(hostname)
@staticmethod @staticmethod
def mount_store(host, username, password, key): def mount_store(host, username, password, key):
...@@ -224,44 +229,23 @@ class SerialLineReceiver(SerialLineReceiverBase): ...@@ -224,44 +229,23 @@ class SerialLineReceiver(SerialLineReceiverBase):
self.send_response(response='status', self.send_response(response='status',
args=args) args=args)
def send_ipaddresses(self):
import netifaces
args = {}
interfaces = netifaces.interfaces()
for i in interfaces:
if i == 'lo':
continue
args[i] = []
addresses = netifaces.ifaddresses(i)
args[i] = ([x['addr']
for x in addresses.get(netifaces.AF_INET, [])] +
[x['addr']
for x in addresses.get(netifaces.AF_INET6, [])
if '%' not in x['addr']])
self.send_response(response='ipaddresses',
args=args)
def handle_command(self, command, args): def handle_command(self, command, args):
if command == 'ping': if not isinstance(command, basestring) or command.startswith('_'):
self.send_response(response='pong', raise Exception(u'Invalid command: %s' % command)
args=args)
elif command == 'status': for k, v in args.iteritems():
self.send_status() if not (isinstance(v, int) or isinstance(v, float) or
elif command == 'get_ipaddresses': isinstance(v, basestring)):
self.send_ipaddresses() raise Exception(u'Invalid argument: %s' % k)
elif command == 'change_password':
Context.change_password(str(args['password'])) try:
elif command == 'restart_networking': func = getattr(Context, command)
Context.restart_networking() retval = func(**args)
elif command == 'set_time': except (AttributeError, TypeError) as e:
Context.set_time(str(args['time'])) raise Exception(u'Command not found: %s (%s)' % (command, e))
elif command == 'set_hostname': else:
Context.set_hostname(str(args['hostname'])) if retval:
elif command == 'mount_store': self.send_response(response=func.__name__, args=retval)
Context.mount_store(str(args['host']),
str(args['username']),
str(args['password']),
str(args['key']))
def handle_response(self, response, args): def handle_response(self, response, args):
pass pass
......
...@@ -38,7 +38,10 @@ class SerialLineReceiverBase(LineReceiver, object): ...@@ -38,7 +38,10 @@ class SerialLineReceiverBase(LineReceiver, object):
if command is not None and isinstance(command, unicode): if command is not None and isinstance(command, unicode):
logging.debug('received command: %s (%s)' % (command, args)) logging.debug('received command: %s (%s)' % (command, args))
try:
self.handle_command(command, args) self.handle_command(command, args)
except Exception as e:
logging.error(u'Unhandled exception: %s' % e)
elif response is not None and isinstance(response, unicode): elif response is not None and isinstance(response, unicode):
logging.debug('received reply: %s (%s)' % (response, args)) logging.debug('received reply: %s (%s)' % (response, args))
self.handle_response(response, args) self.handle_response(response, args)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment