From cc8a26960a670ce8795d9575c5fc6417c40e3eb1 Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Mon, 18 Jul 2016 14:41:10 +0200 Subject: [PATCH 01/32] PHP rewrite, first release --- da_integrare.spec | 97 +++++ defaults/access | 1 - doraemon.ini | 16 - doraemon.logrotate | 6 - doraemon.py | 234 ----------- doraemon/EsmithDatabase.php | 391 ++++++++++++++++++ doraemon/index.php | 254 ++++++++++++ initrd | 79 ---- .../defaults/doraemon/DefaultRole | 1 + .../defaults/doraemon/DomainFile | 1 + .../defaults/doraemon/ManagementKeyFile | 1 + .../defaults/doraemon/NamingBase | 1 + .../defaults/doraemon/NamingDigits | 1 + .../configuration/defaults/doraemon}/TCPPort | 0 .../defaults/doraemon/VaultPassFile | 1 + .../db/configuration/defaults/doraemon/access | 1 + .../configuration/defaults/doraemon}/status | 0 .../db/configuration/defaults/doraemon}/type | 0 .../doraemon/httpd.conf/00template_defaults | 10 + .../etc/httpd/doraemon/httpd.conf/20Manager | 127 ++++++ .../httpd/doraemon/httpd.conf/40DefaultAccess | 16 + .../doraemon/httpd.conf/60DoraemonInterface | 23 ++ .../etc/httpd/doraemon/httpd.conf/90include | 1 + root/etc/httpd/doraemon/.gitignore | 0 root/etc/logrotate.d/doraemon | 9 + root/etc/sysconfig/doraemon | 8 + .../systemd/system/doraemon-reload.service | 9 + .../lib/systemd/system/doraemon-reload.timer | 9 + root/usr/lib/systemd/system/doraemon.service | 14 + root/usr/sbin/doraemon | 1 + 30 files changed, 976 insertions(+), 336 deletions(-) create mode 100644 da_integrare.spec delete mode 100644 defaults/access delete mode 100644 doraemon.ini delete mode 100644 doraemon.logrotate delete mode 100644 doraemon.py create mode 100644 doraemon/EsmithDatabase.php create mode 100644 doraemon/index.php delete mode 100644 initrd create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/DefaultRole create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/DomainFile create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/ManagementKeyFile create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/NamingBase create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/NamingDigits rename {defaults => root/etc/e-smith/db/configuration/defaults/doraemon}/TCPPort (100%) create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/VaultPassFile create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/access rename {defaults => root/etc/e-smith/db/configuration/defaults/doraemon}/status (100%) rename {defaults => root/etc/e-smith/db/configuration/defaults/doraemon}/type (100%) create mode 100644 root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/00template_defaults create mode 100644 root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/20Manager create mode 100644 root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/40DefaultAccess create mode 100644 root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/60DoraemonInterface create mode 100644 root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/90include create mode 100644 root/etc/httpd/doraemon/.gitignore create mode 100644 root/etc/logrotate.d/doraemon create mode 100644 root/etc/sysconfig/doraemon create mode 100644 root/usr/lib/systemd/system/doraemon-reload.service create mode 100644 root/usr/lib/systemd/system/doraemon-reload.timer create mode 100644 root/usr/lib/systemd/system/doraemon.service create mode 120000 root/usr/sbin/doraemon diff --git a/da_integrare.spec b/da_integrare.spec new file mode 100644 index 0000000..0742cb1 --- /dev/null +++ b/da_integrare.spec @@ -0,0 +1,97 @@ +Summary: apache/mod_php stack for Doraemon +Name: doraemon +Version: 1.3.0.1 +Release: 1%{?dist} +License: GPL +URL: %{url_prefix}/%{name} +BuildArch: noarch + +Source0: %{name}-%{version}.tar.gz + + +BuildRequires: nethserver-devtools + +BuildRequires: systemd +Requires(post): systemd +Requires(preun): systemd +Requires(postun): systemd + +Requires: httpd, php, sudo, php-xml, php-mcrypt, nethserver-httpd-admin +Requires: nethserver-base, nethserver-php +Requires: nethserver-lang-en + +%description +Runs an Apache instance on port 3000 that serves +the doraemon web application + +%prep +%setup + + +# Nethgui: +cd %{_builddir}/nethgui-%{nethgui_commit} + +%build +perl createlinks +mkdir -p root/%{_nseventsdir}/%{name}-update + +%install +(cd root ; find . -depth -print | cpio -dump %{buildroot}) +rm -f %{name}-%{version}-%{release}-filelist +%{genfilelist} %{buildroot} \ + > %{name}-%{version}-%{release}-filelist +mkdir -p %{buildroot}/%{_localstatedir}/log/doraemon +mkdir -p %{buildroot}/%{_localstatedir}/cache/doraemon + +# Copy the server-manager dir +mkdir -p %{buildroot}%{_nsuidir} +cp -av nethserver-manager %{buildroot}%{_nsuidir}/nethserver-manager + +%files -f %{name}-%{version}-%{release}-filelist +%defattr(-,root,root) +%doc %{extradocs} + +%{_nsuidir}/nethserver-manager + + +%dir %{_nseventsdir}/%{name}-update +%dir %{_sysconfdir}/httpd/doraemon.d + +%attr(0750,srvmgr,srvmgr) %dir %{_localstatedir}/cache/doraemon +%attr(0644,root,root) %ghost %{_sysconfdir}/init/doraemon.conf +%attr(0644,root,root) %ghost %{_sysconfdir}/httpd/doraemon/httpd.conf +%attr(0700,root,root) %dir %{_localstatedir}/log/doraemon +%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/access_log +%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/error_log +%config(noreplace) /etc/sysconfig/doraemon + +%post +%systemd_post doraemon.service + +%preun +%systemd_preun doraemon.service + +%postun +%systemd_postun + +%changelog +* Tue Oct 27 2015 Emiliano Vavassori - 1.2.1-2.ns6 +- Packing corrections to rpm to fix upgrading issue + +* Tue Oct 27 2015 Emiliano Vavassori - 1.2.1-1.ns6 +- Packing new minor correction on how packages are extracted from db + +* Mon Sep 11 2015 Emiliano Vavassori - 1.2.0-1.ns6 +- Packing new version with ansible dynamic inventory support, epoptes server role support. + +* Mon Sep 07 2015 Emiliano Vavassori - 1.1.1-1.ns6 +- Packing new version with correct roles. + +* Sun Sep 06 2015 Emiliano Vavassori - 1.1.0-1.ns6 +- Packing new version with new functionalities. + +* Wed Jul 15 2015 Emiliano Vavassori - 1.0.0-2.ns6 +- Added logrotate file. + +* Mon Jul 13 2015 Emiliano Vavassori - 1.0.0-1.ns6 +- Unique binary for both ansiblehelper and mac2hostname. diff --git a/defaults/access b/defaults/access deleted file mode 100644 index 3e18ebf..0000000 --- a/defaults/access +++ /dev/null @@ -1 +0,0 @@ -private diff --git a/doraemon.ini b/doraemon.ini deleted file mode 100644 index a9bbdc8..0000000 --- a/doraemon.ini +++ /dev/null @@ -1,16 +0,0 @@ -[Daemon] -Database = /var/lib/doraemon/doraemon.db -LogFile = /var/log/doraemon.log -PIDFile = /var/run/doraemon.pid -BindAddress = 0.0.0.0 -Port = 3000 - -[NameSettings] -Base = lab -Role = client -Digits = 2 - -[Files] -Domain = /etc/domain.yml -MgmtKey = /home/amgmt/.ssh/id_rsa.pub -VaultPassFile = /home/amgmt/.ansible/vault.txt diff --git a/doraemon.logrotate b/doraemon.logrotate deleted file mode 100644 index 443f997..0000000 --- a/doraemon.logrotate +++ /dev/null @@ -1,6 +0,0 @@ -/var/log/doraemon.log { - daily - rotate 15 - compress - missingok -} diff --git a/doraemon.py b/doraemon.py deleted file mode 100644 index 459c316..0000000 --- a/doraemon.py +++ /dev/null @@ -1,234 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""Helps a client to join domain and maintain itself.""" -__author__ = 'BgLUG' -__email__ = 'info@bglug.it' - -from contextlib import contextmanager, closing -from subprocess import Popen, PIPE -from sqlite3 import connect -from bottle import Bottle, request -from json import dumps -from ConfigParser import ConfigParser -from Crypto.Hash import MD5 -from Crypto.Cipher import AES -import base64 -import json -import sys -import re -import os - -class MyApp: - def __init__(self, configfile = '/etc/mac2hostname.ini'): - if not os.path.isfile(configfile): - print "Cannot find main file, %s. Exiting." % configfile - sys.exit(1) - - # Loads configurations - config = ConfigParser() - config.read(configfile) - # Populates private properties with configuration - self.__dbfile = config.get('Daemon', 'Database') if config.has_option('Daemon', 'Database') else '/var/lib/doraemon/doraemon.db' - self.__logdir = config.get('Daemon', 'LogFile') if config.has_option('Daemon', 'LogFile') else '/var/log/doraemon.log' - self.__pidfile = config.get('Daemon', 'PIDFile') if config.has_option('Daemon', 'PIDFile') else '/var/run/doraemon.pid' - self.__bindaddress = config.get('Daemon', 'BindAddress') if config.has_option('Daemon', 'BindAddress') else '127.0.0.1' - self.__port = config.getint('Daemon', 'Port') if config.has_option('Daemon', - 'Port') else 8080 - self.__defaultbase = config.get('NameSettings', 'Base') if config.has_option('NameSettings', 'Base') else 'client' - self.__defaultrole = config.get('NameSettings', 'Role') if config.has_option('NameSettings', 'Role') else 'client' - self.__namedigits = config.get('NameSettings', 'Digits') if config.has_option('NameSettings', 'Digits') else '2' - self.__domainfile = config.get('Files', 'Domain') if config.has_option('Files', 'Domain') else None - self.__mgmtfile = config.get('Files', 'MgmtKey') if config.has_option('Files', 'MgmtKey') else None - self.__vaultpassfile = config.get('Files', 'VaultPassFile') if config.has_option('Files', 'VaultPassFile') else None - self.__app = Bottle() - # Applies routes - self.__route() - # Assures table creation - self.__init_tables() - - @contextmanager - def __getcursor(self): - with connect(self.__dbfile) as connection: - with closing(connection.cursor()) as cursor: - yield cursor - - # Private methods - def __route(self): - self.__app.get('/mac2hostname', callback=self.mac2hostname) - self.__app.get('/whatsmyhostname', callback=self.whatsmyhostname) - self.__app.get('/hosts', callback=self.hosts) - self.__app.get('/domain', callback=self.domain) - self.__app.get('/mgmtkey', callback=self.mgmtkey) - self.__app.get('/vaultpass', callback=self.vaultpass) - self.__app.get('/ansible_list', callback=self.ansible_list) - self.__app.get('/ansible_host', callback=self.ansible_host) - self.__app.get('/epoptes-srv', callback=self.epoptes_srv) - - def __init_tables(self): - with self.__getcursor() as cursor: - cursor.execute('CREATE TABLE IF NOT EXISTS client (id INT PRIMARY KEY,' - 'hostname TEXT NOT NULL UNIQUE, mac TEXT UNIQUE, role TEXT)') - cursor.execute('CREATE INDEX IF NOT EXISTS idxmac ON client(mac)') - - def __getmac(self, ip): - Popen(['ping', '-c1', '-t2', ip], stdout=PIPE).communicate() - arp = Popen(['arp', '-n', ip], stdout=PIPE).communicate()[0] - return re.search(r'(([\da-fA-F]{1,2}\:){5}[\da-fA-F]{1,2})', arp).group(1).lower() - - def __normalizemac(self, mac): - return ':'.join(x.zfill(2) for x in mac.split('_')).lower() - - def __gethostname(self, mac, base = None, role = None): - if base == None: - base = self.__defaultbase - if role == None: - role = self.__defaultrole - - with self.__getcursor() as cursor: - (newid,) = cursor.execute('SELECT COALESCE(MAX(id) + 1, 1) FROM client').fetchone() - # Constucts the hostname format - formatstring = '%s-%0' + self.__namedigits + 'd' - data = (newid, formatstring % (base, newid), mac, role) - # Since MAC is Unique, this fails with the same MAC address - cursor.execute('INSERT OR IGNORE INTO client VALUES (?, ?, ?, ?)', data) - (hostname,) = cursor.execute('SELECT hostname FROM client WHERE mac = "%s"' % mac).fetchone() - return hostname - - # This should be used only after registration of the client - # (whatsmyhostname) - def __getrole(self): - macaddress = self.__normalizemac(self.__getmac(request['REMOTE_ADDR'])) - hostname = self.__gethostname(macaddress) - - with self.__getcursor() as cursor: - (role,) = cursor.execute("SELECT role FROM client WHERE hostname = '%s' AND mac = '%s'" % (hostname, macaddress)).fetchone() - return role - - # Variables returned to the client - def __rolevars(self, role=None): - retval = {'role': role, 'addpkg': [], 'delpkg': []} - try: - db = Popen(['/sbin/e-smith/db', 'roles', 'getjson'], stdout=PIPE).communicate()[0] - for data in json.loads(db): - if data['name'] == role: - retval['addpkg'] = re.split(r'[\s,;]+', data['props']['Addpkg']) - retval['delpkg'] = re.split(r'[\s,;]+', data['props']['Delpkg']) - continue - except: pass - return retval - - # Instance methods AKA routes - def mac2hostname(self): - # Ensure required parameters have been passed - if not request.query.mac: - return "Usage: GET /mac2hostname?mac=XX_XX_XX_XX_XX_XX[&base=YYY][&role=ZZZ]" - # Sets up variables for possible parameters - mac = self.__normalizemac(request.query.mac) - base = request.query.base or self.__defaultbase - role = request.query.role or self.__defaultrole - return self.__gethostname(mac, base, role) - - def whatsmyhostname(self): - # No required parameters - ip = request.query.ip or request['REMOTE_ADDR'] - base = request.query.base or self.__defaultbase - role = request.query.role or self.__defaultrole - return self.__gethostname(self.__getmac(ip), base, role) - - def hosts(self): - # Default where clause: no where specifications - where = '' - # If a role parameter is passed, list the hosts for that role - if request.query.role: - where = "WHERE role = '%s'" % request.query.role - with self.__getcursor() as cursor: - return dumps([dict((meta[0], data) - for meta, data in zip(cursor.description, row)) - for row in cursor.execute('SELECT role, hostname, mac FROM client ' - + where + 'ORDER BY role ASC, hostname ASC')], indent=4) - - def domain(self): - with open(self.__domainfile, 'r') as f: - return f.read() - - def mgmtkey(self): - with open(self.__mgmtfile, 'r') as f: - return f.read() - - def vaultpass(self): - with open(self.__vaultpassfile, 'r') as f: - ip = request.query.ip or request['REMOTE_ADDR'] - base = request.query.base or self.__defaultbase - role = request.query.role or self.__defaultrole - hostname = self.__gethostname(self.__getmac(ip), base, role) - # Encryption key - key = MD5.new(hostname).digest() - # Secret - secret = f.read().strip() - # Creating a secret that is multiple of 16 in length - i = 16 - (len(secret) % 16) - lengthy_secret = secret + i * 'x' - cipher = AES.new(key, AES.MODE_ECB) - crypted = cipher.encrypt(lengthy_secret) - # Encode in base64 because of unicode strings - return base64.b64encode(crypted) - - def ansible_list(self): - # Faking calls - if request.query.role: - role = request.query.role - else: - role = self.__getrole() - - result = { - 'localhost': { - 'hosts': [ 'localhost' ], - 'vars': { - 'ansible_connection': 'local' - } - }, - '_meta': { - 'hostvars': { - 'localhost': self.__rolevars(role) - } - } - } - return dumps(result) - - def ansible_host(self): - # Ignoring 'host' parameter, since it should always be 'localhost'. - # Instead, for testing purposes, if asked for a role, use it - if request.query.role: - role = request.query.role - else: - role = self.__getrole() - return dumps(self.__rolevars(role)) - - def epoptes_srv(self): - hostname = None - try: - with self.__getcursor() as cursor: - (hostname,) = cursor.execute('SELECT hostname FROM client WHERE role = \'docenti\' ORDER BY id DESC LIMIT 1').fetchone() - except TypeError: - return 'none' - - return hostname - - def start(self): - # Opens up a PID file - pid = os.getpid() - pidfile = open(self.__pidfile, 'w') - pidfile.write('%s' % pid) - pidfile.close() - - # Runs Bottle, at last. - self.__app.run(host=self.__bindaddress, port=self.__port) - -# Main body -if __name__ == '__main__': - cfgfile = '/etc/doraemon.ini' - if len(sys.argv) > 1: - cfgfile = sys.argv[1] - app = MyApp(cfgfile) - app.start() diff --git a/doraemon/EsmithDatabase.php b/doraemon/EsmithDatabase.php new file mode 100644 index 0000000..e0e0268 --- /dev/null +++ b/doraemon/EsmithDatabase.php @@ -0,0 +1,391 @@ +. + */ + +/** + * Read and write parameters into SME DB + * + * Ths class implements an interface to SME database executing the command /sbin/e-smith/db with sudo. + * The class needs /etc/sudoers configurazione. In the sudoers file you must have something like this: + * + * Cmnd_Alias SME = /sbin/e-smith/db, /sbin/e-smith/signal-event + * www ALL=NOPASSWD: SME + * + * + * + * @author Giacomo Sanchietti + * @author Davide Principi + * @since 1.0 + * @internal + */ +class EsmithDatabase +{ + + /** + * @var SME DB database command + * */ + private $command = "/usr/bin/sudo /sbin/e-smith/db"; + + /** + * @var $db Database name, it's translated into the db file path. For example: /home/e-smith/db/testdb + * */ + private $db; + + /** + * This static class variable shares a socket connection to smwingsd + * + * @var resource + */ + private static $socket; + + + + + /** + * Construct an object to access a SME Configuration database file + * with $user's privileges. + * + * @param string $database Database name + */ + public function __construct($database) + { + if ( ! $database) + sprintf("%s: You must provide a valid database name.", get_class($this)); + + $this->db = $database; + } + + public function getAll($type = NULL) + { + $output = ""; + + $ret = $this->dbRead('getjson', array(), $output); + if ($ret !== 0) { + sprintf("%s: internal database command failed!", __CLASS__); + } + + $data = json_decode($output, TRUE); + if ( ! is_array($data)) { + sprintf("%s: unexpected json string `%s`", __CLASS__, substr($output, 0, 8)); + } + + $result = array(); + + foreach ($data as $item) { + // Apply type check filter: + if (isset($type) && $type !== $item['type']) { + continue; + } + $props = isset($item['props']) ? $item['props'] : array(); + $result[$item['name']] = array_merge($props, array('type' => $item['type'])); + } + + return $result; + } + + public function getAllByProp($propName = NULL, $propValue = NULL) + { + $output = ""; + + $ret = $this->dbRead('getjson', array(), $output); + if ($ret !== 0) { + sprintf("%s: internal database command failed!", __CLASS__); + } + + $data = json_decode($output, TRUE); + if ( ! is_array($data)) { + sprintf("%s: unexpected json string `%s`", __CLASS__, substr($output, 0, 8)); + } + + $result = array(); + + foreach ($data as $item) { + $item['props']['type'] = $item['type']; + $item['props']['name'] = $item['name']; + + if (isset($propName) && isset($propValue)) { + if (isset($item['props'][$propName]) && $propValue == $item['props'][$propName]) { + $result[$item['name']] = $item['props']; + } + } else { + $result[$item['name']] = $item['props']; + } + } + + return $result; + } + + public function getKey($key) + { + $output = ''; + + $ret = $this->dbRead('getjson', array($key), $output); + if ($ret !== 0) { + sprintf("%s: internal database command failed", __CLASS__); + } + + $data = json_decode($output, TRUE); + + if ($data === 1) { + // Key has not been found + return array(); + } elseif ( ! is_array($data)) { + sprintf("%s: unexpected json string `%s`", __CLASS__, substr($output, 0, 8)); + } + + $data['props']['type'] = $data['type']; + $data['props']['name'] = $data['name']; + return $data['props']; + } + + public function getKeyValue($key) + { + $output = ''; + + $ret = $this->dbRead('getjson', array($key), $output); + if ($ret !== 0) { + sprintf("%s: internal database command failed", __CLASS__); + } + + $data = json_decode($output, TRUE); + + if ($data === 1) { + // Key has not been found + return array(); + } elseif ( ! is_array($data)) { + sprintf("%s: unexpected json string `%s`", __CLASS__, substr($output, 0, 8)); + } + + return $data['type']; + } + + public function setKey($key, $type, $props) + { + $output = NULL; + $ret = $this->dbExec('set', $this->prepareArguments($key, $type, $props), $output); + return ($ret == 0); + } + + public function deleteKey($key) + { + $output = NULL; + $output = NULL; + $ret = $this->dbExec('delete', $this->prepareArguments($key), $output); + return ($ret == 0); + } + + /** + * Return the type of a key + * Act like: /sbin/e-smith/db dbfile gettype key + * + * @param string $key the key to retrieve + * @access public + * @return string the type of the key + */ + public function getType($key) + { + $output = NULL; + $ret = $this->dbRead('gettype', array($key), $output); + return trim($output); + } + + /** + * Set the type of a key + * Act like: /sbin/e-smith/db dbfile settype key type + * + * @param string $key the key to change + * @param string $type the new type + * @access public + * @return bool true on success, FALSE otherwise + */ + public function setType($key, $type) + { + $output = NULL; + $ret = $this->dbExec('settype', $this->prepareArguments($key, $type), $output); + return ($ret == 0); + } + + public function getProp($key, $prop) + { + $output = NULL; + $ret = $this->dbRead('getprop', array($key, $prop), $output); + return trim($output); + } + + public function setProp($key, $props) + { + $output = NULL; + $ret = $this->dbExec('setprop', $this->prepareArguments($key, $props), $output); + return ($ret == 0); + } + + public function delProp($key, $props) + { + $output = NULL; + $ret = $this->dbExec('delprop', array_merge(array($key), array_values($props)), $output); + return ($ret == 0); + } + + /** + * Execute the db command + * @param string $command The command to invoke + * @param array $args The command arguments + * @param string &$output The output from the command process + * @return int The command exit code + */ + private function dbExec($command, $args, &$output) + { + // prepend the database name and command + array_unshift($args, $this->db, $command); + $exitCode = 0; + $oArr = array(); + exec($this->command . ' ' . implode(' ', array_map('escapeshellarg', $args)), $oArr, $exitCode); + $output = implode("\n", $oArr); + return $exitCode; + } + + /** + * Read db data from memory cache daemon + * @param string $command The command to invoke + * @param array $args The command arguments + * @param string &$output The output from the read socket + * @return int The command exit code + */ + private function dbRead($command, $args, &$output) + { + if ( ! isset(self::$socket) ) { + $socketPath = '/var/run/smwingsd.sock'; + $errno = 0; + $errstr = ''; + self::$socket = fsockopen('unix://' . $socketPath, -1, $errno, $errstr); + if( ! is_resource(self::$socket)) { + sprintf("Invalid socket (%d): %s. Fall back to exec().", $errno, $errstr); + } + } + + if ( ! is_resource(self::$socket)) { + return $this->dbExec($command, call_user_func_array(array($this, 'prepareArguments'), $args), $output); + } + + // prepend the database name and command + array_unshift($args, $this->db, $command); + + $ret = $this->sendMessage(self::$socket, 0x10, $args); + if ( ! $ret ) { + return 1; + } + $ret = $this->recvMessage(self::$socket); + if ( ! $ret ) { + return 1; + } + if ($command === 'getjson') { + $output = $ret; + } else { + $output = json_decode($ret, TRUE); + } + + return 0; + } + + private function sendMessage($socket, $type, $args = array()) + { + $payload = json_encode($args); + $data = pack('CN', (int) $type, strlen($payload)) . $payload; + $written = fwrite($socket, $data); + if ($written !== strlen($data)) { + echo 'Socket write error'; + } + return TRUE; + } + + private function recvMessage($socket) + { + $buf = $this->safeRead($socket, 5); + if ($buf === FALSE) { + echo 'Socket read error'; + return false; + } + + $header = unpack('Ctype/Nsize', $buf); + if ( ! is_array($header)) { + echo 'Invalid message header'; + return false; + } + + $message = $this->safeRead($socket, $header['size']); + if ($message === FALSE) { + echo 'Socket read error'; + return false; + } + + if ($header['type'] & 0x02) { + return NULL; + } + + return $message; + } + + private function safeRead($socket, $size) + { + $buffer = ""; + $count = 0; + while($count < $size) { + if(feof($socket)) { + return FALSE; + } + $chunk = fread($socket, $size - $count); + $count += strlen($chunk); + if($chunk === FALSE) { + return FALSE; + } + $buffer .= $chunk; + } + return $buffer; + } + + + /** + * Take arbitrary arguments and flattenize to an array + * + * @param mixed $_ + * @return array + */ + private function prepareArguments() + { + $args = array(); + + foreach (func_get_args() as $arg) { + if (is_array($arg)) { + foreach ($arg as $propName => $propValue) { + $args[] = $propName; + $args[] = $propValue; + } + } else { + $args[] = (String) $arg; + } + } + + return $args; + } + + + + +} \ No newline at end of file diff --git a/doraemon/index.php b/doraemon/index.php new file mode 100644 index 0000000..41daa53 --- /dev/null +++ b/doraemon/index.php @@ -0,0 +1,254 @@ +getKey($role); + $return = array('role'=>$role,'Delpkg'=>'','Addpkg'=>''); + if (is_array($result)) { + if (is_string($result['Addpkg'])) $return['Addpkg'] = $result['Addpkg']; + if (is_string($result['Delpkg'])) $return['Delpkg'] = $result['Delpkg']; + } + if ($json) { + return json_encode($return); + } else { + return $return; + } +} + +function getClient($mac=false) { + global $hosts_db; + if (!$mac) { + $mac = getClientMac(); + if (!$mac) return false; + } + $hosts = $hosts_db->getAllByProp('MacAddress',$mac); + if (count($hosts)>0) { + return array_pop($hosts); + } else { + return false; + } +} + +function getClientMac($ip=false) { + if (false === $ip) { + $ip = $_SERVER['REMOTE_ADDR']; + } + $result = pingHost($ip,1); + if (!$result) return false; + $macAddr=false; + $arptable=`arp -n $ip`; + $lines=explode("\n", $arptable); + foreach($lines as $line) { + $cols=preg_split('/\s+/', trim($line)); + if ($cols[0]==$ip) + { + return $cols[2]; + } + } +} + +function pingHost($host, $timeout=1) { + $pingresult = exec("/bin/ping -c 1 -t 2 -W $timeout $host", $output, $retvar); + return (0 == $retvar); +} + + + +function ROUTE_domain() { + global $config_db; + $theFile = $config_db->getProp(CONFIG_KEY,'DomainFile'); + $content = file_get_contents($theFile); + if (false !== $content) { + echo $content; + } +} + +function ROUTE_mgmtkey() { + global $config_db; + $theFile = $config_db->getProp(CONFIG_KEY,'ManagementKeyFile'); + $content = file_get_contents($theFile); + if (false !== $content) { + echo $content; + } +} + +function ROUTE_epoptes_srv() { + global $hosts_db; + $hosts = $hosts_db->getAllByProp('Role','docenti'); + if (count($hosts) == 0) { + echo 'none'; + } else { + $host = array_pop($hosts); + echo json_encode($host); + } +} + +function ROUTE_ansible_host() { + global $get_params; + if (isset($get_params['role'])) { + $role = $get_params['role']; + } elseif ($client = getClient()) { + $role = $client['Role']; + } else { + $role = 'unknown'; + } + echo varsForRole($role); +} + +function ROUTE_hosts() { + global $hosts_db; + global $get_params; + if (isset($get_params['role'])) { + $items = $hosts_db->getAllByProp('Role', $get_params['role']); + } else { + $items = $hosts_db->getAll(); + } + $results=array(); + foreach ($items as $name=>$item) { + $results[]=array( + 'mac'=>$item['MacAddress'], + 'hostname'=>$name, + 'role'=>$item['Role'] + ); + } + echo json_encode($results); +} + + +function ROUTE_ansible_list() { + global $get_params; + if (isset($get_params['role'])) { + $role = $get_params['role']; + } elseif ($client = getClient()) { + $role = $client['Role']; + } else { + $role = 'unknown'; + } + $vars = varsForRole($role, false); + echo json_encode(array( + 'localhost'=>array( + 'hosts'=>array('localhost'), + 'vars'=>array('ansible_connection'=>'local') + ), + '_meta'=> array('hostvars'=>array('localhost'=>$vars)) + )); +} + + +function ROUTE_vaultpass() { + global $config_db; + $theFile = $config_db->getProp(CONFIG_KEY,'VaultPassFile'); + $content = trim(file_get_contents($theFile)); + if (false === $content) { + echo 'no file'; return; + } + if (!$client = getClient()) { + echo 'no client'; return; + } + $key = md5($client['name']); + $padlenght = 16 - (strlen($content) % 16); + $content_padded = str_repeat('x', $padlenght); + $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $content_padded, MCRYPT_MODE_ECB); + echo base64_encode($ciphertext); +} + +function ROUTE_whatsmyhostname() { + global $config_db; + $mac = getClientMac(); + if (!$mac) return false; + $base = $config_db->getProp(CONFIG_KEY,'NamingBase'); + $role = $config_db->getProp(CONFIG_KEY,'DefaultRole'); + echo newHostname($mac, $base, $role); +} + +function ROUTE_mac2hostname() { + global $config_db; + global $get_params; + $mac = getClientMac(); + if (!$mac) { + echo 'Usage: GET /mac2hostname?mac=XX_XX_XX_XX_XX_XX[&base=YYY][&role=ZZZ]'; + return; + } + + if (isset($get_params['role'])) { + $role = $get_params['role']; + } else { + $role = $config_db->getProp(CONFIG_KEY,'DefaultRole'); + } + + if (isset($get_params['base'])) { + $base = $get_params['base']; + } else { + $base = $config_db->getProp(CONFIG_KEY,'NamingBase'); + } + + echo newHostname($mac, $base, $role); +} + +function newHostname($mac, $base, $role) { + global $config_db; + global $hosts_db; + if(!preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $mac)) { + echo "invalid mac address"; + return; + } + + if ($client=getClient($mac)) { + echo $client['name']; + return; + } + + $domainName = $config_db->getKeyValue('DomainName'); + $digits = $config_db->getProp(CONFIG_KEY,'NamingDigits'); + $formatstring = '%s-%0'.$digits.'d'; + $nr=0; + $hostname = ''; + do { + $nr++; + $hostname = sprintf($formatstring, $base, $nr); + if ($domainName != '') { + $hostname .= '.' . $domainname; + } + } while ($hosts_db->getKey($hostname)); + + $hosts_db->setKey($hostname, 'remote', array( + 'MacAddress' => $mac, + 'Role' => $role, + 'Description' => '' + )); + + echo $hostname; +} + diff --git a/initrd b/initrd deleted file mode 100644 index 5453b61..0000000 --- a/initrd +++ /dev/null @@ -1,79 +0,0 @@ -#!/bin/sh - -# chkconfig: 2345 20 80 -# description: Manage assignation of hostnames for clients -# pidfile: /var/run/doraemon.pid -# config: /etc/doraemon.ini - -### BEGIN INIT INFO -# Provides: doraemon -# Required-Start: $remote_fs $syslog -# Required-Stop: $remote_fs $syslog -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: Helps client to join the domain and maintain itself -# Description: Helps client to join the domain and maintain itself -### END INIT INFO - -# Change the next 3 lines to suit where you install your script and what you want to call it -DAEMON=/usr/bin/doraemon.py -DAEMON_NAME=doraemon - -# Add any command line options for your daemon here -DAEMON_OPTS="" - -# This next line determines what user the script runs as. -# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python. -#DAEMON_USER=mac2hostname -#DAEMON_GROUP=mac2hostname - -# The process ID of the script when it runs is stored here: -LOGFILE=/var/log/$DAEMON_NAME.log -PIDFILE=/var/run/$DAEMON_NAME.pid -lockfile=/var/lock/subsys/$DAEMON_NAME - -. /etc/rc.d/init.d/functions -. /etc/sysconfig/network - -[ "$NETWORKING" = "no" ] && exit 0 - -do_start () { - echo -n $"Starting $DAEMON_NAME: " - daemon --pidfile=$PIDFILE "python $DAEMON >>$LOGFILE 2>/dev/null &" - RETVAL=$? - echo - [ $RETVAL -eq 0 ] && touch $lockfile - return $RETVAL -} - -do_stop () { - echo -n $"Stopping $DAEMON_NAME: " - killproc -p $PIDFILE python - RETVAL=$? - echo - [ $RETVAL -eq 0 ] && rm -f $lockfile - return $RETVAL -} - -case "$1" in - - start|stop) - do_${1} - ;; - - restart|reload|force-reload) - do_stop - do_start - ;; - - status) - status -p $PIDFILE python - ;; - - *) - echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}" - exit 1 - ;; - -esac -exit 0 diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/DefaultRole b/root/etc/e-smith/db/configuration/defaults/doraemon/DefaultRole new file mode 100644 index 0000000..b051c6c --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/DefaultRole @@ -0,0 +1 @@ +client diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/DomainFile b/root/etc/e-smith/db/configuration/defaults/doraemon/DomainFile new file mode 100644 index 0000000..e978cbd --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/DomainFile @@ -0,0 +1 @@ +/etc/domain.yml diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/ManagementKeyFile b/root/etc/e-smith/db/configuration/defaults/doraemon/ManagementKeyFile new file mode 100644 index 0000000..a2d5166 --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/ManagementKeyFile @@ -0,0 +1 @@ +/home/amgmt/.ssh/id_rsa.pub diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/NamingBase b/root/etc/e-smith/db/configuration/defaults/doraemon/NamingBase new file mode 100644 index 0000000..10441b4 --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/NamingBase @@ -0,0 +1 @@ +lab diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/NamingDigits b/root/etc/e-smith/db/configuration/defaults/doraemon/NamingDigits new file mode 100644 index 0000000..0cfbf08 --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/NamingDigits @@ -0,0 +1 @@ +2 diff --git a/defaults/TCPPort b/root/etc/e-smith/db/configuration/defaults/doraemon/TCPPort similarity index 100% rename from defaults/TCPPort rename to root/etc/e-smith/db/configuration/defaults/doraemon/TCPPort diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/VaultPassFile b/root/etc/e-smith/db/configuration/defaults/doraemon/VaultPassFile new file mode 100644 index 0000000..65f2cd9 --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/VaultPassFile @@ -0,0 +1 @@ +/home/amgmt/.ansible/vault.txt diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/access b/root/etc/e-smith/db/configuration/defaults/doraemon/access new file mode 100644 index 0000000..a48cf0d --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/access @@ -0,0 +1 @@ +public diff --git a/defaults/status b/root/etc/e-smith/db/configuration/defaults/doraemon/status similarity index 100% rename from defaults/status rename to root/etc/e-smith/db/configuration/defaults/doraemon/status diff --git a/defaults/type b/root/etc/e-smith/db/configuration/defaults/doraemon/type similarity index 100% rename from defaults/type rename to root/etc/e-smith/db/configuration/defaults/doraemon/type diff --git a/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/00template_defaults b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/00template_defaults new file mode 100644 index 0000000..4c1a258 --- /dev/null +++ b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/00template_defaults @@ -0,0 +1,10 @@ +{ + # + # 00template_defaults + # + + $localAccess = ''; + $port = ${'doraemon'}{TCPPort} || "3000"; + + ""; +} \ No newline at end of file diff --git a/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/20Manager b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/20Manager new file mode 100644 index 0000000..b879b6a --- /dev/null +++ b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/20Manager @@ -0,0 +1,127 @@ +{ + + $OUT .= <s %b" common +LogFormat "%{User-agent}i" agent + +CustomLog /var/log/doraemon/access_log common + +KeepAlive On +MaxKeepAliveRequests 100 +KeepAliveTimeout 15 + +MaxClients 150 +MaxRequestsPerChild 100 + +MinSpareServers 1 +MaxSpareServers 5 +StartServers 1 +Timeout 300 + +DefaultIcon /icons/unknown.gif +DirectoryIndex index.htm index.html index.shtml index.cgi +IndexOptions FancyIndexing VersionSort NameWidth=* +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t +AccessFileName .htaccess + +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* +DefaultType text/plain +TypesConfig /etc/mime.types + +AddEncoding x-compress Z +AddEncoding x-gzip gz + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +AddLanguage en .en +AddLanguage fr .fr +AddLanguage de .de +AddLanguage da .da +AddLanguage el .el +AddLanguage it .it + +LanguagePriority en it de fr + +AddType text/html .shtml +AddType application/x-pkcs7-crl .crl + +AddType application/x-x509-ca-cert .crt + +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +AddHandler cgi-script .cgi +AddHandler server-parsed .shtml +AddHandler imap-file map + +HERE +} + diff --git a/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/40DefaultAccess b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/40DefaultAccess new file mode 100644 index 0000000..fe3528e --- /dev/null +++ b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/40DefaultAccess @@ -0,0 +1,16 @@ + +# First, we configure the "default" to be a very restrictive set of +# permissions. + + + Options None + AllowOverride None + order deny,allow + deny from all + allow from none + + + + Allow from all + + diff --git a/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/60DoraemonInterface b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/60DoraemonInterface new file mode 100644 index 0000000..743bbf3 --- /dev/null +++ b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/60DoraemonInterface @@ -0,0 +1,23 @@ + +DocumentRoot /usr/share/doraemon +Alias /icons/ /var/www/icons/ + + + Options +Indexes + Order Deny,Allow + Deny from all + Allow from { $localAccess || 'all' } + AddType application/x-httpd-php .php + Options +FollowSymlinks + RewriteEngine on + RewriteBase / + RewriteRule ^(js/|fonts/|css/|images/|icons/|.+\.php) - [PT,L] + RewriteRule ^favicon.ico$ images/favicon.ico [L] + RewriteRule ^(.*)$ index.php/$1 [L] + php_value session.save_path /var/cache/doraemon + php_flag magic_quotes_gpc off + + + + + diff --git a/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/90include b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/90include new file mode 100644 index 0000000..e7f3cdb --- /dev/null +++ b/root/etc/e-smith/templates/etc/httpd/doraemon/httpd.conf/90include @@ -0,0 +1 @@ +Include conf.d/php.conf diff --git a/root/etc/httpd/doraemon/.gitignore b/root/etc/httpd/doraemon/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/root/etc/logrotate.d/doraemon b/root/etc/logrotate.d/doraemon new file mode 100644 index 0000000..d409c39 --- /dev/null +++ b/root/etc/logrotate.d/doraemon @@ -0,0 +1,9 @@ +/var/log/doraemon/*log { + missingok + notifempty + sharedscripts + delaycompress + postrotate + /sbin/reload doraemon > /dev/null 2>/dev/null || true + endscript +} \ No newline at end of file diff --git a/root/etc/sysconfig/doraemon b/root/etc/sysconfig/doraemon new file mode 100644 index 0000000..007b91f --- /dev/null +++ b/root/etc/sysconfig/doraemon @@ -0,0 +1,8 @@ +# +# This file can be used to set additional environment variables for +# the httpd-admin process, or pass additional options to the +# httpd-admin executable. See httpd-admin.service unit. +# + +LANG=C + diff --git a/root/usr/lib/systemd/system/doraemon-reload.service b/root/usr/lib/systemd/system/doraemon-reload.service new file mode 100644 index 0000000..320c054 --- /dev/null +++ b/root/usr/lib/systemd/system/doraemon-reload.service @@ -0,0 +1,9 @@ +[Unit] +Description=Graceful restart of doraemon service +Documentation=https://github.com/bglug-it/doraemon +Requisite=doraemon.service + +[Service] +Type=oneshot +ExecStart=/usr/sbin/httpd -f /etc/httpd/doraemon/httpd.conf -k graceful + diff --git a/root/usr/lib/systemd/system/doraemon-reload.timer b/root/usr/lib/systemd/system/doraemon-reload.timer new file mode 100644 index 0000000..7531f12 --- /dev/null +++ b/root/usr/lib/systemd/system/doraemon-reload.timer @@ -0,0 +1,9 @@ +[Unit] +Description=Delayed graceful restart of doraemon service +Documentation=https://github.com/bglug-it/doraemon +Conflicts=doraemon-reload.service + +[Timer] +OnActiveSec=5 + + diff --git a/root/usr/lib/systemd/system/doraemon.service b/root/usr/lib/systemd/system/doraemon.service new file mode 100644 index 0000000..d4eeb35 --- /dev/null +++ b/root/usr/lib/systemd/system/doraemon.service @@ -0,0 +1,14 @@ +[Unit] +Description=Doraemon httpd instance +Documentation=https://github.com/bglug-it/doraemon +After=network.target remote-fs.target nss-lookup.target + +[Service] +Type=simple +EnvironmentFile=/etc/sysconfig/doraemon +ExecStart=/usr/sbin/httpd -f /etc/httpd/doraemon/httpd.conf -c 'MaxConnectionsPerChild 12' -DFOREGROUND +ExecReload=/usr/sbin/httpd -f /etc/httpd/doraemon/httpd.conf -k graceful +LimitNOFILE=4096 + +[Install] +WantedBy=multi-user.target diff --git a/root/usr/sbin/doraemon b/root/usr/sbin/doraemon new file mode 120000 index 0000000..558a907 --- /dev/null +++ b/root/usr/sbin/doraemon @@ -0,0 +1 @@ +httpd \ No newline at end of file From b1502803ff336ff7e3fb3cbad1ed335180ffa1b8 Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Fri, 22 Jul 2016 18:38:13 +0200 Subject: [PATCH 02/32] small fixes stupid vault typo e vaultpass permission via sudo added ui only 'remote' hosts sdasfdfsda boh test specfile --- da_integrare.spec | 97 ------------------- doraemon.spec | 79 +++++++-------- .../migrate/migrate_from_doraemon_120 | 33 +++++++ .../events/actions/doraemon-asyncreload | 3 + .../e-smith/events/actions/doraemon-migrate | 56 +++++++++++ .../doraemon-update/services2adjust/doraemon | 1 + .../etc/httpd/doraemon/httpd.conf | 0 .../templates2expand/etc/init/doraemon.conf | 0 .../migration-import/S99doraemon-migrate | 1 + .../templates.metadata/etc/init/doraemon.conf | 3 + .../e-smith/templates/etc/sudoers/50doraemon | 6 ++ root/etc/init/doraemon-reload.conf | 12 +++ root/etc/sysconfig/doraemon | 8 -- .../systemd/system/doraemon-reload.service | 9 -- .../lib/systemd/system/doraemon-reload.timer | 9 -- root/usr/lib/systemd/system/doraemon.service | 14 --- .../usr/share/doraemon}/EsmithDatabase.php | 0 .../usr/share/doraemon}/index.php | 19 ++-- .../en/NethServer_Module_Doraemon.php | 12 +++ .../it/NethServer_Module_Doraemon.php | 12 +++ .../nethesis/NethServer/Module/Doraemon.php | 17 ++++ .../NethServer/Module/Doraemon/Hosts.php | 34 +++++++ .../Module/Doraemon/Hosts/Modify.php | 55 +++++++++++ .../NethServer/Template/Doraemon/Hosts.php | 22 +++++ 24 files changed, 313 insertions(+), 189 deletions(-) delete mode 100644 da_integrare.spec create mode 100644 root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 create mode 100755 root/etc/e-smith/events/actions/doraemon-asyncreload create mode 100755 root/etc/e-smith/events/actions/doraemon-migrate create mode 120000 root/etc/e-smith/events/doraemon-update/services2adjust/doraemon create mode 100644 root/etc/e-smith/events/doraemon-update/templates2expand/etc/httpd/doraemon/httpd.conf create mode 100644 root/etc/e-smith/events/doraemon-update/templates2expand/etc/init/doraemon.conf create mode 120000 root/etc/e-smith/events/migration-import/S99doraemon-migrate create mode 100644 root/etc/e-smith/templates.metadata/etc/init/doraemon.conf create mode 100644 root/etc/e-smith/templates/etc/sudoers/50doraemon create mode 100644 root/etc/init/doraemon-reload.conf delete mode 100644 root/etc/sysconfig/doraemon delete mode 100644 root/usr/lib/systemd/system/doraemon-reload.service delete mode 100644 root/usr/lib/systemd/system/doraemon-reload.timer delete mode 100644 root/usr/lib/systemd/system/doraemon.service rename {doraemon => root/usr/share/doraemon}/EsmithDatabase.php (100%) rename {doraemon => root/usr/share/doraemon}/index.php (92%) create mode 100644 root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php create mode 100644 root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php create mode 100644 root/usr/share/nethesis/NethServer/Module/Doraemon.php create mode 100644 root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php create mode 100644 root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php create mode 100644 root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts.php diff --git a/da_integrare.spec b/da_integrare.spec deleted file mode 100644 index 0742cb1..0000000 --- a/da_integrare.spec +++ /dev/null @@ -1,97 +0,0 @@ -Summary: apache/mod_php stack for Doraemon -Name: doraemon -Version: 1.3.0.1 -Release: 1%{?dist} -License: GPL -URL: %{url_prefix}/%{name} -BuildArch: noarch - -Source0: %{name}-%{version}.tar.gz - - -BuildRequires: nethserver-devtools - -BuildRequires: systemd -Requires(post): systemd -Requires(preun): systemd -Requires(postun): systemd - -Requires: httpd, php, sudo, php-xml, php-mcrypt, nethserver-httpd-admin -Requires: nethserver-base, nethserver-php -Requires: nethserver-lang-en - -%description -Runs an Apache instance on port 3000 that serves -the doraemon web application - -%prep -%setup - - -# Nethgui: -cd %{_builddir}/nethgui-%{nethgui_commit} - -%build -perl createlinks -mkdir -p root/%{_nseventsdir}/%{name}-update - -%install -(cd root ; find . -depth -print | cpio -dump %{buildroot}) -rm -f %{name}-%{version}-%{release}-filelist -%{genfilelist} %{buildroot} \ - > %{name}-%{version}-%{release}-filelist -mkdir -p %{buildroot}/%{_localstatedir}/log/doraemon -mkdir -p %{buildroot}/%{_localstatedir}/cache/doraemon - -# Copy the server-manager dir -mkdir -p %{buildroot}%{_nsuidir} -cp -av nethserver-manager %{buildroot}%{_nsuidir}/nethserver-manager - -%files -f %{name}-%{version}-%{release}-filelist -%defattr(-,root,root) -%doc %{extradocs} - -%{_nsuidir}/nethserver-manager - - -%dir %{_nseventsdir}/%{name}-update -%dir %{_sysconfdir}/httpd/doraemon.d - -%attr(0750,srvmgr,srvmgr) %dir %{_localstatedir}/cache/doraemon -%attr(0644,root,root) %ghost %{_sysconfdir}/init/doraemon.conf -%attr(0644,root,root) %ghost %{_sysconfdir}/httpd/doraemon/httpd.conf -%attr(0700,root,root) %dir %{_localstatedir}/log/doraemon -%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/access_log -%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/error_log -%config(noreplace) /etc/sysconfig/doraemon - -%post -%systemd_post doraemon.service - -%preun -%systemd_preun doraemon.service - -%postun -%systemd_postun - -%changelog -* Tue Oct 27 2015 Emiliano Vavassori - 1.2.1-2.ns6 -- Packing corrections to rpm to fix upgrading issue - -* Tue Oct 27 2015 Emiliano Vavassori - 1.2.1-1.ns6 -- Packing new minor correction on how packages are extracted from db - -* Mon Sep 11 2015 Emiliano Vavassori - 1.2.0-1.ns6 -- Packing new version with ansible dynamic inventory support, epoptes server role support. - -* Mon Sep 07 2015 Emiliano Vavassori - 1.1.1-1.ns6 -- Packing new version with correct roles. - -* Sun Sep 06 2015 Emiliano Vavassori - 1.1.0-1.ns6 -- Packing new version with new functionalities. - -* Wed Jul 15 2015 Emiliano Vavassori - 1.0.0-2.ns6 -- Added logrotate file. - -* Mon Jul 13 2015 Emiliano Vavassori - 1.0.0-1.ns6 -- Unique binary for both ansiblehelper and mac2hostname. diff --git a/doraemon.spec b/doraemon.spec index 9923f8e..88d21dd 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -1,15 +1,16 @@ Summary: Helps client to join domain and maintain itself Name: doraemon -Version: 1.2.1 -Release: 2.ns6 +Version: 1.3.0 +Release: 1.ns6 URL: https://github.com/bglug-it/doraemon/ License: GPLv2+ Group: System Environment/Daemons BuildRoot: %{_tmppath}/%{name}-root -Requires: python python-bottle python-crypto2.6 nethserver-base -Requires(post): chkconfig nethserver-base -Requires(preun): chkconfig initscripts nethserver-base -Source0: doraemon-1.2.1.tar.gz +BuildRequires: nethserver-devtools > 1.0.1 +Requires: httpd, php, sudo, php-xml, php-mcrypt +Requires: nethserver-base, nethserver-php +Requires: upstart +Source0: doraemon-1.3.0.tar.gz BuildArch: noarch %description @@ -21,33 +22,20 @@ Helps client on a domain network to get information for its maintenance. %build %install -rm -rf %{buildroot} -install -d %{buildroot} -install -d -m 755 %{buildroot}%{_sysconfdir} -install -m 644 doraemon.ini %{buildroot}%{_sysconfdir}/%{name}.ini -# Installo il servizio -install -d -m 755 %{buildroot}%{_initrddir} -install -m 755 initrd %{buildroot}%{_initrddir}/%{name} -# Installo lo script vero e proprio -install -d -m 755 %{buildroot}%{_bindir} -install -m 755 doraemon.py %{buildroot}%{_bindir}/%{name}.py -# Cartella del database -install -d %{buildroot}%{_sharedstatedir}/%{name} -# File per il rotate -install -d %{buildroot}%{_sysconfdir}/logrotate.d -install -m 644 doraemon.logrotate %{buildroot}%{_sysconfdir}/logrotate.d/%{name} -# File di Nethserver -install -d %{buildroot}%{_sysconfdir}/e-smith/db/configuration/defaults/%{name} -install -m 644 type %{buildroot}%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/type -install -m 644 status %{buildroot}%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/status -install -m 644 access %{buildroot}%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/access -install -m 644 TCPPort %{buildroot}%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/TCPPort +(cd root ; find . -depth -print | cpio -dump %{buildroot}) +rm -f %{name}-%{version}-%{release}-filelist +%{genfilelist} %{buildroot} > %{name}-%{version}-%{release}-filelist +mkdir -p %{buildroot}%{_localstatedir}/log/doraemon +mkdir -p %{buildroot}%{_localstatedir}/cache/doraemon + +# Copy the webroot dir +# mkdir -p %{buildroot}%{_datarootdir}/%{name} +# cp -av doraemon/* %{buildroot}%{_datadir}/%{name} %post if [ "$1" = 1 ]; then - /sbin/chkconfig --add %{name} - /sbin/service %{name} start >/dev/null 2>&1 - /sbin/e-smith/db configuration set %{name} service status enabled TCPPort 3000 access private + /sbin/start %{name} >/dev/null 2>&1 || : + /sbin/e-smith/db configuration set %{name} service status enabled TCPPort 3000 access private DefaultRole client DomainFile /etc/domain.yml ManagementKeyFile /home/amgmt/.ssh/id_rsa.pub NamingBase lab NamingDigits 2 VaultPassFile /home/amgmt/.ansible/vault.txt /sbin/e-smith/signal-event runlevel-adjust /sbin/e-smith/signal-event firewall-adjust fi @@ -55,8 +43,7 @@ fi %preun if [ "$1" = 0 ]; then /sbin/e-smith/db configuration delete %{name} - /sbin/service %{name} stop >/dev/null 2>&1 - chkconfig --del %{name} + /sbin/stop %{name} >/dev/null 2>&1 || : /sbin/e-smith/signal-event runlevel-adjust /sbin/e-smith/signal-event firewall-adjust fi @@ -64,22 +51,26 @@ fi %clean rm -rf %{buildroot} +%files -f %{name}-%{version}-%{release}-filelist %files %defattr(644,root,root,755) -%doc README.md LICENSE -%config(noreplace) %{_sysconfdir}/%{name}.ini -%attr(755,-,-) %{_initrddir}/%{name} -%attr(755,-,-) %{_bindir}/%{name}.py - -%dir %attr(755,-,-) %{_sharedstatedir}/%{name} -%{_sysconfdir}/logrotate.d/%{name} -%dir %attr(755,-,-) %{_sysconfdir}/e-smith/db/configuration/defaults/%{name} -%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/status -%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/type -%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/access -%{_sysconfdir}/e-smith/db/configuration/defaults/%{name}/TCPPort +# %doc README.md LICENSE.txt +# %attr(755,-,-) %{_initrddir}/%{name} +# %{_sysconfdir}/logrotate.d/%{name} +# %dir %{_sysconfdir}/httpd/doraemon +%attr(0750,srvmgr,srvmgr) %dir %{_localstatedir}/cache/doraemon +# %attr(0644,root,root) %ghost %{_sysconfdir}/init/doraemon.conf +# %attr(0644,root,root) %ghost %{_sysconfdir}/httpd/doraemon/httpd.conf +%attr(0700,root,root) %dir %{_localstatedir}/log/doraemon +%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/access_log +%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/error_log + %changelog +* Mon Jul 18 2016 Paolo Asperti - 1.3.0-1.ns6 +- PHP porting +- Added a basic UI + * Tue Oct 27 2015 Emiliano Vavassori - 1.2.1-2.ns6 - Packing corrections to rpm to fix upgrading issue diff --git a/root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 b/root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 new file mode 100644 index 0000000..05df6ff --- /dev/null +++ b/root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 @@ -0,0 +1,33 @@ +{ + # + # feature2956_ns6 -- Base: refactor Remote Access page + # + # The ValidFrom prop is migrated to AllowAccess + # + + # TODO: gestire la migrazione dal doraemon precedente (sqlite + doraemon.ini -> e-smith) + + use esmith::ConfigDB; + use esmith::util; + + my $cdb = esmith::ConfigDB->open(); + + my $validFrom = $cdb->get_prop_and_delete('httpd-admin', 'ValidFrom') || ''; + + # 1) Ignore ValidFrom if AllowHosts is already set + if($cdb->get_prop('httpd-admin', 'AllowHosts')) { + return ""; + } + + # 2) Sanitize and import validFrom value if access is private + if($cdb->get_prop('httpd-admin', 'access') eq 'private') { + my $newValue = join(',', map { + my ($ipaddr, $netmask) = (split(/\//, $_)); + $_ eq '0.0.0.0/0.0.0.0' ? () : esmith::util::computeLocalNetworkShortSpec($ipaddr, $netmask); + } split(/,/, $validFrom)); + $cdb->set_prop('httpd-admin', 'AllowHosts', $newValue); + } + + + ""; +} diff --git a/root/etc/e-smith/events/actions/doraemon-asyncreload b/root/etc/e-smith/events/actions/doraemon-asyncreload new file mode 100755 index 0000000..ae656e5 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-asyncreload @@ -0,0 +1,3 @@ +#!/bin/bash + +exec /sbin/start doraemon-reload diff --git a/root/etc/e-smith/events/actions/doraemon-migrate b/root/etc/e-smith/events/actions/doraemon-migrate new file mode 100755 index 0000000..f4b9ca2 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-migrate @@ -0,0 +1,56 @@ +#!/usr/bin/perl + +# +# Copyright (C) 2013 Nethesis S.r.l. +# http://www.nethesis.it - support@nethesis.it +# +# This script is part of NethServer. +# +# NethServer is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, +# or any later version. +# +# NethServer is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with NethServer. If not, see . +# + +# TODO: manage migration + +use esmith::DB::db; +use esmith::event; +use strict; + +my $event = shift; +my $sourceDir = shift; +my $esmithDbDir = '/home/e-smith/db'; +my $errors = 0; +if( ! -d $sourceDir) { + die("Could not find dir $sourceDir"); +} + +my $srcConfigDb = esmith::DB::db->open_ro(join('', $sourceDir, $esmithDbDir, '/configuration')) || die("Could not open source configuration database in $sourceDir \n"); + +my $dstConfigDb = esmith::DB::db->open('configuration') || die("Could not open destination account db\n"); + + +my $service = 'httpd-admin'; +my $old = $srcConfigDb->get($service); +my $new = $dstConfigDb->get($service) || $dstConfigDb->new_record($service); +$new->set_prop('ValidFrom', $old->prop('ValidFrom') || ''); +$old = $srcConfigDb->get('modSSL'); +$new->set_prop('SSLCipherSuite', $old->prop('CipherSuite') || 'ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM'); + +# +# Apply configuration +# +if( ! esmith::event::event_signal('nethserver-httpd-admin-update')) { + exit(1); +} + +exit 0; diff --git a/root/etc/e-smith/events/doraemon-update/services2adjust/doraemon b/root/etc/e-smith/events/doraemon-update/services2adjust/doraemon new file mode 120000 index 0000000..b7dc720 --- /dev/null +++ b/root/etc/e-smith/events/doraemon-update/services2adjust/doraemon @@ -0,0 +1 @@ +restart \ No newline at end of file diff --git a/root/etc/e-smith/events/doraemon-update/templates2expand/etc/httpd/doraemon/httpd.conf b/root/etc/e-smith/events/doraemon-update/templates2expand/etc/httpd/doraemon/httpd.conf new file mode 100644 index 0000000..e69de29 diff --git a/root/etc/e-smith/events/doraemon-update/templates2expand/etc/init/doraemon.conf b/root/etc/e-smith/events/doraemon-update/templates2expand/etc/init/doraemon.conf new file mode 100644 index 0000000..e69de29 diff --git a/root/etc/e-smith/events/migration-import/S99doraemon-migrate b/root/etc/e-smith/events/migration-import/S99doraemon-migrate new file mode 120000 index 0000000..c6ee670 --- /dev/null +++ b/root/etc/e-smith/events/migration-import/S99doraemon-migrate @@ -0,0 +1 @@ +../actions/doraemon-migrate \ No newline at end of file diff --git a/root/etc/e-smith/templates.metadata/etc/init/doraemon.conf b/root/etc/e-smith/templates.metadata/etc/init/doraemon.conf new file mode 100644 index 0000000..5e5de6f --- /dev/null +++ b/root/etc/e-smith/templates.metadata/etc/init/doraemon.conf @@ -0,0 +1,3 @@ +TEMPLATE_PATH='upstart-job' +OUTPUT_FILENAME='/etc/init/doraemon.conf' +MORE_DATA={ name => 'doraemon', description => 'Apache instance that runs the doraemon service', author => 'Paolo Asperti ', daemon_bin => '/usr/sbin/doraemon', daemon_args => '-f /etc/httpd/doraemon/httpd.conf', respawn => 1, 'expect' => 'fork', stop_on => 'stopping network', start_on => 'started network' } diff --git a/root/etc/e-smith/templates/etc/sudoers/50doraemon b/root/etc/e-smith/templates/etc/sudoers/50doraemon new file mode 100644 index 0000000..b456169 --- /dev/null +++ b/root/etc/e-smith/templates/etc/sudoers/50doraemon @@ -0,0 +1,6 @@ +# +# 50doraemon +# +srvmgr ALL=NOPASSWD: /bin/cat /home/amgmt/.ansible/vault.txt + + diff --git a/root/etc/init/doraemon-reload.conf b/root/etc/init/doraemon-reload.conf new file mode 100644 index 0000000..be8a4b0 --- /dev/null +++ b/root/etc/init/doraemon-reload.conf @@ -0,0 +1,12 @@ +# +# doraemon-reload task +# +# Signals an Apache graceful restart for doraemon instance +# + +# service job, runs asynchronously + +script + sleep 5 + exec /usr/sbin/doraemon -f /etc/httpd/doraemon/httpd.conf -k graceful +end script diff --git a/root/etc/sysconfig/doraemon b/root/etc/sysconfig/doraemon deleted file mode 100644 index 007b91f..0000000 --- a/root/etc/sysconfig/doraemon +++ /dev/null @@ -1,8 +0,0 @@ -# -# This file can be used to set additional environment variables for -# the httpd-admin process, or pass additional options to the -# httpd-admin executable. See httpd-admin.service unit. -# - -LANG=C - diff --git a/root/usr/lib/systemd/system/doraemon-reload.service b/root/usr/lib/systemd/system/doraemon-reload.service deleted file mode 100644 index 320c054..0000000 --- a/root/usr/lib/systemd/system/doraemon-reload.service +++ /dev/null @@ -1,9 +0,0 @@ -[Unit] -Description=Graceful restart of doraemon service -Documentation=https://github.com/bglug-it/doraemon -Requisite=doraemon.service - -[Service] -Type=oneshot -ExecStart=/usr/sbin/httpd -f /etc/httpd/doraemon/httpd.conf -k graceful - diff --git a/root/usr/lib/systemd/system/doraemon-reload.timer b/root/usr/lib/systemd/system/doraemon-reload.timer deleted file mode 100644 index 7531f12..0000000 --- a/root/usr/lib/systemd/system/doraemon-reload.timer +++ /dev/null @@ -1,9 +0,0 @@ -[Unit] -Description=Delayed graceful restart of doraemon service -Documentation=https://github.com/bglug-it/doraemon -Conflicts=doraemon-reload.service - -[Timer] -OnActiveSec=5 - - diff --git a/root/usr/lib/systemd/system/doraemon.service b/root/usr/lib/systemd/system/doraemon.service deleted file mode 100644 index d4eeb35..0000000 --- a/root/usr/lib/systemd/system/doraemon.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -Description=Doraemon httpd instance -Documentation=https://github.com/bglug-it/doraemon -After=network.target remote-fs.target nss-lookup.target - -[Service] -Type=simple -EnvironmentFile=/etc/sysconfig/doraemon -ExecStart=/usr/sbin/httpd -f /etc/httpd/doraemon/httpd.conf -c 'MaxConnectionsPerChild 12' -DFOREGROUND -ExecReload=/usr/sbin/httpd -f /etc/httpd/doraemon/httpd.conf -k graceful -LimitNOFILE=4096 - -[Install] -WantedBy=multi-user.target diff --git a/doraemon/EsmithDatabase.php b/root/usr/share/doraemon/EsmithDatabase.php similarity index 100% rename from doraemon/EsmithDatabase.php rename to root/usr/share/doraemon/EsmithDatabase.php diff --git a/doraemon/index.php b/root/usr/share/doraemon/index.php similarity index 92% rename from doraemon/index.php rename to root/usr/share/doraemon/index.php index 41daa53..069d20f 100644 --- a/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -133,7 +133,7 @@ function ROUTE_hosts() { if (isset($get_params['role'])) { $items = $hosts_db->getAllByProp('Role', $get_params['role']); } else { - $items = $hosts_db->getAll(); + $items = $hosts_db->getAll('remote'); } $results=array(); foreach ($items as $name=>$item) { @@ -170,16 +170,18 @@ function ROUTE_ansible_list() { function ROUTE_vaultpass() { global $config_db; $theFile = $config_db->getProp(CONFIG_KEY,'VaultPassFile'); - $content = trim(file_get_contents($theFile)); + $oArr = array(); + exec('/usr/bin/sudo /bin/cat ' . $theFile, $oArr, $exitCode); + $content = trim(implode("\n", $oArr)); if (false === $content) { echo 'no file'; return; } if (!$client = getClient()) { echo 'no client'; return; } - $key = md5($client['name']); + $key = md5($client['name'], true); $padlenght = 16 - (strlen($content) % 16); - $content_padded = str_repeat('x', $padlenght); + $content_padded = $content . str_repeat('x', $padlenght); $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $content_padded, MCRYPT_MODE_ECB); echo base64_encode($ciphertext); } @@ -230,7 +232,7 @@ function newHostname($mac, $base, $role) { return; } - $domainName = $config_db->getKeyValue('DomainName'); + $domainName = (string)$config_db->getKeyValue('DomainName'); $digits = $config_db->getProp(CONFIG_KEY,'NamingDigits'); $formatstring = '%s-%0'.$digits.'d'; $nr=0; @@ -238,9 +240,10 @@ function newHostname($mac, $base, $role) { do { $nr++; $hostname = sprintf($formatstring, $base, $nr); - if ($domainName != '') { - $hostname .= '.' . $domainname; - } +# TODO: we'll use the hostname in future, maybe +# if (trim($domainName) != '') { +# $hostname .= '.' . $domainName; +# } } while ($hosts_db->getKey($hostname)); $hosts_db->setKey($hostname, 'remote', array( diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php new file mode 100644 index 0000000..7fe4d17 --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php @@ -0,0 +1,12 @@ +loadChildrenDirectory(); + } + +} diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php new file mode 100644 index 0000000..6c753fd --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php @@ -0,0 +1,34 @@ +setTableAdapter($this->getPlatform()->getTableAdapter('hosts', 'remote')) + ->setColumns($columns) + // TODO: + // ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('wake')) + // ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('reboot')) + // ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('shutdown')) + ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('update')) + ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('delete')) + ->addTableAction(new \NethServer\Module\Doraemon\Hosts\Modify('create')) + ->addTableAction(new \Nethgui\Controller\Table\Help('Help')) + ; + + parent::initialize(); + } + +} diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php new file mode 100644 index 0000000..740b3eb --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php @@ -0,0 +1,55 @@ +setSchema($parameterSchema); + parent::initialize(); + } + + public function validate(\Nethgui\Controller\ValidationReportInterface $report) + { + if ($this->getIdentifier() === 'delete') { + $v = $this->createValidator()->platform('host-delete'); + if ( ! $v->evaluate($this->parameters['hostname'])) { + $report->addValidationError($this, 'Key', $v); + } + } + parent::validate($report); + } + + protected function onParametersSaved($parameters) + { + $actionName = $this->getIdentifier(); + if ($actionName === 'update') { + $actionName = 'modify'; + } + $this->getPlatform()->signalEvent(sprintf('host-%s &', $actionName)); + } + + public function prepareView(\Nethgui\View\ViewInterface $view) + { + parent::prepareView($view); + $templates = array( + 'create' => 'NethServer\Template\Doraemon\Hosts', + 'update' => 'NethServer\Template\Doraemon\Hosts', + 'delete' => 'Nethgui\Template\Table\Delete', + ); + $view->setTemplate($templates[$this->getIdentifier()]); + } + +} \ No newline at end of file diff --git a/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts.php b/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts.php new file mode 100644 index 0000000..eccb4a9 --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts.php @@ -0,0 +1,22 @@ +getModule()->getIdentifier() == 'update') { + // disable updating of hostname + // the hostname is the key of the db item, if you change it, bad things happens + $keyFlags = $view::STATE_DISABLED; + $template = 'Update_Host_Header'; +} else { + $keyFlags = 0; + $template = 'Create_Host_Header'; +} + +echo $view->header('hostname')->setAttribute('template', $T($template)); + +echo $view->panel() + ->insert($view->textInput('hostname', $keyFlags)) + ->insert($view->textInput('MacAddress')) + ->insert($view->textInput('Role')) +; + +echo $view->buttonList($view::BUTTON_SUBMIT | $view::BUTTON_CANCEL | $view::BUTTON_HELP); From eee2c83d9099f2f3432c9e34e6db77fc62573602 Mon Sep 17 00:00:00 2001 From: paspo Date: Sat, 23 Jul 2016 12:48:58 +0200 Subject: [PATCH 03/32] searching for " negative one" Overnumerousness :) --- root/usr/share/doraemon/index.php | 96 +++++++++++++++---------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index 069d20f..202d574 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -79,9 +79,45 @@ function getClientMac($ip=false) { } } +function newHostname($mac, $base, $role) { + global $config_db; + global $hosts_db; + if(!preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $mac)) { + echo "invalid mac address"; + return; + } + + if ($client=getClient($mac)) { + echo $client['name']; + return; + } + + $domainName = (string)$config_db->getKeyValue('DomainName'); + $digits = $config_db->getProp(CONFIG_KEY,'NamingDigits'); + $formatstring = '%s-%0'.$digits.'d'; + $nr=0; + $hostname = ''; + do { + $nr++; + $hostname = sprintf($formatstring, $base, $nr); +# TODO: we'll use the hostname in future, maybe +# if (trim($domainName) != '') { +# $hostname .= '.' . $domainName; +# } + } while ($hosts_db->getKey($hostname)); + + $hosts_db->setKey($hostname, 'remote', array( + 'MacAddress' => $mac, + 'Role' => $role, + 'Description' => '' + )); + + echo $hostname; +} + function pingHost($host, $timeout=1) { $pingresult = exec("/bin/ping -c 1 -t 2 -W $timeout $host", $output, $retvar); - return (0 == $retvar); + return (0 == $retvar); } @@ -92,7 +128,7 @@ function ROUTE_domain() { $content = file_get_contents($theFile); if (false !== $content) { echo $content; - } + } } function ROUTE_mgmtkey() { @@ -101,7 +137,7 @@ function ROUTE_mgmtkey() { $content = file_get_contents($theFile); if (false !== $content) { echo $content; - } + } } function ROUTE_epoptes_srv() { @@ -146,7 +182,6 @@ function ROUTE_hosts() { echo json_encode($results); } - function ROUTE_ansible_list() { global $get_params; if (isset($get_params['role'])) { @@ -166,7 +201,6 @@ function ROUTE_ansible_list() { )); } - function ROUTE_vaultpass() { global $config_db; $theFile = $config_db->getProp(CONFIG_KEY,'VaultPassFile'); @@ -175,13 +209,13 @@ function ROUTE_vaultpass() { $content = trim(implode("\n", $oArr)); if (false === $content) { echo 'no file'; return; - } + } if (!$client = getClient()) { echo 'no client'; return; } $key = md5($client['name'], true); $padlenght = 16 - (strlen($content) % 16); - $content_padded = $content . str_repeat('x', $padlenght); + $content_padded = $content . str_repeat('x', $padlenght); $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $content_padded, MCRYPT_MODE_ECB); echo base64_encode($ciphertext); } @@ -189,10 +223,13 @@ function ROUTE_vaultpass() { function ROUTE_whatsmyhostname() { global $config_db; $mac = getClientMac(); - if (!$mac) return false; + if (!$mac) { + echo 'no-mac-address'; + return false; + } $base = $config_db->getProp(CONFIG_KEY,'NamingBase'); $role = $config_db->getProp(CONFIG_KEY,'DefaultRole'); - echo newHostname($mac, $base, $role); + newHostname($mac, $base, $role); } function ROUTE_mac2hostname() { @@ -209,49 +246,12 @@ function ROUTE_mac2hostname() { } else { $role = $config_db->getProp(CONFIG_KEY,'DefaultRole'); } - + if (isset($get_params['base'])) { $base = $get_params['base']; } else { $base = $config_db->getProp(CONFIG_KEY,'NamingBase'); } - echo newHostname($mac, $base, $role); + newHostname($mac, $base, $role); } - -function newHostname($mac, $base, $role) { - global $config_db; - global $hosts_db; - if(!preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $mac)) { - echo "invalid mac address"; - return; - } - - if ($client=getClient($mac)) { - echo $client['name']; - return; - } - - $domainName = (string)$config_db->getKeyValue('DomainName'); - $digits = $config_db->getProp(CONFIG_KEY,'NamingDigits'); - $formatstring = '%s-%0'.$digits.'d'; - $nr=0; - $hostname = ''; - do { - $nr++; - $hostname = sprintf($formatstring, $base, $nr); -# TODO: we'll use the hostname in future, maybe -# if (trim($domainName) != '') { -# $hostname .= '.' . $domainName; -# } - } while ($hosts_db->getKey($hostname)); - - $hosts_db->setKey($hostname, 'remote', array( - 'MacAddress' => $mac, - 'Role' => $role, - 'Description' => '' - )); - - echo $hostname; -} - From 91840647e55d3b599b21833ec8cae3af4e3eea92 Mon Sep 17 00:00:00 2001 From: paspo Date: Sat, 23 Jul 2016 14:41:22 +0200 Subject: [PATCH 04/32] fix sudoers --- doraemon.spec | 4 ++-- .../events/doraemon-update/templates2expand/etc/sudoers | 0 2 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 root/etc/e-smith/events/doraemon-update/templates2expand/etc/sudoers diff --git a/doraemon.spec b/doraemon.spec index 88d21dd..f7b4a52 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -34,16 +34,16 @@ mkdir -p %{buildroot}%{_localstatedir}/cache/doraemon %post if [ "$1" = 1 ]; then - /sbin/start %{name} >/dev/null 2>&1 || : /sbin/e-smith/db configuration set %{name} service status enabled TCPPort 3000 access private DefaultRole client DomainFile /etc/domain.yml ManagementKeyFile /home/amgmt/.ssh/id_rsa.pub NamingBase lab NamingDigits 2 VaultPassFile /home/amgmt/.ansible/vault.txt + /sbin/start %{name} >/dev/null 2>&1 || : /sbin/e-smith/signal-event runlevel-adjust /sbin/e-smith/signal-event firewall-adjust fi %preun if [ "$1" = 0 ]; then - /sbin/e-smith/db configuration delete %{name} /sbin/stop %{name} >/dev/null 2>&1 || : + /sbin/e-smith/db configuration delete %{name} /sbin/e-smith/signal-event runlevel-adjust /sbin/e-smith/signal-event firewall-adjust fi diff --git a/root/etc/e-smith/events/doraemon-update/templates2expand/etc/sudoers b/root/etc/e-smith/events/doraemon-update/templates2expand/etc/sudoers new file mode 100644 index 0000000..e69de29 From 3d81fd12e34a9f24a40636cdbab7a3dca3e72b03 Mon Sep 17 00:00:00 2001 From: paspo Date: Sun, 24 Jul 2016 00:27:49 +0200 Subject: [PATCH 05/32] too late for a commit message --- doraemon.spec | 89 +++++++++++++++++-- .../migrate/migrate_from_doraemon_120 | 33 ------- .../events/actions/doraemon-asyncreload | 3 - .../e-smith/events/actions/doraemon-migrate | 56 ------------ .../doraemon-update/services2adjust/doraemon | 1 - .../etc/httpd/doraemon/httpd.conf | 0 .../templates2expand/etc/init/doraemon.conf | 0 .../templates2expand/etc/sudoers | 0 .../migration-import/S99doraemon-migrate | 1 - root/etc/httpd/doraemon/.gitignore | 0 10 files changed, 80 insertions(+), 103 deletions(-) delete mode 100644 root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 delete mode 100755 root/etc/e-smith/events/actions/doraemon-asyncreload delete mode 100755 root/etc/e-smith/events/actions/doraemon-migrate delete mode 120000 root/etc/e-smith/events/doraemon-update/services2adjust/doraemon delete mode 100644 root/etc/e-smith/events/doraemon-update/templates2expand/etc/httpd/doraemon/httpd.conf delete mode 100644 root/etc/e-smith/events/doraemon-update/templates2expand/etc/init/doraemon.conf delete mode 100644 root/etc/e-smith/events/doraemon-update/templates2expand/etc/sudoers delete mode 120000 root/etc/e-smith/events/migration-import/S99doraemon-migrate delete mode 100644 root/etc/httpd/doraemon/.gitignore diff --git a/doraemon.spec b/doraemon.spec index f7b4a52..c030b11 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -28,39 +28,110 @@ rm -f %{name}-%{version}-%{release}-filelist mkdir -p %{buildroot}%{_localstatedir}/log/doraemon mkdir -p %{buildroot}%{_localstatedir}/cache/doraemon -# Copy the webroot dir -# mkdir -p %{buildroot}%{_datarootdir}/%{name} -# cp -av doraemon/* %{buildroot}%{_datadir}/%{name} + +%pre +#if [ "$1" = 1 ]; then +# #installation +#fi +if [ "$1" = 2 ]; then + #upgrade + /sbin/stop %{name} >/dev/null 2>&1 || : + DATABASE=/var/lib/doraemon/doraemon.db + INI=/etc/doraemon.ini + if [ -f $INI ]; then + DATABASE=$(awk -F "=" '/Database/ {print $2}' $INI) + PORT=$(awk -F "=" '/Port/ {print $2}' $INI) + BASE=$(awk -F "=" '/Base/ {print $2}' $INI) + ROLE=$(awk -F "=" '/Role/ {print $2}' $INI) + DIGITS=$(awk -F "=" '/Digits/ {print $2}' $INI) + DOMAIN=$(awk -F "=" '/Domain/ {print $2}' $INI) + MGMTKEY=$(awk -F "=" '/MgmtKey/ {print $2}' $INI) + VAULTPASSFILE=$(awk -F "=" '/VaultPassFile/ {print $2}' $INI) + rm $INI + /sbin/e-smith/db configuration set %{name} service \ + status enabled \ + TCPPort $PORT \ + access private \ + DefaultRole $ROLE \ + DomainFile $DOMAIN \ + ManagementKeyFile $MGMTKEY \ + NamingBase $BASE \ + NamingDigits $DIGITS \ + VaultPassFile $VAULTPASSFILE + else + /sbin/e-smith/db configuration set %{name} service \ + status enabled \ + TCPPort 3000 \ + access private \ + DefaultRole client \ + DomainFile /etc/domain.yml \ + ManagementKeyFile /home/amgmt/.ssh/id_rsa.pub \ + NamingBase lab \ + NamingDigits 2 \ + VaultPassFile /home/amgmt/.ansible/vault.txt + fi + if [ -f $DATABASE ]; then + sqlite3 -separator " " $DATABASE \ + "select * from client" | while read id hostname mac role; do + /sbin/e-smith/db hosts set $hostname remote \ + MacAddress $mac Role $role + done + rm $DATABASE + fi +fi %post if [ "$1" = 1 ]; then + #installation /sbin/e-smith/db configuration set %{name} service status enabled TCPPort 3000 access private DefaultRole client DomainFile /etc/domain.yml ManagementKeyFile /home/amgmt/.ssh/id_rsa.pub NamingBase lab NamingDigits 2 VaultPassFile /home/amgmt/.ansible/vault.txt + /sbin/e-smith/expand-template /etc/sudoers + /sbin/e-smith/expand-template /etc/httpd/doraemon/httpd.conf + /sbin/start %{name} >/dev/null 2>&1 || : + /sbin/e-smith/signal-event runlevel-adjust + /sbin/e-smith/signal-event firewall-adjust +fi +if [ "$1" = 2 ]; then + #upgrade + # TODO: this won't be needed in the next version + /sbin/e-smith/expand-template /etc/sudoers + /sbin/e-smith/expand-template /etc/httpd/doraemon/httpd.conf /sbin/start %{name} >/dev/null 2>&1 || : /sbin/e-smith/signal-event runlevel-adjust /sbin/e-smith/signal-event firewall-adjust fi + %preun +#if [ "$1" = 1 ]; then +# #upgrade +#fi if [ "$1" = 0 ]; then + #uninstallation /sbin/stop %{name} >/dev/null 2>&1 || : +fi + + +%postun +#if [ "$1" = 1 ]; then +# #upgrade +#fi +if [ "$1" = 0 ]; then + #uninstallation /sbin/e-smith/db configuration delete %{name} + /sbin/e-smith/expand-template /etc/sudoers /sbin/e-smith/signal-event runlevel-adjust /sbin/e-smith/signal-event firewall-adjust fi + %clean rm -rf %{buildroot} %files -f %{name}-%{version}-%{release}-filelist %files %defattr(644,root,root,755) -# %doc README.md LICENSE.txt -# %attr(755,-,-) %{_initrddir}/%{name} -# %{_sysconfdir}/logrotate.d/%{name} -# %dir %{_sysconfdir}/httpd/doraemon +%doc README.md LICENSE.txt %attr(0750,srvmgr,srvmgr) %dir %{_localstatedir}/cache/doraemon -# %attr(0644,root,root) %ghost %{_sysconfdir}/init/doraemon.conf -# %attr(0644,root,root) %ghost %{_sysconfdir}/httpd/doraemon/httpd.conf %attr(0700,root,root) %dir %{_localstatedir}/log/doraemon %attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/access_log %attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/error_log diff --git a/root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 b/root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 deleted file mode 100644 index 05df6ff..0000000 --- a/root/etc/e-smith/db/configuration/migrate/migrate_from_doraemon_120 +++ /dev/null @@ -1,33 +0,0 @@ -{ - # - # feature2956_ns6 -- Base: refactor Remote Access page - # - # The ValidFrom prop is migrated to AllowAccess - # - - # TODO: gestire la migrazione dal doraemon precedente (sqlite + doraemon.ini -> e-smith) - - use esmith::ConfigDB; - use esmith::util; - - my $cdb = esmith::ConfigDB->open(); - - my $validFrom = $cdb->get_prop_and_delete('httpd-admin', 'ValidFrom') || ''; - - # 1) Ignore ValidFrom if AllowHosts is already set - if($cdb->get_prop('httpd-admin', 'AllowHosts')) { - return ""; - } - - # 2) Sanitize and import validFrom value if access is private - if($cdb->get_prop('httpd-admin', 'access') eq 'private') { - my $newValue = join(',', map { - my ($ipaddr, $netmask) = (split(/\//, $_)); - $_ eq '0.0.0.0/0.0.0.0' ? () : esmith::util::computeLocalNetworkShortSpec($ipaddr, $netmask); - } split(/,/, $validFrom)); - $cdb->set_prop('httpd-admin', 'AllowHosts', $newValue); - } - - - ""; -} diff --git a/root/etc/e-smith/events/actions/doraemon-asyncreload b/root/etc/e-smith/events/actions/doraemon-asyncreload deleted file mode 100755 index ae656e5..0000000 --- a/root/etc/e-smith/events/actions/doraemon-asyncreload +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -exec /sbin/start doraemon-reload diff --git a/root/etc/e-smith/events/actions/doraemon-migrate b/root/etc/e-smith/events/actions/doraemon-migrate deleted file mode 100755 index f4b9ca2..0000000 --- a/root/etc/e-smith/events/actions/doraemon-migrate +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/perl - -# -# Copyright (C) 2013 Nethesis S.r.l. -# http://www.nethesis.it - support@nethesis.it -# -# This script is part of NethServer. -# -# NethServer is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, -# or any later version. -# -# NethServer is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with NethServer. If not, see . -# - -# TODO: manage migration - -use esmith::DB::db; -use esmith::event; -use strict; - -my $event = shift; -my $sourceDir = shift; -my $esmithDbDir = '/home/e-smith/db'; -my $errors = 0; -if( ! -d $sourceDir) { - die("Could not find dir $sourceDir"); -} - -my $srcConfigDb = esmith::DB::db->open_ro(join('', $sourceDir, $esmithDbDir, '/configuration')) || die("Could not open source configuration database in $sourceDir \n"); - -my $dstConfigDb = esmith::DB::db->open('configuration') || die("Could not open destination account db\n"); - - -my $service = 'httpd-admin'; -my $old = $srcConfigDb->get($service); -my $new = $dstConfigDb->get($service) || $dstConfigDb->new_record($service); -$new->set_prop('ValidFrom', $old->prop('ValidFrom') || ''); -$old = $srcConfigDb->get('modSSL'); -$new->set_prop('SSLCipherSuite', $old->prop('CipherSuite') || 'ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM'); - -# -# Apply configuration -# -if( ! esmith::event::event_signal('nethserver-httpd-admin-update')) { - exit(1); -} - -exit 0; diff --git a/root/etc/e-smith/events/doraemon-update/services2adjust/doraemon b/root/etc/e-smith/events/doraemon-update/services2adjust/doraemon deleted file mode 120000 index b7dc720..0000000 --- a/root/etc/e-smith/events/doraemon-update/services2adjust/doraemon +++ /dev/null @@ -1 +0,0 @@ -restart \ No newline at end of file diff --git a/root/etc/e-smith/events/doraemon-update/templates2expand/etc/httpd/doraemon/httpd.conf b/root/etc/e-smith/events/doraemon-update/templates2expand/etc/httpd/doraemon/httpd.conf deleted file mode 100644 index e69de29..0000000 diff --git a/root/etc/e-smith/events/doraemon-update/templates2expand/etc/init/doraemon.conf b/root/etc/e-smith/events/doraemon-update/templates2expand/etc/init/doraemon.conf deleted file mode 100644 index e69de29..0000000 diff --git a/root/etc/e-smith/events/doraemon-update/templates2expand/etc/sudoers b/root/etc/e-smith/events/doraemon-update/templates2expand/etc/sudoers deleted file mode 100644 index e69de29..0000000 diff --git a/root/etc/e-smith/events/migration-import/S99doraemon-migrate b/root/etc/e-smith/events/migration-import/S99doraemon-migrate deleted file mode 120000 index c6ee670..0000000 --- a/root/etc/e-smith/events/migration-import/S99doraemon-migrate +++ /dev/null @@ -1 +0,0 @@ -../actions/doraemon-migrate \ No newline at end of file diff --git a/root/etc/httpd/doraemon/.gitignore b/root/etc/httpd/doraemon/.gitignore deleted file mode 100644 index e69de29..0000000 From 34457e96923c2cf9de5c9955eb26d452ca1dfcab Mon Sep 17 00:00:00 2001 From: paspo Date: Thu, 28 Jul 2016 01:10:06 +0200 Subject: [PATCH 06/32] host actions --- doraemon.spec | 1 + .../e-smith/events/actions/doraemon-reboot | 34 +++++++++++++ .../e-smith/events/actions/doraemon-shutdown | 34 +++++++++++++ root/etc/e-smith/events/actions/doraemon-wake | 35 ++++++++++++++ .../events/doraemon-reboot/S50doraemon-reboot | 1 + .../doraemon-shutdown/S50doraemon-shutdown | 1 + .../events/doraemon-wake/S50doraemon-wake | 1 + .../en/NethServer_Module_Doraemon.php | 21 ++++---- .../it/NethServer_Module_Doraemon.php | 21 ++++---- .../NethServer/Module/Doraemon/Hosts.php | 7 ++- .../Module/Doraemon/Hosts/Modify.php | 4 +- .../Module/Doraemon/Hosts/TogglePower.php | 48 +++++++++++++++++++ .../Template/Doraemon/Hosts/TogglePower.php | 23 +++++++++ 13 files changed, 207 insertions(+), 24 deletions(-) create mode 100755 root/etc/e-smith/events/actions/doraemon-reboot create mode 100755 root/etc/e-smith/events/actions/doraemon-shutdown create mode 100755 root/etc/e-smith/events/actions/doraemon-wake create mode 120000 root/etc/e-smith/events/doraemon-reboot/S50doraemon-reboot create mode 120000 root/etc/e-smith/events/doraemon-shutdown/S50doraemon-shutdown create mode 120000 root/etc/e-smith/events/doraemon-wake/S50doraemon-wake create mode 100644 root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePower.php create mode 100644 root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePower.php diff --git a/doraemon.spec b/doraemon.spec index c030b11..3650594 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -9,6 +9,7 @@ BuildRoot: %{_tmppath}/%{name}-root BuildRequires: nethserver-devtools > 1.0.1 Requires: httpd, php, sudo, php-xml, php-mcrypt Requires: nethserver-base, nethserver-php +Requires: net-tools Requires: upstart Source0: doraemon-1.3.0.tar.gz BuildArch: noarch diff --git a/root/etc/e-smith/events/actions/doraemon-reboot b/root/etc/e-smith/events/actions/doraemon-reboot new file mode 100755 index 0000000..5f02685 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-reboot @@ -0,0 +1,34 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); + +my $event = $ARGV [0]; + +defined $ARGV[1] || die "No host specied"; +my $host = $ARGV[1]; + +reboot_host($host); + +exit 0; + +sub reboot_host +{ + my ($hostName) = @_; + #------------------------------------------------------------ + # Reboot the host + #------------------------------------------------------------ + + my $h = $db_hosts->get($hostName) or die "No host record for user $hostName"; + + system("/usr/bin/sudo -u amgmt /usr/bin/ssh -o StrictHostKeyChecking=no amgmt\@$hostName /usr/bin/sudo /sbin/reboot") == 0 + or die "Error rebooting $hostName"; + +} diff --git a/root/etc/e-smith/events/actions/doraemon-shutdown b/root/etc/e-smith/events/actions/doraemon-shutdown new file mode 100755 index 0000000..04d61c7 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-shutdown @@ -0,0 +1,34 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); + +my $event = $ARGV [0]; + +defined $ARGV[1] || die "No host specied"; +my $host = $ARGV[1]; + +shutdown_host($host); + +exit 0; + +sub shutdown_host +{ + my ($hostName) = @_; + #------------------------------------------------------------ + # Shutdown the host + #------------------------------------------------------------ + + my $h = $db_hosts->get($hostName) or die "No host record for user $hostName"; + + system("/usr/bin/sudo -u amgmt /usr/bin/ssh -o StrictHostKeyChecking=no amgmt\@$hostName /usr/bin/sudo /sbin/poweroff") == 0 + or die "Error shutting down $hostName"; + +} diff --git a/root/etc/e-smith/events/actions/doraemon-wake b/root/etc/e-smith/events/actions/doraemon-wake new file mode 100755 index 0000000..bb43cb6 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-wake @@ -0,0 +1,35 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); + +my $event = $ARGV [0]; + +defined $ARGV[1] || die "No host specied"; +my $host = $ARGV[1]; + +wake_host($host); + +exit 0; + +sub wake_host +{ + my ($hostName) = @_; + #------------------------------------------------------------ + # Wake up the host + #------------------------------------------------------------ + + my $h = $db_hosts->get($hostName) or die "No host record for user $hostName"; + my $client = $h[0]; + my $mac = $client->prop('MacAddress'); + system("/sbin/ether-wake -i lan0 $mac") == 0 + or die "Error waking up $hostName"; + +} diff --git a/root/etc/e-smith/events/doraemon-reboot/S50doraemon-reboot b/root/etc/e-smith/events/doraemon-reboot/S50doraemon-reboot new file mode 120000 index 0000000..42198ce --- /dev/null +++ b/root/etc/e-smith/events/doraemon-reboot/S50doraemon-reboot @@ -0,0 +1 @@ +../actions/doraemon-reboot \ No newline at end of file diff --git a/root/etc/e-smith/events/doraemon-shutdown/S50doraemon-shutdown b/root/etc/e-smith/events/doraemon-shutdown/S50doraemon-shutdown new file mode 120000 index 0000000..91b5632 --- /dev/null +++ b/root/etc/e-smith/events/doraemon-shutdown/S50doraemon-shutdown @@ -0,0 +1 @@ +../actions/doraemon-shutdown \ No newline at end of file diff --git a/root/etc/e-smith/events/doraemon-wake/S50doraemon-wake b/root/etc/e-smith/events/doraemon-wake/S50doraemon-wake new file mode 120000 index 0000000..c8520f0 --- /dev/null +++ b/root/etc/e-smith/events/doraemon-wake/S50doraemon-wake @@ -0,0 +1 @@ +../actions/doraemon-wake \ No newline at end of file diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php index 7fe4d17..f9b8147 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php @@ -1,12 +1,15 @@ -setTableAdapter($this->getPlatform()->getTableAdapter('hosts', 'remote')) ->setColumns($columns) - // TODO: - // ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('wake')) - // ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('reboot')) - // ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('shutdown')) ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('update')) + ->addRowAction(new \NethServer\Module\Doraemon\Hosts\TogglePower('wake')) + ->addRowAction(new \NethServer\Module\Doraemon\Hosts\TogglePower('reboot')) + ->addRowAction(new \NethServer\Module\Doraemon\Hosts\TogglePower('shutdown')) ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('delete')) ->addTableAction(new \NethServer\Module\Doraemon\Hosts\Modify('create')) ->addTableAction(new \Nethgui\Controller\Table\Help('Help')) diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php index 740b3eb..ab9d3d6 100644 --- a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php @@ -12,7 +12,7 @@ public function initialize() { $parameterSchema = array( // was: Validate::HOSTNAME_FQDN, but we need hostname - array('hostname', Validate::ANYTHING, \Nethgui\Controller\Table\Modify::KEY), + array('hostname', Validate::HOSTNAME_SIMPLE, \Nethgui\Controller\Table\Modify::KEY), array('MacAddress', Validate::MACADDRESS, \Nethgui\Controller\Table\Modify::FIELD), array('Role', Validate::ANYTHING, \Nethgui\Controller\Table\Modify::FIELD), // array('Role', Validate::ROLES_COLLECTION ??? TODO!!!, \Nethgui\Controller\Table\Modify::FIELD), @@ -52,4 +52,4 @@ public function prepareView(\Nethgui\View\ViewInterface $view) $view->setTemplate($templates[$this->getIdentifier()]); } -} \ No newline at end of file +} diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePower.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePower.php new file mode 100644 index 0000000..b9a366b --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePower.php @@ -0,0 +1,48 @@ +declareParameter('hostname', Validate::HOSTNAME_SIMPLE); + + parent::bind($request); + $hostname = \Nethgui\array_end($request->getPath()); + + if ( ! $hostname) { + throw new \Nethgui\Exception\HttpException('Not found', 404, 1322148400); + } + + $this->parameters['hostname'] = $hostname; + } + + public function process() + { + if ( ! $this->getRequest()->isMutation()) { + return; + } + + $this->getPlatform()->signalEvent(sprintf('doraemon-%s@post', $this->getIdentifier()), array($this->parameters['hostname'])); + } + +} diff --git a/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePower.php b/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePower.php new file mode 100644 index 0000000..4e16e40 --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePower.php @@ -0,0 +1,23 @@ +requireFlag($view::INSET_DIALOG); + +if ($view->getModule()->getIdentifier() == 'shutdown') { + $headerText = $T('Shutdown host `${0}`'); + $panelText = $T('Proceed with host `${0}` shutdown?'); +} elseif ($view->getModule()->getIdentifier() == 'reboot') { + $headerText = $T('Reboot host `${0}`'); + $panelText = $T('Proceed with host `${0}` reboot?'); +} else { + $headerText = $T('Wakeup host `${0}`'); + $panelText = $T('Proceed with host `${0}` wakeup?'); +} + +echo $view->panel() + ->insert($view->header('hostname')->setAttribute('template', $headerText)) + ->insert($view->textLabel('hostname')->setAttribute('template', $panelText)) +; + +echo $view->buttonList() + ->insert($view->button('Yes', $view::BUTTON_SUBMIT)) + ->insert($view->button('No', $view::BUTTON_CANCEL)->setAttribute('value', $view['Cancel'])) +; From 52904028d650c91df6e46922174ee53ca97e5018 Mon Sep 17 00:00:00 2001 From: paspo Date: Wed, 14 Sep 2016 09:06:11 +0200 Subject: [PATCH 07/32] translations updated --- .../NethServer/Language/en/NethServer_Module_Doraemon.php | 3 --- .../Language/en/NethServer_Module_Doraemon_Hosts.php | 7 +++++++ .../NethServer/Language/it/NethServer_Module_Doraemon.php | 5 +---- .../Language/it/NethServer_Module_Doraemon_Hosts.php | 7 +++++++ 4 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php create mode 100644 root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php index f9b8147..080d6ff 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php @@ -7,9 +7,6 @@ $L['hostname_label'] = 'Hostname'; $L['Role_label'] = 'Role'; $L['MacAddress_label'] = 'MAC Address'; -$L['Hosts_Title'] = 'Hosts'; -$L['Create_Host_Header'] = 'Create a new host'; -$L['Update_Host_Header'] = 'Update host "${0}"'; $L['shutdown_label'] = 'Shutdown'; $L['reboot_label'] = 'Reboot'; $L['wake_label'] = 'Wake Up'; diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php new file mode 100644 index 0000000..cbf3d30 --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php @@ -0,0 +1,7 @@ + Date: Wed, 14 Sep 2016 09:06:55 +0200 Subject: [PATCH 08/32] room management skeleton --- doraemon.spec | 5 +- .../en/NethServer_Module_Doraemon_Rooms.php | 7 +++ .../it/NethServer_Module_Doraemon_Rooms.php | 7 +++ .../NethServer/Module/Doraemon/Rooms.php | 28 ++++++++++ .../Module/Doraemon/Rooms/Modify.php | 55 +++++++++++++++++++ .../NethServer/Template/Doraemon/Rooms.php | 21 +++++++ 6 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php create mode 100644 root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php create mode 100644 root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms.php create mode 100644 root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php create mode 100644 root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php diff --git a/doraemon.spec b/doraemon.spec index 3650594..2d5dff6 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -1,6 +1,6 @@ Summary: Helps client to join domain and maintain itself Name: doraemon -Version: 1.3.0 +Version: 2.0.0-alpha2 Release: 1.ns6 URL: https://github.com/bglug-it/doraemon/ License: GPLv2+ @@ -11,7 +11,7 @@ Requires: httpd, php, sudo, php-xml, php-mcrypt Requires: nethserver-base, nethserver-php Requires: net-tools Requires: upstart -Source0: doraemon-1.3.0.tar.gz +Source0: doraemon-2.0.0.tar.gz BuildArch: noarch %description @@ -82,6 +82,7 @@ if [ "$1" = 2 ]; then fi %post +/etc/e-smith/events/actions/initialize-default-databases if [ "$1" = 1 ]; then #installation /sbin/e-smith/db configuration set %{name} service status enabled TCPPort 3000 access private DefaultRole client DomainFile /etc/domain.yml ManagementKeyFile /home/amgmt/.ssh/id_rsa.pub NamingBase lab NamingDigits 2 VaultPassFile /home/amgmt/.ansible/vault.txt diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php new file mode 100644 index 0000000..14cf8bc --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php @@ -0,0 +1,7 @@ +setTableAdapter($this->getPlatform()->getTableAdapter('rooms', 'room')) + ->setColumns($columns) + ->addRowAction(new \NethServer\Module\Doraemon\Rooms\Modify('update')) + ->addRowAction(new \NethServer\Module\Doraemon\Rooms\Modify('delete')) + ->addTableAction(new \NethServer\Module\Doraemon\Rooms\Modify('create')) + ->addTableAction(new \Nethgui\Controller\Table\Help('Help')) + ; + + parent::initialize(); + } + +} diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php new file mode 100644 index 0000000..122b7d7 --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php @@ -0,0 +1,55 @@ +setSchema($parameterSchema); + parent::initialize(); + } + + public function validate(\Nethgui\Controller\ValidationReportInterface $report) + { + if ($this->getIdentifier() === 'delete') { + $v = $this->createValidator()->platform('room-delete'); + if ( ! $v->evaluate($this->parameters['name'])) { + $report->addValidationError($this, 'Key', $v); + } + } + parent::validate($report); + } + + protected function onParametersSaved($parameters) + { + $actionName = $this->getIdentifier(); + if ($actionName === 'update') { + $actionName = 'modify'; + } + $this->getPlatform()->signalEvent(sprintf('room-%s &', $actionName)); + } + + public function prepareView(\Nethgui\View\ViewInterface $view) + { + parent::prepareView($view); + $templates = array( + 'create' => 'NethServer\Template\Doraemon\Rooms', + 'update' => 'NethServer\Template\Doraemon\Rooms', + 'delete' => 'Nethgui\Template\Table\Delete', + ); + $view->setTemplate($templates[$this->getIdentifier()]); + } + +} diff --git a/root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php b/root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php new file mode 100644 index 0000000..48ca637 --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php @@ -0,0 +1,21 @@ +getModule()->getIdentifier() == 'update') { + // disable updating of hostname + // the hostname is the key of the db item, if you change it, bad things happens + $keyFlags = $view::STATE_DISABLED; + $template = 'Update_Room_Header'; +} else { + $keyFlags = 0; + $template = 'Create_Room_Header'; +} + +echo $view->header('hostname')->setAttribute('template', $T($template)); + +echo $view->panel() + ->insert($view->textInput('Name')) +// ->insert($view->textInput('Name', $keyFlags)) +; + +echo $view->buttonList($view::BUTTON_SUBMIT | $view::BUTTON_CANCEL | $view::BUTTON_HELP); From 4e1b2c2199e286b4494163992142fc46624cf8f1 Mon Sep 17 00:00:00 2001 From: paspo Date: Wed, 14 Sep 2016 21:37:37 +0200 Subject: [PATCH 09/32] updated specfile --- createlinks.pl | 15 +++++++++++++++ doraemon.spec | 21 +++++++++++---------- 2 files changed, 26 insertions(+), 10 deletions(-) create mode 100644 createlinks.pl diff --git a/createlinks.pl b/createlinks.pl new file mode 100644 index 0000000..66923f1 --- /dev/null +++ b/createlinks.pl @@ -0,0 +1,15 @@ +#!/usr/bin/perl -w + +use esmith::Build::CreateLinks qw(:all); +use File::Basename; +use File::Path; + + +$event = "doraemon-reboot"; +event_actions($event, 'doraemon-reboot' => 50); + +$event = "doraemon-shutdown"; +event_actions($event, 'doraemon-shutdown' => 50); + +$event = "doraemon-wake"; +event_actions($event, 'doraemon-wake' => 50); diff --git a/doraemon.spec b/doraemon.spec index 2d5dff6..1d903d4 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -1,28 +1,33 @@ Summary: Helps client to join domain and maintain itself Name: doraemon -Version: 2.0.0-alpha2 +Version: 2.0.0 Release: 1.ns6 URL: https://github.com/bglug-it/doraemon/ License: GPLv2+ +Packager: Paolo Asperti Group: System Environment/Daemons BuildRoot: %{_tmppath}/%{name}-root BuildRequires: nethserver-devtools > 1.0.1 +BuildRequires: hunspell-en Requires: httpd, php, sudo, php-xml, php-mcrypt Requires: nethserver-base, nethserver-php Requires: net-tools Requires: upstart -Source0: doraemon-2.0.0.tar.gz +Source0: %{name}-%{version}.tar.gz BuildArch: noarch %description Helps client on a domain network to get information for its maintenance. %prep -%setup -q +%setup %build +%{makedocs} +perl createlinks.pl %install +rm -Rf $RPM_BUILD_ROOT (cd root ; find . -depth -print | cpio -dump %{buildroot}) rm -f %{name}-%{version}-%{release}-filelist %{genfilelist} %{buildroot} > %{name}-%{version}-%{release}-filelist @@ -130,19 +135,15 @@ fi rm -rf %{buildroot} %files -f %{name}-%{version}-%{release}-filelist -%files -%defattr(644,root,root,755) +%defattr(0644,root,root,755) %doc README.md LICENSE.txt -%attr(0750,srvmgr,srvmgr) %dir %{_localstatedir}/cache/doraemon -%attr(0700,root,root) %dir %{_localstatedir}/log/doraemon -%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/access_log -%attr(0644,root,root) %config %ghost %{_localstatedir}/log/doraemon/error_log %changelog -* Mon Jul 18 2016 Paolo Asperti - 1.3.0-1.ns6 +* Mon Jul 18 2016 Paolo Asperti - 2.0.0-1 - PHP porting - Added a basic UI +- Added room support * Tue Oct 27 2015 Emiliano Vavassori - 1.2.1-2.ns6 - Packing corrections to rpm to fix upgrading issue From fee905ac7915030a3a983f0034ed51b8b805bfbb Mon Sep 17 00:00:00 2001 From: paspo Date: Wed, 14 Sep 2016 22:06:01 +0200 Subject: [PATCH 10/32] fixed translations --- .../NethServer/Language/en/NethServer_Module_Doraemon.php | 1 - .../NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php | 1 + .../NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php | 1 + .../NethServer/Language/it/NethServer_Module_Doraemon.php | 1 - .../NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php | 1 + .../NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php | 1 + 6 files changed, 4 insertions(+), 2 deletions(-) diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php index 080d6ff..9af5b40 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php @@ -5,7 +5,6 @@ $L['Doraemon_Title'] = 'Doraemon'; $L['Key_label'] = 'Hostname'; $L['hostname_label'] = 'Hostname'; -$L['Role_label'] = 'Role'; $L['MacAddress_label'] = 'MAC Address'; $L['shutdown_label'] = 'Shutdown'; $L['reboot_label'] = 'Reboot'; diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php index cbf3d30..fb935d2 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php @@ -5,3 +5,4 @@ $L['Hosts_Title'] = 'Hosts'; $L['Create_Host_Header'] = 'Create a new host'; $L['Update_Host_Header'] = 'Update host "${0}"'; +$L['Role_label'] = 'Role'; diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php index 14cf8bc..4ff50e0 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php @@ -5,3 +5,4 @@ $L['Rooms_Title'] = 'Rooms'; $L['Create_Room_Header'] = 'Create a new room'; $L['Update_Room_Header'] = 'Update room "${0}"'; +$L['Name_label'] = 'Name'; diff --git a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php index 6f0c5d3..9d23878 100644 --- a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php @@ -5,7 +5,6 @@ $L['Doraemon_Title'] = 'Doraemon'; $L['Key_label'] = 'Hostname'; $L['hostname_label'] = 'Hostname'; -$L['Role_label'] = 'Ruolo'; $L['MacAddress_label'] = 'MAC Address'; $L['shutdown_label'] = 'Spegni'; $L['reboot_label'] = 'Riavvia'; diff --git a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php index da7d979..2609f3e 100644 --- a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php +++ b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php @@ -5,3 +5,4 @@ $L['Hosts_Title'] = 'Hosts'; $L['Create_Host_Header'] = 'Crea un nuovo host'; $L['Update_Host_Header'] = 'Modifica il nome host "${0}"'; +$L['Role_label'] = 'Ruolo'; diff --git a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php index fbbc884..4f63a0c 100644 --- a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php +++ b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php @@ -5,3 +5,4 @@ $L['Rooms_Title'] = 'Stanze'; $L['Create_Room_Header'] = 'Crea una nuova stanza'; $L['Update_Room_Header'] = 'Modifica il nome stanza "${0}"'; +$L['Name_label'] = 'Nome'; From 04097ff49d11329d9be3c326341ab265f0c0d66b Mon Sep 17 00:00:00 2001 From: paspo Date: Wed, 14 Sep 2016 23:35:45 +0200 Subject: [PATCH 11/32] modify table --- doraemon.spec | 2 ++ .../en/NethServer_Module_Doraemon.php | 1 - .../en/NethServer_Module_Doraemon_Hosts.php | 1 + .../en/NethServer_Module_Doraemon_Rooms.php | 1 + .../it/NethServer_Module_Doraemon.php | 1 - .../it/NethServer_Module_Doraemon_Hosts.php | 1 + .../it/NethServer_Module_Doraemon_Rooms.php | 1 + .../Module/Doraemon/Rooms/Modify.php | 36 ++++++++++++++++++- .../NethServer/Template/Doraemon/Rooms.php | 27 +++++++++++--- 9 files changed, 64 insertions(+), 7 deletions(-) diff --git a/doraemon.spec b/doraemon.spec index 1d903d4..bf4793f 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -137,6 +137,8 @@ rm -rf %{buildroot} %files -f %{name}-%{version}-%{release}-filelist %defattr(0644,root,root,755) %doc README.md LICENSE.txt +%attr(0644,srvmgr,srvmgr) %ghost %{_localstatedir}/log/doraemon/access_log +%attr(0644,srvmgr,srvmgr) %ghost %{_localstatedir}/log/doraemon/error_log %changelog diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php index 9af5b40..9c70ab3 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php @@ -3,7 +3,6 @@ /* /usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php */ $L['Doraemon_Title'] = 'Doraemon'; -$L['Key_label'] = 'Hostname'; $L['hostname_label'] = 'Hostname'; $L['MacAddress_label'] = 'MAC Address'; $L['shutdown_label'] = 'Shutdown'; diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php index fb935d2..b5c5108 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Hosts.php @@ -6,3 +6,4 @@ $L['Create_Host_Header'] = 'Create a new host'; $L['Update_Host_Header'] = 'Update host "${0}"'; $L['Role_label'] = 'Role'; +$L['Key_label'] = 'Hostname'; diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php index 4ff50e0..bc616fc 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon_Rooms.php @@ -6,3 +6,4 @@ $L['Create_Room_Header'] = 'Create a new room'; $L['Update_Room_Header'] = 'Update room "${0}"'; $L['Name_label'] = 'Name'; +$L['Key_label'] = 'Room'; diff --git a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php index 9d23878..812bcea 100644 --- a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php @@ -3,7 +3,6 @@ /* /usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php */ $L['Doraemon_Title'] = 'Doraemon'; -$L['Key_label'] = 'Hostname'; $L['hostname_label'] = 'Hostname'; $L['MacAddress_label'] = 'MAC Address'; $L['shutdown_label'] = 'Spegni'; diff --git a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php index 2609f3e..a0ac122 100644 --- a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php +++ b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Hosts.php @@ -6,3 +6,4 @@ $L['Create_Host_Header'] = 'Crea un nuovo host'; $L['Update_Host_Header'] = 'Modifica il nome host "${0}"'; $L['Role_label'] = 'Ruolo'; +$L['Key_label'] = 'Hostname'; diff --git a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php index 4f63a0c..91a6440 100644 --- a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php +++ b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon_Rooms.php @@ -6,3 +6,4 @@ $L['Create_Room_Header'] = 'Crea una nuova stanza'; $L['Update_Room_Header'] = 'Modifica il nome stanza "${0}"'; $L['Name_label'] = 'Nome'; +$L['Key_label'] = 'Stanza'; diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php index 122b7d7..6ee5e48 100644 --- a/root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Rooms/Modify.php @@ -3,6 +3,7 @@ namespace NethServer\Module\Doraemon\Rooms; use Nethgui\System\PlatformInterface as Validate; +use Nethgui\Controller\Table\Modify as Table; class Modify extends \Nethgui\Controller\Table\Modify @@ -12,7 +13,10 @@ public function initialize() { $parameterSchema = array( // was: Validate::HOSTNAME_FQDN, but we need hostname - array('Name', Validate::ANYTHING, \Nethgui\Controller\Table\Modify::KEY), + array('Name', Validate::ANYTHING, Table::KEY), + array('AclRead', Validate::USERNAME_COLLECTION, Table::FIELD, 'AclRead', ','), // ACL + array('AclWrite', Validate::USERNAME_COLLECTION, Table::FIELD, 'AclWrite', ','), // ACL + // array('MacAddress', Validate::MACADDRESS, \Nethgui\Controller\Table\Modify::FIELD), // array('Role', Validate::ANYTHING, \Nethgui\Controller\Table\Modify::FIELD), // array('Role', Validate::ROLES_COLLECTION ??? TODO!!!, \Nethgui\Controller\Table\Modify::FIELD), @@ -21,6 +25,16 @@ public function initialize() parent::initialize(); } + public function bind(\Nethgui\Controller\RequestInterface $request) + { + parent::bind($request); + if($request->isMutation()) { + // save the old values for later usage: + $this->originalAclRead = $this->getPlatform()->getDatabase('accounts')->getProp($this->parameters['ibay'], 'AclRead'); + $this->originalAclWrite = $this->getPlatform()->getDatabase('accounts')->getProp($this->parameters['ibay'], 'AclWrite'); + } + } + public function validate(\Nethgui\Controller\ValidationReportInterface $report) { if ($this->getIdentifier() === 'delete') { @@ -50,6 +64,26 @@ public function prepareView(\Nethgui\View\ViewInterface $view) 'delete' => 'Nethgui\Template\Table\Delete', ); $view->setTemplate($templates[$this->getIdentifier()]); + + + $owners = array(array('locals', $view->translate('locals_group_label'))); + $subjects = array(array('locals', $view->translate('locals_group_label'))); + + foreach ($this->getPlatform()->getDatabase('accounts')->getAll('group') as $keyName => $props) { + $entry = array($keyName, sprintf("%s (%s)", isset($props['Description']) ? $props['Description'] : $keyName, $keyName)); + $owners[] = $entry; + $subjects[] = $entry; + } + + $view['OwningGroupDatasource'] = $owners; + + foreach ($this->getPlatform()->getDatabase('accounts')->getAll('user') as $keyName => $props) { + $entry = array($keyName, sprintf("%s (%s)", trim($props['FirstName'] . ' ' . $props['LastName']), $keyName)); + $subjects[] = $entry; + } + + $view['AclSubjects'] = $subjects; + } } diff --git a/root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php b/root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php index 48ca637..723c7ef 100644 --- a/root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php +++ b/root/usr/share/nethesis/NethServer/Template/Doraemon/Rooms.php @@ -1,5 +1,7 @@ requireFlag($view::INSET_FORM); if ($view->getModule()->getIdentifier() == 'update') { // disable updating of hostname @@ -11,11 +13,28 @@ $template = 'Create_Room_Header'; } -echo $view->header('hostname')->setAttribute('template', $T($template)); +echo $view->header('doraemon')->setAttribute('template', $view->translate($template)); echo $view->panel() - ->insert($view->textInput('Name')) -// ->insert($view->textInput('Name', $keyFlags)) -; + ->insert($view->textInput('ibay', $keyFlags)) + ->insert($view->textInput('Description')) + ->insert($view->selector('OwningGroup', $view::SELECTOR_DROPDOWN)) + ->insert($view->checkBox('GroupAccess', 'rw')->setAttribute('uncheckedValue', 'r')) + ->insert($view->checkBox('OtherAccess', 'r')->setAttribute('uncheckedValue', '')) + ->insert($view->objectPicker() + ->setAttribute('objects', 'AclSubjects') + ->setAttribute('objectLabel', 1) + ->insert($view->checkBox('AclRead', FALSE, $view::STATE_CHECKED)) + ->insert($view->checkBox('AclWrite', FALSE)) +); echo $view->buttonList($view::BUTTON_SUBMIT | $view::BUTTON_CANCEL | $view::BUTTON_HELP); + +$actionId = $view->getUniqueId(); +$view->includeJavascript(" +jQuery(function($){ + $('#${actionId}').on('nethguishow', function () { + $(this).find('.Tabs').tabs('select', 0); + }); +}); +"); From 9b9db0f626c2892bc12867210d093143b9fd2987 Mon Sep 17 00:00:00 2001 From: paspo Date: Thu, 15 Sep 2016 00:02:26 +0200 Subject: [PATCH 12/32] typo --- root/usr/share/doraemon/index.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index 202d574..b688186 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -35,10 +35,10 @@ function varsForRole($role, $json=true) { global $roles_db; $result = $roles_db->getKey($role); - $return = array('role'=>$role,'Delpkg'=>'','Addpkg'=>''); + $return = array('role'=>$role,'delpkg'=>'','addpkg'=>''); if (is_array($result)) { - if (is_string($result['Addpkg'])) $return['Addpkg'] = $result['Addpkg']; - if (is_string($result['Delpkg'])) $return['Delpkg'] = $result['Delpkg']; + if (is_string($result['Addpkg'])) $return['addpkg'] = $result['Addpkg']; + if (is_string($result['Delpkg'])) $return['delpkg'] = $result['Delpkg']; } if ($json) { return json_encode($return); From cfe38a1321e755fa246fb18d29ef1bff52c0a094 Mon Sep 17 00:00:00 2001 From: paspo Date: Thu, 15 Sep 2016 00:29:58 +0200 Subject: [PATCH 13/32] sudoers fix --- doraemon.spec | 2 +- .../e-smith/templates/etc/sudoers/50doraemon | 17 +++++++++++++---- root/usr/share/doraemon/index.php | 10 ++-------- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/doraemon.spec b/doraemon.spec index bf4793f..5244199 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -1,7 +1,7 @@ Summary: Helps client to join domain and maintain itself Name: doraemon Version: 2.0.0 -Release: 1.ns6 +Release: 2.ns6 URL: https://github.com/bglug-it/doraemon/ License: GPLv2+ Packager: Paolo Asperti diff --git a/root/etc/e-smith/templates/etc/sudoers/50doraemon b/root/etc/e-smith/templates/etc/sudoers/50doraemon index b456169..06692c8 100644 --- a/root/etc/e-smith/templates/etc/sudoers/50doraemon +++ b/root/etc/e-smith/templates/etc/sudoers/50doraemon @@ -1,6 +1,15 @@ -# -# 50doraemon -# -srvmgr ALL=NOPASSWD: /bin/cat /home/amgmt/.ansible/vault.txt +{ + $OUT = 'srvmgr ALL=NOPASSWD: /bin/cat '; + use esmith::ConfigDB; + my $confdb = esmith::ConfigDB->open; + my $backup = $confdb->get('doraemon') or die "No doraemon db entry found\n"; + my $VaultPassFile = $backup->prop('VaultPassFile') || '/home/amgmt/.ansible/vault.txt'; + my $ManagementKeyFile = $backup->prop('ManagementKeyFile') || '/home/amgmt/.ssh/id_rsa.pub'; + my $DomainFile = $backup->prop('DomainFile') || '/etc/domain.yml'; + $OUT = 'srvmgr ALL=NOPASSWD: /bin/cat ' . $VaultPassFile . ' +srvmgr ALL=NOPASSWD: /bin/cat ' . $ManagementKeyFile .' +srvmgr ALL=NOPASSWD: /bin/cat ' . $DomainFile; + +} diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index b688186..3d61794 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -125,19 +125,13 @@ function pingHost($host, $timeout=1) { function ROUTE_domain() { global $config_db; $theFile = $config_db->getProp(CONFIG_KEY,'DomainFile'); - $content = file_get_contents($theFile); - if (false !== $content) { - echo $content; - } + passthru("/usr/bin/sudo /bin/cat $theFile"); } function ROUTE_mgmtkey() { global $config_db; $theFile = $config_db->getProp(CONFIG_KEY,'ManagementKeyFile'); - $content = file_get_contents($theFile); - if (false !== $content) { - echo $content; - } + passthru("/usr/bin/sudo /bin/cat $theFile"); } function ROUTE_epoptes_srv() { From 048e5a82daf3c1cfee5901fd078f20b6ab57677f Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Thu, 15 Sep 2016 09:38:43 +0200 Subject: [PATCH 14/32] httpd link --- doraemon.spec | 2 ++ root/usr/sbin/doraemon | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) delete mode 120000 root/usr/sbin/doraemon diff --git a/doraemon.spec b/doraemon.spec index 5244199..91261bf 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -88,6 +88,8 @@ fi %post /etc/e-smith/events/actions/initialize-default-databases +[ -e /usr/sbin/doraemon ] && [ ! -L /usr/sbin/doraemon ] && rm /usr/sbin/doraemon +[ ! -L /usr/sbin/doraemon ] && ln -s httpd /usr/sbin/doraemon if [ "$1" = 1 ]; then #installation /sbin/e-smith/db configuration set %{name} service status enabled TCPPort 3000 access private DefaultRole client DomainFile /etc/domain.yml ManagementKeyFile /home/amgmt/.ssh/id_rsa.pub NamingBase lab NamingDigits 2 VaultPassFile /home/amgmt/.ansible/vault.txt diff --git a/root/usr/sbin/doraemon b/root/usr/sbin/doraemon deleted file mode 120000 index 558a907..0000000 --- a/root/usr/sbin/doraemon +++ /dev/null @@ -1 +0,0 @@ -httpd \ No newline at end of file From 17fcc5267dd980c7d62673e6a5814f41ccc8f74c Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Thu, 15 Sep 2016 10:48:36 +0200 Subject: [PATCH 15/32] fix packages list format --- root/usr/share/doraemon/index.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index 3d61794..5ec8d65 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -37,8 +37,10 @@ function varsForRole($role, $json=true) { $result = $roles_db->getKey($role); $return = array('role'=>$role,'delpkg'=>'','addpkg'=>''); if (is_array($result)) { - if (is_string($result['Addpkg'])) $return['addpkg'] = $result['Addpkg']; - if (is_string($result['Delpkg'])) $return['delpkg'] = $result['Delpkg']; + if (is_string($result['Addpkg'])) + $return['addpkg'] = preg_split("/[\s,]+/", $result['Addpkg']); + if (is_string($result['Delpkg'])) + $return['delpkg'] = preg_split("/[\s,]+/", $result['Delpkg']); } if ($json) { return json_encode($return); From 69c5c6af52e213c4a0252a81adba780f90403382 Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Thu, 15 Sep 2016 10:55:06 +0200 Subject: [PATCH 16/32] fix epoptes format --- root/usr/share/doraemon/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index 5ec8d65..ae2f3bf 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -143,7 +143,7 @@ function ROUTE_epoptes_srv() { echo 'none'; } else { $host = array_pop($hosts); - echo json_encode($host); + echo $host['name']; } } From abb3acf3a9d7aab94957fcaa12096aa9118e34f8 Mon Sep 17 00:00:00 2001 From: paspo Date: Tue, 27 Sep 2016 15:59:16 +0200 Subject: [PATCH 17/32] global hosts actions --- .../events/actions/doraemon-reboot-all | 20 +++++++++++ .../events/actions/doraemon-shutdown-all | 20 +++++++++++ .../e-smith/events/actions/doraemon-wake-all | 21 ++++++++++++ .../S50doraemon-reboot-all | 1 + .../S50doraemon-shutdown-all | 1 + .../doraemon-wake-all/S50doraemon-wake-all | 1 + .../en/NethServer_Module_Doraemon.php | 3 ++ .../it/NethServer_Module_Doraemon.php | 3 ++ .../NethServer/Module/Doraemon/Hosts.php | 3 ++ .../Module/Doraemon/Hosts/TogglePowerAll.php | 34 +++++++++++++++++++ .../Doraemon/Hosts/TogglePowerAll.php | 21 ++++++++++++ 11 files changed, 128 insertions(+) create mode 100755 root/etc/e-smith/events/actions/doraemon-reboot-all create mode 100755 root/etc/e-smith/events/actions/doraemon-shutdown-all create mode 100755 root/etc/e-smith/events/actions/doraemon-wake-all create mode 120000 root/etc/e-smith/events/doraemon-reboot-all/S50doraemon-reboot-all create mode 120000 root/etc/e-smith/events/doraemon-shutdown-all/S50doraemon-shutdown-all create mode 120000 root/etc/e-smith/events/doraemon-wake-all/S50doraemon-wake-all create mode 100644 root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePowerAll.php create mode 100644 root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePowerAll.php diff --git a/root/etc/e-smith/events/actions/doraemon-reboot-all b/root/etc/e-smith/events/actions/doraemon-reboot-all new file mode 100755 index 0000000..1e8d739 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-reboot-all @@ -0,0 +1,20 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); + +my @items = $db_hosts->get_all('remote'); +foreach my $item (@items) { + my $hostName = $item->key; + system("/usr/bin/sudo -u amgmt /usr/bin/ssh -o StrictHostKeyChecking=no amgmt\@$hostName /usr/bin/sudo /sbin/reboot &") == 0 + or die "Error rebooting $hostName"; +} + +exit 0; diff --git a/root/etc/e-smith/events/actions/doraemon-shutdown-all b/root/etc/e-smith/events/actions/doraemon-shutdown-all new file mode 100755 index 0000000..5df4213 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-shutdown-all @@ -0,0 +1,20 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); + +my @items = $db_hosts->get_all('remote'); +foreach my $item (@items) { + my $hostName = $item->key; + system("/usr/bin/sudo -u amgmt /usr/bin/ssh -o StrictHostKeyChecking=no amgmt\@$hostName /usr/bin/sudo /sbin/poweroff &") == 0 + or die "Error shutting down $hostName"; +} + +exit 0; diff --git a/root/etc/e-smith/events/actions/doraemon-wake-all b/root/etc/e-smith/events/actions/doraemon-wake-all new file mode 100755 index 0000000..39f97e2 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-wake-all @@ -0,0 +1,21 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); + +my @items = $db_hosts->get_all('remote'); +foreach my $item (@items) { + my $hostName = $item->key; + my $mac = $item->prop('MacAddress'); + system("/sbin/ether-wake -i lan0 $mac &") == 0 + or die "Error waking up $hostName"; +} + +exit 0; diff --git a/root/etc/e-smith/events/doraemon-reboot-all/S50doraemon-reboot-all b/root/etc/e-smith/events/doraemon-reboot-all/S50doraemon-reboot-all new file mode 120000 index 0000000..d03ca78 --- /dev/null +++ b/root/etc/e-smith/events/doraemon-reboot-all/S50doraemon-reboot-all @@ -0,0 +1 @@ +../actions/doraemon-reboot-all \ No newline at end of file diff --git a/root/etc/e-smith/events/doraemon-shutdown-all/S50doraemon-shutdown-all b/root/etc/e-smith/events/doraemon-shutdown-all/S50doraemon-shutdown-all new file mode 120000 index 0000000..c2cdf5f --- /dev/null +++ b/root/etc/e-smith/events/doraemon-shutdown-all/S50doraemon-shutdown-all @@ -0,0 +1 @@ +../actions/doraemon-shutdown-all \ No newline at end of file diff --git a/root/etc/e-smith/events/doraemon-wake-all/S50doraemon-wake-all b/root/etc/e-smith/events/doraemon-wake-all/S50doraemon-wake-all new file mode 120000 index 0000000..6642a73 --- /dev/null +++ b/root/etc/e-smith/events/doraemon-wake-all/S50doraemon-wake-all @@ -0,0 +1 @@ +../actions/doraemon-wake-all \ No newline at end of file diff --git a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php index 9c70ab3..6f87ce3 100644 --- a/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/en/NethServer_Module_Doraemon.php @@ -8,3 +8,6 @@ $L['shutdown_label'] = 'Shutdown'; $L['reboot_label'] = 'Reboot'; $L['wake_label'] = 'Wake Up'; +$L['shutdown-all_label'] = 'Shutdown all'; +$L['reboot-all_label'] = 'Reboot all'; +$L['wake-all_label'] = 'Wake Up all'; diff --git a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php index 812bcea..26e3dff 100644 --- a/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php +++ b/root/usr/share/nethesis/NethServer/Language/it/NethServer_Module_Doraemon.php @@ -8,3 +8,6 @@ $L['shutdown_label'] = 'Spegni'; $L['reboot_label'] = 'Riavvia'; $L['wake_label'] = 'Accendi'; +$L['shutdown-all_label'] = 'Spegni tutti'; +$L['reboot-all_label'] = 'Riavvia tutti'; +$L['wake-all_label'] = 'Accendi tutti'; diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php index 10c05ce..e898502 100644 --- a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php @@ -24,6 +24,9 @@ public function initialize() ->addRowAction(new \NethServer\Module\Doraemon\Hosts\TogglePower('shutdown')) ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('delete')) ->addTableAction(new \NethServer\Module\Doraemon\Hosts\Modify('create')) + ->addTableAction(new \NethServer\Module\Doraemon\Hosts\TogglePowerAll('wake-all')) + ->addTableAction(new \NethServer\Module\Doraemon\Hosts\TogglePowerAll('reboot-all')) + ->addTableAction(new \NethServer\Module\Doraemon\Hosts\TogglePowerAll('shutdown-all')) ->addTableAction(new \Nethgui\Controller\Table\Help('Help')) ; diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePowerAll.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePowerAll.php new file mode 100644 index 0000000..b1c7a26 --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/TogglePowerAll.php @@ -0,0 +1,34 @@ +getRequest()->isMutation()) { + return; + } + + $this->getPlatform()->signalEvent(sprintf('doraemon-%s@post', $this->getIdentifier())); + } + +} diff --git a/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePowerAll.php b/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePowerAll.php new file mode 100644 index 0000000..2d9968f --- /dev/null +++ b/root/usr/share/nethesis/NethServer/Template/Doraemon/Hosts/TogglePowerAll.php @@ -0,0 +1,21 @@ +requireFlag($view::INSET_DIALOG); + +if ($view->getModule()->getIdentifier() == 'shutdown-all') { + $headerText = $T('Shutdown all hosts'); + $panelText = $T('Proceed with all hosts shutdown?'); +} elseif ($view->getModule()->getIdentifier() == 'reboot-all') { + $headerText = $T('Reboot all hosts'); + $panelText = $T('Proceed with all hosts reboot?'); +} else { + $headerText = $T('Wakeup all hosts'); + $panelText = $T('Proceed with all hosts wakeup?'); +} + +echo $view->header()->setAttribute('template', $headerText); +// TODO: add a text label here +// echo $view->textLabel()->setAttribute('template', $panelText); +echo $view->buttonList() + ->insert($view->button('Yes', $view::BUTTON_SUBMIT)) + ->insert($view->button('No', $view::BUTTON_CANCEL)->setAttribute('value', $view['Cancel'])) +; From 3d9b33f770d933977274aaef6449b05718f23d67 Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Tue, 27 Sep 2016 17:51:58 +0200 Subject: [PATCH 18/32] fix: let's use the correct db for hosts --- doraemon.spec | 2 +- root/etc/e-smith/events/actions/doraemon-reboot-all | 2 +- root/etc/e-smith/events/actions/doraemon-shutdown-all | 2 +- root/etc/e-smith/events/actions/doraemon-wake-all | 2 +- root/usr/share/doraemon/index.php | 4 ++-- root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/doraemon.spec b/doraemon.spec index 91261bf..9e284bf 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -79,7 +79,7 @@ if [ "$1" = 2 ]; then if [ -f $DATABASE ]; then sqlite3 -separator " " $DATABASE \ "select * from client" | while read id hostname mac role; do - /sbin/e-smith/db hosts set $hostname remote \ + /sbin/e-smith/db hosts set $hostname local \ MacAddress $mac Role $role done rm $DATABASE diff --git a/root/etc/e-smith/events/actions/doraemon-reboot-all b/root/etc/e-smith/events/actions/doraemon-reboot-all index 1e8d739..8036c82 100755 --- a/root/etc/e-smith/events/actions/doraemon-reboot-all +++ b/root/etc/e-smith/events/actions/doraemon-reboot-all @@ -10,7 +10,7 @@ use English; my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); -my @items = $db_hosts->get_all('remote'); +my @items = $db_hosts->get_all('local'); foreach my $item (@items) { my $hostName = $item->key; system("/usr/bin/sudo -u amgmt /usr/bin/ssh -o StrictHostKeyChecking=no amgmt\@$hostName /usr/bin/sudo /sbin/reboot &") == 0 diff --git a/root/etc/e-smith/events/actions/doraemon-shutdown-all b/root/etc/e-smith/events/actions/doraemon-shutdown-all index 5df4213..cd0a5b1 100755 --- a/root/etc/e-smith/events/actions/doraemon-shutdown-all +++ b/root/etc/e-smith/events/actions/doraemon-shutdown-all @@ -10,7 +10,7 @@ use English; my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); -my @items = $db_hosts->get_all('remote'); +my @items = $db_hosts->get_all('local'); foreach my $item (@items) { my $hostName = $item->key; system("/usr/bin/sudo -u amgmt /usr/bin/ssh -o StrictHostKeyChecking=no amgmt\@$hostName /usr/bin/sudo /sbin/poweroff &") == 0 diff --git a/root/etc/e-smith/events/actions/doraemon-wake-all b/root/etc/e-smith/events/actions/doraemon-wake-all index 39f97e2..274d231 100755 --- a/root/etc/e-smith/events/actions/doraemon-wake-all +++ b/root/etc/e-smith/events/actions/doraemon-wake-all @@ -10,7 +10,7 @@ use English; my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); -my @items = $db_hosts->get_all('remote'); +my @items = $db_hosts->get_all('local'); foreach my $item (@items) { my $hostName = $item->key; my $mac = $item->prop('MacAddress'); diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index ae2f3bf..842a624 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -108,7 +108,7 @@ function newHostname($mac, $base, $role) { # } } while ($hosts_db->getKey($hostname)); - $hosts_db->setKey($hostname, 'remote', array( + $hosts_db->setKey($hostname, 'local', array( 'MacAddress' => $mac, 'Role' => $role, 'Description' => '' @@ -165,7 +165,7 @@ function ROUTE_hosts() { if (isset($get_params['role'])) { $items = $hosts_db->getAllByProp('Role', $get_params['role']); } else { - $items = $hosts_db->getAll('remote'); + $items = $hosts_db->getAll('local'); } $results=array(); foreach ($items as $name=>$item) { diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php index e898502..ca90f1f 100644 --- a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php @@ -16,7 +16,7 @@ public function initialize() ); $this - ->setTableAdapter($this->getPlatform()->getTableAdapter('hosts', 'remote')) + ->setTableAdapter($this->getPlatform()->getTableAdapter('hosts', 'local')) ->setColumns($columns) ->addRowAction(new \NethServer\Module\Doraemon\Hosts\Modify('update')) ->addRowAction(new \NethServer\Module\Doraemon\Hosts\TogglePower('wake')) From ee92679103fea34b0baa9b6c1a7796385c5ea1e8 Mon Sep 17 00:00:00 2001 From: paspo Date: Fri, 28 Oct 2016 19:01:27 +0200 Subject: [PATCH 19/32] FIX: doraemon doesn't start --- doraemon.spec | 2 +- root/etc/init/doraemon.conf | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 root/etc/init/doraemon.conf diff --git a/doraemon.spec b/doraemon.spec index 9e284bf..4e7fb4a 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -1,7 +1,7 @@ Summary: Helps client to join domain and maintain itself Name: doraemon Version: 2.0.0 -Release: 2.ns6 +Release: 7.ns6 URL: https://github.com/bglug-it/doraemon/ License: GPLv2+ Packager: Paolo Asperti diff --git a/root/etc/init/doraemon.conf b/root/etc/init/doraemon.conf new file mode 100644 index 0000000..e091ef8 --- /dev/null +++ b/root/etc/init/doraemon.conf @@ -0,0 +1,42 @@ +# ================= DO NOT MODIFY THIS FILE ================= +# +# Manual changes will be lost when this file is regenerated. +# +# Please read the developer's guide, which is available +# at https://dev.nethesis.it/projects/nethserver/wiki/NethServer +# original work from http://www.contribs.org/development/ +# +# Copyright (C) 2013 Nethesis S.r.l. +# http://www.nethesis.it - support@nethesis.it +# +# +# 10base doraemon - Apache instance that runs the doraemon service +# + +description "Apache instance that runs the doraemon service" +author "Paolo Asperti " +respawn +respawn limit 10 5 +expect fork +start on started network +stop on stopping network + + +# +# 20pre_start +# +pre-start script + STAT=`/sbin/e-smith/config getprop doraemon status` + if test "x$STAT" = "xenabled" \ + -a -f "/etc/e-smith/db/configuration/defaults/doraemon/status" \ + -a -x /usr/sbin/doraemon; then + exit 0; + fi + stop; exit 0; +end script + + +# +# 30script +# +exec /usr/sbin/doraemon -f /etc/httpd/doraemon/httpd.conf From 9a735742863e69dda0322dadc9d459c87a3ab3c3 Mon Sep 17 00:00:00 2001 From: paspo Date: Thu, 20 Oct 2016 13:10:53 +0200 Subject: [PATCH 20/32] FIX: old doraemon doesn't get stopped during upgrades --- doraemon.spec | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doraemon.spec b/doraemon.spec index 4e7fb4a..ec1db83 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -1,7 +1,7 @@ Summary: Helps client to join domain and maintain itself Name: doraemon Version: 2.0.0 -Release: 7.ns6 +Release: 8.ns6 URL: https://github.com/bglug-it/doraemon/ License: GPLv2+ Packager: Paolo Asperti @@ -41,6 +41,7 @@ mkdir -p %{buildroot}%{_localstatedir}/cache/doraemon #fi if [ "$1" = 2 ]; then #upgrade + /sbin/service %{name} stop >/dev/null 2>&1 || : /sbin/stop %{name} >/dev/null 2>&1 || : DATABASE=/var/lib/doraemon/doraemon.db INI=/etc/doraemon.ini From ce7ef1d33ce7c47b7bffe89c54e53c470cc4e4cb Mon Sep 17 00:00:00 2001 From: paspo Date: Fri, 28 Oct 2016 22:57:20 +0200 Subject: [PATCH 21/32] WIP: ansible configuration push --- root/etc/ansible/ansible.cfg | 13 +++++++++++++ root/etc/ansible/facts.d/domain.fact | 7 +++++++ root/etc/ansible/hosts | 8 ++++++++ root/etc/ansible/reconfigure_clients.yml | 7 +++++++ .../roles/proxy-client/tasks/apt-proxies.yml | 7 +++++++ root/etc/ansible/roles/proxy-client/tasks/main.yml | 6 ++++++ .../ansible/roles/proxy-client/templates/95proxies | 3 +++ .../e-smith/events/actions/doraemon-reconfigure-all | 3 +++ .../S50doraemon-reconfigure-all | 1 + 9 files changed, 55 insertions(+) create mode 100644 root/etc/ansible/ansible.cfg create mode 100755 root/etc/ansible/facts.d/domain.fact create mode 100644 root/etc/ansible/hosts create mode 100644 root/etc/ansible/reconfigure_clients.yml create mode 100644 root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml create mode 100644 root/etc/ansible/roles/proxy-client/tasks/main.yml create mode 100644 root/etc/ansible/roles/proxy-client/templates/95proxies create mode 100755 root/etc/e-smith/events/actions/doraemon-reconfigure-all create mode 120000 root/etc/e-smith/events/doraemon-reconfigure-all/S50doraemon-reconfigure-all diff --git a/root/etc/ansible/ansible.cfg b/root/etc/ansible/ansible.cfg new file mode 100644 index 0000000..1b51a8e --- /dev/null +++ b/root/etc/ansible/ansible.cfg @@ -0,0 +1,13 @@ +[defaults] +host_key_checking = False +remote_user = amgmt +private_key_file=/home/amgmt/.ssh/id_rsa +nocows = 1 +log_path = /var/log/ansible.log + +[privilege_escalation] +become=True +become_method=sudo +become_user=root +become_ask_pass=False + diff --git a/root/etc/ansible/facts.d/domain.fact b/root/etc/ansible/facts.d/domain.fact new file mode 100755 index 0000000..7f4612c --- /dev/null +++ b/root/etc/ansible/facts.d/domain.fact @@ -0,0 +1,7 @@ +#!/usr/bin/env python + +from yaml import load +from json import dumps + +with open('/etc/domain.yml') as file: + print(dumps(load(file))) diff --git a/root/etc/ansible/hosts b/root/etc/ansible/hosts new file mode 100644 index 0000000..683b834 --- /dev/null +++ b/root/etc/ansible/hosts @@ -0,0 +1,8 @@ +[clients:vars] +ansible_ssh_private_key_file=/home/amgmt/.ssh/id_rsa +ansible_user=amgmt + +[clients] +lab-01.mastri.edu +lab-02.mastri.edu + diff --git a/root/etc/ansible/reconfigure_clients.yml b/root/etc/ansible/reconfigure_clients.yml new file mode 100644 index 0000000..f33a57a --- /dev/null +++ b/root/etc/ansible/reconfigure_clients.yml @@ -0,0 +1,7 @@ +--- + +- hosts: clients + user: root + + roles: + - proxy-client diff --git a/root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml b/root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml new file mode 100644 index 0000000..492437e --- /dev/null +++ b/root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml @@ -0,0 +1,7 @@ +--- + +- name: Set apt proxies + template: + src: 95proxies + dest: /etc/apt/apt.conf.d/95proxies + force: yes diff --git a/root/etc/ansible/roles/proxy-client/tasks/main.yml b/root/etc/ansible/roles/proxy-client/tasks/main.yml new file mode 100644 index 0000000..db26c29 --- /dev/null +++ b/root/etc/ansible/roles/proxy-client/tasks/main.yml @@ -0,0 +1,6 @@ +--- +# BgLUG customization + +- include: apt-proxies.yml + tags: + - proxy-client diff --git a/root/etc/ansible/roles/proxy-client/templates/95proxies b/root/etc/ansible/roles/proxy-client/templates/95proxies new file mode 100644 index 0000000..10b2dfa --- /dev/null +++ b/root/etc/ansible/roles/proxy-client/templates/95proxies @@ -0,0 +1,3 @@ +Acquire::http::proxy "http://{{ ansible_local.domain.serverfqdn }}:3128/"; +Acquire::https::proxy "http://{{ ansible_local.domain.serverfqdn }}:3128/"; + diff --git a/root/etc/e-smith/events/actions/doraemon-reconfigure-all b/root/etc/e-smith/events/actions/doraemon-reconfigure-all new file mode 100755 index 0000000..1eb3939 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-reconfigure-all @@ -0,0 +1,3 @@ +#!/bin/bash + +/usr/bin/sudo -u amgmt /usr/bin/ansible-playbook -v /etc/ansible/doit.yml diff --git a/root/etc/e-smith/events/doraemon-reconfigure-all/S50doraemon-reconfigure-all b/root/etc/e-smith/events/doraemon-reconfigure-all/S50doraemon-reconfigure-all new file mode 120000 index 0000000..6f54f17 --- /dev/null +++ b/root/etc/e-smith/events/doraemon-reconfigure-all/S50doraemon-reconfigure-all @@ -0,0 +1 @@ +../actions/doraemon-reconfigure-all \ No newline at end of file From 253bab94c74065a79d1086563e43048cf6ba55f1 Mon Sep 17 00:00:00 2001 From: paspo Date: Mon, 31 Oct 2016 17:22:04 +0100 Subject: [PATCH 22/32] WIP: ansible configuration push --- doraemon.spec | 5 +++ root/etc/ansible/ansible.cfg | 2 +- root/etc/ansible/facts.d/domain.fact | 7 ---- root/etc/ansible/hosts | 8 ----- root/etc/ansible/inventory/clients.pl | 36 +++++++++++++++++++ root/etc/ansible/reconfigure_clients.yml | 3 +- root/etc/ansible/roles/common/tasks/main.yml | 11 ++++++ .../ansible/roles/proxy-client/tasks/main.yml | 5 ++- .../doraemon/ManagementPrivateKeyFile | 1 + .../events/actions/doraemon-reconfigure-all | 2 +- 10 files changed, 61 insertions(+), 19 deletions(-) delete mode 100755 root/etc/ansible/facts.d/domain.fact delete mode 100644 root/etc/ansible/hosts create mode 100755 root/etc/ansible/inventory/clients.pl create mode 100644 root/etc/ansible/roles/common/tasks/main.yml create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/ManagementPrivateKeyFile diff --git a/doraemon.spec b/doraemon.spec index ec1db83..c79d813 100644 --- a/doraemon.spec +++ b/doraemon.spec @@ -85,6 +85,11 @@ if [ "$1" = 2 ]; then done rm $DATABASE fi + V1=$(/sbin/e-smith/db configuration getprop doraemon ManagementPrivateKeyFile) + if [ "a$V1" == "a" ] ; then + V2=$(/sbin/e-smith/db configuration getprop doraemon ManagementKeyFile | sed "s/\.pub$//") + /sbin/e-smith/db configuration setprop doraemon ManagementPrivateKeyFile "$V2" + fi fi %post diff --git a/root/etc/ansible/ansible.cfg b/root/etc/ansible/ansible.cfg index 1b51a8e..b1a27c0 100644 --- a/root/etc/ansible/ansible.cfg +++ b/root/etc/ansible/ansible.cfg @@ -1,5 +1,6 @@ [defaults] host_key_checking = False +inventory = /etc/ansible/inventory/ remote_user = amgmt private_key_file=/home/amgmt/.ssh/id_rsa nocows = 1 @@ -10,4 +11,3 @@ become=True become_method=sudo become_user=root become_ask_pass=False - diff --git a/root/etc/ansible/facts.d/domain.fact b/root/etc/ansible/facts.d/domain.fact deleted file mode 100755 index 7f4612c..0000000 --- a/root/etc/ansible/facts.d/domain.fact +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env python - -from yaml import load -from json import dumps - -with open('/etc/domain.yml') as file: - print(dumps(load(file))) diff --git a/root/etc/ansible/hosts b/root/etc/ansible/hosts deleted file mode 100644 index 683b834..0000000 --- a/root/etc/ansible/hosts +++ /dev/null @@ -1,8 +0,0 @@ -[clients:vars] -ansible_ssh_private_key_file=/home/amgmt/.ssh/id_rsa -ansible_user=amgmt - -[clients] -lab-01.mastri.edu -lab-02.mastri.edu - diff --git a/root/etc/ansible/inventory/clients.pl b/root/etc/ansible/inventory/clients.pl new file mode 100755 index 0000000..989fff5 --- /dev/null +++ b/root/etc/ansible/inventory/clients.pl @@ -0,0 +1,36 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; +use JSON; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); +my $db_configuration = esmith::DB::db->open('configuration') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); + +my @hostnames = (); +my %vars = (); + +$vars{"proxy_status"} = $db_configuration->get_prop('squid', 'status'); +$vars{"ansible_user"} = "amgmt"; +$vars{"ansible_ssh_private_key_file"} = $db_configuration->get_prop('doraemon', 'ManagementPrivateKeyFile'); + +my $domainname = $db_configuration->get_prop('DomainName','type'); + +my @items = $db_hosts->get_all('local'); +foreach my $item (@items) { + push @hostnames, $item->key . '.' . $domainname; +} + +my %output = ('clients' => { + 'hosts' => [ @hostnames ], + 'vars' => { %vars } +} ); +my $json = encode_json \%output; +print "$json\n"; + +exit 0; diff --git a/root/etc/ansible/reconfigure_clients.yml b/root/etc/ansible/reconfigure_clients.yml index f33a57a..3c1cda4 100644 --- a/root/etc/ansible/reconfigure_clients.yml +++ b/root/etc/ansible/reconfigure_clients.yml @@ -4,4 +4,5 @@ user: root roles: - - proxy-client + - common + - { role: proxy-client, when: proxy_status == 'enabled' } diff --git a/root/etc/ansible/roles/common/tasks/main.yml b/root/etc/ansible/roles/common/tasks/main.yml new file mode 100644 index 0000000..00b76a9 --- /dev/null +++ b/root/etc/ansible/roles/common/tasks/main.yml @@ -0,0 +1,11 @@ +--- + +- name: Set hostname + hostname: name={{inventory_hostname}} + +- name: Update /etc/hosts for localhost + lineinfile: dest=/etc/hosts regexp='^127\.0\.0\.1' line='127.0.0.1 localhost' owner=root group=root mode=0644 + +- name: Update /etc/hosts for hostname + lineinfile: dest=/etc/hosts regexp='^127\.0\.1\.1' line='127.0.1.1 {{inventory_hostname}} {{inventory_hostname_short}}' owner=root group=root mode=0644 + diff --git a/root/etc/ansible/roles/proxy-client/tasks/main.yml b/root/etc/ansible/roles/proxy-client/tasks/main.yml index db26c29..2a2d35f 100644 --- a/root/etc/ansible/roles/proxy-client/tasks/main.yml +++ b/root/etc/ansible/roles/proxy-client/tasks/main.yml @@ -1,6 +1,9 @@ --- -# BgLUG customization - include: apt-proxies.yml tags: - proxy-client + when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu' + + + # when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux' diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/ManagementPrivateKeyFile b/root/etc/e-smith/db/configuration/defaults/doraemon/ManagementPrivateKeyFile new file mode 100644 index 0000000..5b4ee9d --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/ManagementPrivateKeyFile @@ -0,0 +1 @@ +/home/amgmt/.ssh/id_rsa diff --git a/root/etc/e-smith/events/actions/doraemon-reconfigure-all b/root/etc/e-smith/events/actions/doraemon-reconfigure-all index 1eb3939..79d11da 100755 --- a/root/etc/e-smith/events/actions/doraemon-reconfigure-all +++ b/root/etc/e-smith/events/actions/doraemon-reconfigure-all @@ -1,3 +1,3 @@ #!/bin/bash -/usr/bin/sudo -u amgmt /usr/bin/ansible-playbook -v /etc/ansible/doit.yml +/usr/bin/sudo -u amgmt /usr/bin/ansible-playbook -v /etc/ansible/reconfigure_clients.yml From 7b7ff6f8f47613a5fbf22daad7f9bb1db75d455d Mon Sep 17 00:00:00 2001 From: paspo Date: Tue, 1 Nov 2016 21:33:55 +0100 Subject: [PATCH 23/32] WIP: ansible configuration push --- root/etc/ansible/inventory/clients.pl | 2 + root/etc/ansible/roles/common/tasks/main.yml | 11 +++++- .../ansible/roles/common/templates/cronjob | 2 + .../events/actions/doraemon-reconfigure | 35 +++++++++++++++++ .../S50doraemon-reconfigure | 1 + root/usr/share/doraemon/index.php | 38 +++++++++++++++++++ 6 files changed, 88 insertions(+), 1 deletion(-) create mode 100755 root/etc/ansible/roles/common/templates/cronjob create mode 100755 root/etc/e-smith/events/actions/doraemon-reconfigure create mode 120000 root/etc/e-smith/events/doraemon-reconfigure/S50doraemon-reconfigure diff --git a/root/etc/ansible/inventory/clients.pl b/root/etc/ansible/inventory/clients.pl index 989fff5..1569847 100755 --- a/root/etc/ansible/inventory/clients.pl +++ b/root/etc/ansible/inventory/clients.pl @@ -13,6 +13,7 @@ package esmith; my $db_configuration = esmith::DB::db->open('configuration') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); my @hostnames = (); +my %hostnames_map = (); my %vars = (); $vars{"proxy_status"} = $db_configuration->get_prop('squid', 'status'); @@ -23,6 +24,7 @@ package esmith; my @items = $db_hosts->get_all('local'); foreach my $item (@items) { + $hostnames_map{$item} = $item->key . '.' . $domainname; push @hostnames, $item->key . '.' . $domainname; } diff --git a/root/etc/ansible/roles/common/tasks/main.yml b/root/etc/ansible/roles/common/tasks/main.yml index 00b76a9..5995f73 100644 --- a/root/etc/ansible/roles/common/tasks/main.yml +++ b/root/etc/ansible/roles/common/tasks/main.yml @@ -8,4 +8,13 @@ - name: Update /etc/hosts for hostname lineinfile: dest=/etc/hosts regexp='^127\.0\.1\.1' line='127.0.1.1 {{inventory_hostname}} {{inventory_hostname_short}}' owner=root group=root mode=0644 - + +- name: cron script + template: + src: cronjob + dest: /etc/cron.d/doraemon + force: yes + owner: root + group: root + mode: 0644 + when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu' diff --git a/root/etc/ansible/roles/common/templates/cronjob b/root/etc/ansible/roles/common/templates/cronjob new file mode 100755 index 0000000..a355655 --- /dev/null +++ b/root/etc/ansible/roles/common/templates/cronjob @@ -0,0 +1,2 @@ +*/5 * * * * root /usr/bin/curl "http://{{ ansible_local.domain.serverfqdn }}:3000/ping" +@reboot root /usr/bin/curl "http://{{ ansible_local.domain.serverfqdn }}:3000/ping" diff --git a/root/etc/e-smith/events/actions/doraemon-reconfigure b/root/etc/e-smith/events/actions/doraemon-reconfigure new file mode 100755 index 0000000..dc42ee7 --- /dev/null +++ b/root/etc/e-smith/events/actions/doraemon-reconfigure @@ -0,0 +1,35 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; + +my $db_hosts = esmith::DB::db->open('hosts') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); +my $db_configuration = esmith::DB::db->open('configuration') || die("Could not open e-smith db (" . esmith::DB::db->error . ")\n"); +my $domainname = $db_configuration->get_prop('DomainName','type'); + +my $event = $ARGV [0]; + +defined $ARGV[1] || die "No host specied"; +my $host = $ARGV[1]; + +reconfigure_host($host); + +exit 0; + +sub reconfigure_host +{ + my ($hostName) = @_; + + my $h = $db_hosts->get($hostName) or die "No host record for user $hostName"; + + my $fqdn = $hostName . '.' . $domainname; + + system("/usr/bin/sudo -u amgmt /usr/bin/ansible-playbook -l $fqdn -v /etc/ansible/reconfigure_clients.yml") == 0 + or die "Error reconfiguring $hostName"; + +} diff --git a/root/etc/e-smith/events/doraemon-reconfigure/S50doraemon-reconfigure b/root/etc/e-smith/events/doraemon-reconfigure/S50doraemon-reconfigure new file mode 120000 index 0000000..c8febb7 --- /dev/null +++ b/root/etc/e-smith/events/doraemon-reconfigure/S50doraemon-reconfigure @@ -0,0 +1 @@ +../actions/doraemon-reconfigure \ No newline at end of file diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index 842a624..970b75a 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -114,15 +114,53 @@ function newHostname($mac, $base, $role) { 'Description' => '' )); + signalEvent('doraemon-reconfigure', $hostname); + echo $hostname; } +function signalEvent($eventSpecification, $arguments = array()) +{ + $cmd = array( + escapeshellcmd('/usr/bin/sudo -n /sbin/e-smith/signal-event'), + escapeshellarg($eventSpecification) + ); + if (is_array($arguments)) { + $a = array_map('escapeshellarg', $arguments); + $cmd = array_merge($cmd, $a); + } else { + $cmd[] = escapeshellarg($arguments); + } + + exec(join(' ',$cmd)); + return true; +} + function pingHost($host, $timeout=1) { $pingresult = exec("/bin/ping -c 1 -t 2 -W $timeout $host", $output, $retvar); return (0 == $retvar); } +function ROUTE_reconfigureme() { + global $config_db; + $mac = getClientMac(); + if (!$mac) { + echo 'no-mac-address'; + return false; + } + if (!$client=getClient($mac)) { + echo 'unknown client'; + return false; + } + $hostname = $client['name']; + signalEvent('doraemon-reconfigure', $hostname); + echo "$hostname \n"; +} +function ROUTE_ping() { + // TODO: controllare ultimo aggiornamento + ROUTE_reconfigureme(); +} function ROUTE_domain() { global $config_db; From 821f3063a55381e2419a723bf7c133b2e19d5ce0 Mon Sep 17 00:00:00 2001 From: paspo Date: Wed, 2 Nov 2016 23:05:09 +0100 Subject: [PATCH 24/32] FEATURE: proxy client configuration --- root/etc/ansible/roles/proxy-client/handlers/main.yml | 3 +++ .../ansible/roles/proxy-client/tasks/apt-proxies.yml | 9 +++++++++ .../templates/doraemon-proxy.gschema.override | 11 +++++++++++ 3 files changed, 23 insertions(+) create mode 100644 root/etc/ansible/roles/proxy-client/handlers/main.yml create mode 100644 root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override diff --git a/root/etc/ansible/roles/proxy-client/handlers/main.yml b/root/etc/ansible/roles/proxy-client/handlers/main.yml new file mode 100644 index 0000000..1558b13 --- /dev/null +++ b/root/etc/ansible/roles/proxy-client/handlers/main.yml @@ -0,0 +1,3 @@ +--- +- name: glib-compile-schemas + command: /usr/bin/glib-compile-schemas /usr/share/glib-2.0/schemas/ diff --git a/root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml b/root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml index 492437e..647d6ab 100644 --- a/root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml +++ b/root/etc/ansible/roles/proxy-client/tasks/apt-proxies.yml @@ -5,3 +5,12 @@ src: 95proxies dest: /etc/apt/apt.conf.d/95proxies force: yes + + +- name: proxy gconf schema + template: + src: doraemon-proxy.gschema.override + dest: /usr/share/glib-2.0/schemas/doraemon-proxy.gschema.override + force: yes + notify: + - glib-compile-schemas diff --git a/root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override b/root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override new file mode 100644 index 0000000..ed2d434 --- /dev/null +++ b/root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override @@ -0,0 +1,11 @@ +[org.gnome.system.proxy] +mode = 'manual' +autoconfig-url = 'http://pdc.mastri.edu/wpad.dat' + +[org.gnome.system.proxy.http] +host = '{{ ansible_local.domain.serverfqdn }}' +port = 3128 + +[org.gnome.system.proxy.https] +host = '{{ ansible_local.domain.serverfqdn }}' +port = 3128 From 008f46eb5552d88328fa8dc7f16265670e25c827 Mon Sep 17 00:00:00 2001 From: paspo Date: Wed, 9 Nov 2016 23:23:21 +0100 Subject: [PATCH 25/32] FEATURE: show invalid mac address --- root/usr/share/doraemon/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index 970b75a..1dc5dc2 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -85,7 +85,7 @@ function newHostname($mac, $base, $role) { global $config_db; global $hosts_db; if(!preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $mac)) { - echo "invalid mac address"; + echo "invalid mac address: $mac"; return; } From 250017706b7c55bb16e1d460828891c3a7dd1775 Mon Sep 17 00:00:00 2001 From: paspo Date: Thu, 15 Dec 2016 09:11:14 +0100 Subject: [PATCH 26/32] FEATURE: e-smith config db access --- root/etc/ansible/library/e-smith | 19 +++++++++++++++++++ root/etc/ansible/roles/common/tasks/main.yml | 5 +++++ .../ansible/roles/common/templates/cronjob | 4 ++-- 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 root/etc/ansible/library/e-smith diff --git a/root/etc/ansible/library/e-smith b/root/etc/ansible/library/e-smith new file mode 100644 index 0000000..4ec3f36 --- /dev/null +++ b/root/etc/ansible/library/e-smith @@ -0,0 +1,19 @@ +#!/usr/bin/perl -w + +package esmith; + +use strict; +use Errno; +use esmith::DB::db; +use IO::File; +use English; +use JSON; + +my $db_configuration = esmith::DB::db->open('configuration') || die("{}"); +my @items = $db_configuration->get_all(); +my %out; +foreach my $item (@items) { + $out{$item->key} = { $item->props() }; +} + +print encode_json \%out; diff --git a/root/etc/ansible/roles/common/tasks/main.yml b/root/etc/ansible/roles/common/tasks/main.yml index 5995f73..a202693 100644 --- a/root/etc/ansible/roles/common/tasks/main.yml +++ b/root/etc/ansible/roles/common/tasks/main.yml @@ -1,5 +1,10 @@ --- +- name: Import e-smith configuration db + e-smith: + register: esmith + delegate_to: localhost + - name: Set hostname hostname: name={{inventory_hostname}} diff --git a/root/etc/ansible/roles/common/templates/cronjob b/root/etc/ansible/roles/common/templates/cronjob index a355655..4162cab 100755 --- a/root/etc/ansible/roles/common/templates/cronjob +++ b/root/etc/ansible/roles/common/templates/cronjob @@ -1,2 +1,2 @@ -*/5 * * * * root /usr/bin/curl "http://{{ ansible_local.domain.serverfqdn }}:3000/ping" -@reboot root /usr/bin/curl "http://{{ ansible_local.domain.serverfqdn }}:3000/ping" +*/5 * * * * root /usr/bin/curl --noproxy '*' "http://{{ ansible_local.domain.serverfqdn }}:{{ esmith.doraemon.TCPPort }}/ping" +@reboot root /usr/bin/curl --noproxy '*' "http://{{ ansible_local.domain.serverfqdn }}:{{ esmith.doraemon.TCPPort }}/ping" From 87c0fbe1d8e2dc182c24bfc9f624a43f4f537eb2 Mon Sep 17 00:00:00 2001 From: paspo Date: Thu, 15 Dec 2016 09:33:22 +0100 Subject: [PATCH 27/32] FIX: no need of /etc/domain.yml on client --- root/etc/ansible/library/e-smith | 7 ++++++- root/etc/ansible/roles/common/templates/cronjob | 4 ++-- root/etc/ansible/roles/proxy-client/templates/95proxies | 4 ++-- .../proxy-client/templates/doraemon-proxy.gschema.override | 4 ++-- 4 files changed, 12 insertions(+), 7 deletions(-) mode change 100644 => 100755 root/etc/ansible/library/e-smith diff --git a/root/etc/ansible/library/e-smith b/root/etc/ansible/library/e-smith old mode 100644 new mode 100755 index 4ec3f36..abfc93f --- a/root/etc/ansible/library/e-smith +++ b/root/etc/ansible/library/e-smith @@ -13,7 +13,12 @@ my $db_configuration = esmith::DB::db->open('configuration') || die("{}"); my @items = $db_configuration->get_all(); my %out; foreach my $item (@items) { - $out{$item->key} = { $item->props() }; + my %props = $item->props(); + if (scalar(keys %props) <= 1 ) { + $out{$item->key} = $props{'type'}; + } else { + $out{$item->key} = { $item->props() }; + } } print encode_json \%out; diff --git a/root/etc/ansible/roles/common/templates/cronjob b/root/etc/ansible/roles/common/templates/cronjob index 4162cab..ad43848 100755 --- a/root/etc/ansible/roles/common/templates/cronjob +++ b/root/etc/ansible/roles/common/templates/cronjob @@ -1,2 +1,2 @@ -*/5 * * * * root /usr/bin/curl --noproxy '*' "http://{{ ansible_local.domain.serverfqdn }}:{{ esmith.doraemon.TCPPort }}/ping" -@reboot root /usr/bin/curl --noproxy '*' "http://{{ ansible_local.domain.serverfqdn }}:{{ esmith.doraemon.TCPPort }}/ping" +*/5 * * * * root /usr/bin/curl --noproxy '*' "http://{{ esmith.SystemName }}.{{ esmith.DomainName }}:{{ esmith.doraemon.TCPPort }}/ping" +@reboot root /usr/bin/curl --noproxy '*' "http://{{ esmith.SystemName }}.{{ esmith.DomainName }}:{{ esmith.doraemon.TCPPort }}/ping" diff --git a/root/etc/ansible/roles/proxy-client/templates/95proxies b/root/etc/ansible/roles/proxy-client/templates/95proxies index 10b2dfa..935f39e 100644 --- a/root/etc/ansible/roles/proxy-client/templates/95proxies +++ b/root/etc/ansible/roles/proxy-client/templates/95proxies @@ -1,3 +1,3 @@ -Acquire::http::proxy "http://{{ ansible_local.domain.serverfqdn }}:3128/"; -Acquire::https::proxy "http://{{ ansible_local.domain.serverfqdn }}:3128/"; +Acquire::http::proxy "http://{{ esmith.SystemName }}.{{ esmith.DomainName }}:3128/"; +Acquire::https::proxy "http://{{ esmith.SystemName }}.{{ esmith.DomainName }}:3128/"; diff --git a/root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override b/root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override index ed2d434..e6b84e4 100644 --- a/root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override +++ b/root/etc/ansible/roles/proxy-client/templates/doraemon-proxy.gschema.override @@ -3,9 +3,9 @@ mode = 'manual' autoconfig-url = 'http://pdc.mastri.edu/wpad.dat' [org.gnome.system.proxy.http] -host = '{{ ansible_local.domain.serverfqdn }}' +host = '{{ esmith.SystemName }}.{{ esmith.DomainName }}' port = 3128 [org.gnome.system.proxy.https] -host = '{{ ansible_local.domain.serverfqdn }}' +host = '{{ esmith.SystemName }}.{{ esmith.DomainName }}' port = 3128 From 3b9e329f1810ef02fc2c2b1c9dcad0fd49f92533 Mon Sep 17 00:00:00 2001 From: Paolo Asperti Date: Thu, 12 Jan 2017 08:33:32 +0100 Subject: [PATCH 28/32] FEATURE: client check (at boot) if apt has been interrupted --- root/etc/ansible/roles/common/tasks/main.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/root/etc/ansible/roles/common/tasks/main.yml b/root/etc/ansible/roles/common/tasks/main.yml index a202693..77e5240 100644 --- a/root/etc/ansible/roles/common/tasks/main.yml +++ b/root/etc/ansible/roles/common/tasks/main.yml @@ -23,3 +23,12 @@ group: root mode: 0644 when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu' + +- name: rc.local command to check if apt is pending + blockinfile: + dest: /etc/rc.local + block: | + apt-get check >/dev/null 2>&1 + if [ "$?" -ne 0 ]; then + apt-get -f -y install + fi From b73b6e027582a7ca1d3688fe43691198d497f0b5 Mon Sep 17 00:00:00 2001 From: amreo Date: Tue, 7 Feb 2017 21:08:53 +0100 Subject: [PATCH 29/32] Changed old path of config file --- doraemon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doraemon.py b/doraemon.py index 459c316..4c879c3 100644 --- a/doraemon.py +++ b/doraemon.py @@ -20,7 +20,7 @@ import os class MyApp: - def __init__(self, configfile = '/etc/mac2hostname.ini'): + def __init__(self, configfile = '/etc/doraemon.ini'): if not os.path.isfile(configfile): print "Cannot find main file, %s. Exiting." % configfile sys.exit(1) From 126b56d5f27dbc04aac42c9731a12ce3e5395c04 Mon Sep 17 00:00:00 2001 From: amreo Date: Tue, 7 Feb 2017 21:16:33 +0100 Subject: [PATCH 30/32] Updated legacy option --- doraemon.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doraemon.py b/doraemon.py index 4c879c3..0a4f660 100644 --- a/doraemon.py +++ b/doraemon.py @@ -34,8 +34,8 @@ def __init__(self, configfile = '/etc/doraemon.ini'): self.__pidfile = config.get('Daemon', 'PIDFile') if config.has_option('Daemon', 'PIDFile') else '/var/run/doraemon.pid' self.__bindaddress = config.get('Daemon', 'BindAddress') if config.has_option('Daemon', 'BindAddress') else '127.0.0.1' self.__port = config.getint('Daemon', 'Port') if config.has_option('Daemon', - 'Port') else 8080 - self.__defaultbase = config.get('NameSettings', 'Base') if config.has_option('NameSettings', 'Base') else 'client' + 'Port') else 3000 + self.__defaultbase = config.get('NameSettings', 'Base') if config.has_option('NameSettings', 'Base') else 'lab' self.__defaultrole = config.get('NameSettings', 'Role') if config.has_option('NameSettings', 'Role') else 'client' self.__namedigits = config.get('NameSettings', 'Digits') if config.has_option('NameSettings', 'Digits') else '2' self.__domainfile = config.get('Files', 'Domain') if config.has_option('Files', 'Domain') else None From 12e080e3204ec077e1306e2ad4289dfb8e7d38a4 Mon Sep 17 00:00:00 2001 From: amreo Date: Thu, 27 Apr 2017 09:02:06 +0200 Subject: [PATCH 31/32] Added support for multilab in Doraemon --- .../defaults/doraemon/DefaultLabID | 1 + .../defaults/doraemon/HostNameFormat | 1 + root/usr/share/doraemon/index.php | 65 ++++++++++++++----- 3 files changed, 52 insertions(+), 15 deletions(-) create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/DefaultLabID create mode 100644 root/etc/e-smith/db/configuration/defaults/doraemon/HostNameFormat diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/DefaultLabID b/root/etc/e-smith/db/configuration/defaults/doraemon/DefaultLabID new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/DefaultLabID @@ -0,0 +1 @@ +1 diff --git a/root/etc/e-smith/db/configuration/defaults/doraemon/HostNameFormat b/root/etc/e-smith/db/configuration/defaults/doraemon/HostNameFormat new file mode 100644 index 0000000..52e99e5 --- /dev/null +++ b/root/etc/e-smith/db/configuration/defaults/doraemon/HostNameFormat @@ -0,0 +1 @@ +lab%'.02d-%'.02d diff --git a/root/usr/share/doraemon/index.php b/root/usr/share/doraemon/index.php index 1dc5dc2..ce2c6a9 100644 --- a/root/usr/share/doraemon/index.php +++ b/root/usr/share/doraemon/index.php @@ -81,7 +81,7 @@ function getClientMac($ip=false) { } } -function newHostname($mac, $base, $role) { +function newHostname($mac, /*$base,*/ $role, $labid) { global $config_db; global $hosts_db; if(!preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $mac)) { @@ -95,13 +95,14 @@ function newHostname($mac, $base, $role) { } $domainName = (string)$config_db->getKeyValue('DomainName'); - $digits = $config_db->getProp(CONFIG_KEY,'NamingDigits'); - $formatstring = '%s-%0'.$digits.'d'; + //$digits = $config_db->getProp(CONFIG_KEY,'NamingDigits'); + //$formatstring = '%s-%0'.$digits.'d'; + $formatstring = $config_db->getKeyValue('HostNameFormat'); $nr=0; $hostname = ''; do { $nr++; - $hostname = sprintf($formatstring, $base, $nr); + $hostname = sprintf($formatstring, $labid, $nr); # TODO: we'll use the hostname in future, maybe # if (trim($domainName) != '') { # $hostname .= '.' . $domainName; @@ -109,9 +110,10 @@ function newHostname($mac, $base, $role) { } while ($hosts_db->getKey($hostname)); $hosts_db->setKey($hostname, 'local', array( - 'MacAddress' => $mac, + 'MacAddress' => $mac, 'Role' => $role, - 'Description' => '' + 'Description' => '', + 'LabID' => $labid )); signalEvent('doraemon-reconfigure', $hostname); @@ -176,11 +178,28 @@ function ROUTE_mgmtkey() { function ROUTE_epoptes_srv() { global $hosts_db; + global $get_params; + global $config_db; + + if (isset($get_params['labid'])) { + $labid = $get_params['labid']; + } else { + $labid = $config_db->getProp(CONFIG_KEY,'DefaultLabID'); + } + $hosts = $hosts_db->getAllByProp('Role','docenti'); - if (count($hosts) == 0) { + + $hostsFiltered = array_filter( + $hosts, + function ($item) use ($labid) { + return $item['labid'] == $labid; + } + ); + + if (count($hostsFiltered) == 0) { echo 'none'; } else { - $host = array_pop($hosts); + $host = array_pop($hostsFiltered); echo $host['name']; } } @@ -197,6 +216,10 @@ function ROUTE_ansible_host() { echo varsForRole($role); } +/** + * @deprecated + * Will be removed!!! + */ function ROUTE_hosts() { global $hosts_db; global $get_params; @@ -216,6 +239,10 @@ function ROUTE_hosts() { echo json_encode($results); } +/** + * @deprecated + * Will be removed!!! + */ function ROUTE_ansible_list() { global $get_params; if (isset($get_params['role'])) { @@ -261,9 +288,11 @@ function ROUTE_whatsmyhostname() { echo 'no-mac-address'; return false; } - $base = $config_db->getProp(CONFIG_KEY,'NamingBase'); + /*$base = $config_db->getProp(CONFIG_KEY,'NamingBase');*/ $role = $config_db->getProp(CONFIG_KEY,'DefaultRole'); - newHostname($mac, $base, $role); + $labid = $config_db->getProp(CONFIG_KEY,'DefaultLabID'); + + newHostname($mac, /*$base,*/ $role, $labid); } function ROUTE_mac2hostname() { @@ -271,7 +300,7 @@ function ROUTE_mac2hostname() { global $get_params; $mac = getClientMac(); if (!$mac) { - echo 'Usage: GET /mac2hostname?mac=XX_XX_XX_XX_XX_XX[&base=YYY][&role=ZZZ]'; + echo 'Usage: GET /mac2hostname?mac=XX_XX_XX_XX_XX_XX[&base=YYY][&role=ZZZ][&labid=WW]'; return; } @@ -281,11 +310,17 @@ function ROUTE_mac2hostname() { $role = $config_db->getProp(CONFIG_KEY,'DefaultRole'); } - if (isset($get_params['base'])) { - $base = $get_params['base']; +// if (isset($get_params['base'])) { +// $base = $get_params['base']; +// } else { +// $base = $config_db->getProp(CONFIG_KEY,'NamingBase'); +// } + + if (isset($get_params['labid'])) { + $labid = $get_params['labid']; } else { - $base = $config_db->getProp(CONFIG_KEY,'NamingBase'); + $labid = $config_db->getProp(CONFIG_KEY,'DefaultLabID'); } - newHostname($mac, $base, $role); + newHostname($mac, /*$base,*/ $role, $labid); } From b93c6ca754c6537a35fcde67eeb0d9da6d81bc0e Mon Sep 17 00:00:00 2001 From: amreo Date: Thu, 27 Apr 2017 09:46:34 +0200 Subject: [PATCH 32/32] Updated the webgui --- root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php | 1 + .../share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php | 1 + 2 files changed, 2 insertions(+) diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php index ca90f1f..2e0be62 100644 --- a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts.php @@ -12,6 +12,7 @@ public function initialize() 'Key', 'MacAddress', 'Role', + 'LabID', 'Actions', ); diff --git a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php index ab9d3d6..a6f228e 100644 --- a/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php +++ b/root/usr/share/nethesis/NethServer/Module/Doraemon/Hosts/Modify.php @@ -15,6 +15,7 @@ public function initialize() array('hostname', Validate::HOSTNAME_SIMPLE, \Nethgui\Controller\Table\Modify::KEY), array('MacAddress', Validate::MACADDRESS, \Nethgui\Controller\Table\Modify::FIELD), array('Role', Validate::ANYTHING, \Nethgui\Controller\Table\Modify::FIELD), + array('LabID', Validate::POSITIVE_INTEGER, \Nethgui\Controller\Table\Modify::FIELD), // array('Role', Validate::ROLES_COLLECTION ??? TODO!!!, \Nethgui\Controller\Table\Modify::FIELD), ); $this->setSchema($parameterSchema);