Ejemplo n.º 1
0
    def push_data(self,):
        key = self.request.headers.get('X-Key')
        if not key:
            return JSONAsyncResult(http_code = 401, data = {'error': 'X-Key header missing'})
        try:
            data = tornado.escape.json_decode(self.request.body)
            # Insert data in an other thread.
        except Exception as e:
            return JSONAsyncResult(http_code = 500, data = {'error': e.message})
        try:
            # We need to use a scoped_session object here as far the
            # code below is executed in its own thread.
            session_factory = sessionmaker(bind=self.engine)
            Session = scoped_session(session_factory)
            thread_session = Session()

            # Check the key
            if data['instances'][0]['available']:
                check_agent_key(thread_session, data['hostinfo']['hostname'], data['instances'][0]['data_directory'], data['instances'][0]['port'], key)
            else:
                # Case when PostgreSQL instance is not started.
                check_host_key(thread_session, data['hostinfo']['hostname'], key)
            # Update the inventory
            host = merge_agent_info(thread_session,
                    data['hostinfo'],
                    data['instances'])

            # Send the write SQL commands to the database because the
            # metrics are inserted with queries not the orm. Tables must
            # be there.
            thread_session.flush()
            thread_session.commit()

            # Insert metrics data
            insert_metrics(thread_session, host, data['data'], self.logger, data['hostinfo']['hostname'])
            # Close the session
            thread_session.close()
            return JSONAsyncResult(http_code = 200, data = {'done': True})
        except IntegrityError as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            try:
                thread_session.rollback()
                thread_session.close()
            except Exception:
                pass
            return JSONAsyncResult(http_code = 409, data = {'error': e.message})
        except Exception as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            try:
                thread_session.rollback()
                thread_session.close()
            except Exception:
                pass
            return JSONAsyncResult(http_code = 500, data = {'error': e.message})
Ejemplo n.º 2
0
 def post_register(self, ):
     try:
         data = tornado.escape.json_decode(self.request.body)
         if 'agent_address' not in data or data['agent_address'] is None:
             # Try to find agent's IP
             x_real_ip = self.request.headers.get("X-Real-IP")
             data['new_agent_address'] = x_real_ip or self.request.remote_ip
         else:
             data['new_agent_address'] = data['agent_address']
         data['new_agent_port'] = data['agent_port']
         self.request.body = tornado.escape.json_encode(data)
         self.logger.debug(data)
         self.logger.debug(self.request.body)
         return self.post_instance(None, None)
     except (TemboardUIError, TemboardError, Exception) as e:
         self.logger.traceback(get_tb())
         self.logger.error(str(e))
         self.logger.info("Failed.")
         try:
             self.db_session.close()
         except Exception:
             pass
         if isinstance(e, TemboardUIError) or isinstance(e, TemboardError):
             return JSONAsyncResult(e.code, {'error': e.message})
         else:
             return JSONAsyncResult(500, {'error': "Internal error."})
Ejemplo n.º 3
0
def insert_metrics(session, host, agent_data, logger, hostname):
    for metric in agent_data.keys():
        # Do not try to insert empty lines
        if len(agent_data[metric]) == 0:
            continue

        # Find the name to the Table object
        if 'metric_' + metric in globals().keys():
            table = globals()['metric_' + metric]
        else:
            continue

        # XXX The interval input must be a string to be cast by
        # PostgreSQL. It is used by the measure_interval value, which
        # come as a number
        for line in agent_data[metric]:
            if 'measure_interval' in line:
                line['measure_interval'] = str(line['measure_interval'])
            # Add hostname from hostinfo to each line
            line['hostname'] = hostname
        try:
            session.execute(table.insert().values(agent_data[metric]))
            session.flush()
            session.commit()
        except Exception as e:
            logger.info("Metric data not inserted in table '%s'" % (table.name))
            logger.debug(agent_data[metric])
            logger.traceback(get_tb())
            logger.error(str(e))
            session.rollback()
Ejemplo n.º 4
0
def worker_data_agg(task):
    try:
        parameters = json.loads(task.parameters)
        config =  Configuration(parameters['configpath'])
        set_logger_name("worker_data_agg")
        logger = get_logger(config)
        dburi = 'postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(
                    user = config.repository['user'],
                    password = config.repository['password'],
                    host = config.repository['host'],
                    port = config.repository['port'],
                    dbname = config.repository['dbname'])
        engine = create_engine(dburi)
        with engine.connect() as conn:
            conn.execute("SET search_path TO supervision")
            res = conn.execute("SELECT * FROM metric_populate_agg_tables()")
            for row in res.fetchall():
                logger.debug("table=%s insert=%s" % (row['agg_tablename'], row['nb_insert']))
            conn.execute("COMMIT")
            exit(0)
    except (ConfigurationError, ImportError, Exception) as e:
        try:
            logger.traceback(get_tb())
            logger.error(str(e))
            try:
                conn.execute("ROLLBACK")
            except Exception as e:
                pass
        except Exception:
            pass
        exit(1)
Ejemplo n.º 5
0
    def get_discover(self, agent_address, agent_port):
        try:
            self.logger.info("Getting discovery.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()
            self.db_session.close()

            res = temboard_discover(self.ssl_ca_cert_file, agent_address,
                                    agent_port)
            self.logger.info("Done.")
            return JSONAsyncResult(200, res)

        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.close()
            except Exception:
                pass
            if isinstance(e, TemboardUIError) or isinstance(e, TemboardError):
                return JSONAsyncResult(e.code, {'error': e.message})
            else:
                return JSONAsyncResult(500, {'error': "Internal error."})
Ejemplo n.º 6
0
    def delete_instance(self):
        try:
            self.logger.info("Deleting instance.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            data = tornado.escape.json_decode(self.request.body)
            self.logger.debug(data)
            if 'agent_address' not in data or data['agent_address'] == '':
                raise TemboardUIError(400, "Agent address field is missing.")
            if 'agent_port' not in data or data['agent_port'] == '':
                raise TemboardUIError(400, "Agent port field is missing.")
            delete_instance(self.db_session, data['agent_address'],
                            data['agent_port'])
            self.db_session.commit()
            self.db_session.close()
            self.logger.info("Done.")
            return JSONAsyncResult(200, {'delete': True})

        except (TemboardUIError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if isinstance(e, TemboardUIError):
                return JSONAsyncResult(e.code, {'error': e.message})
            else:
                return JSONAsyncResult(500, {'error': "Internal error."})
Ejemplo n.º 7
0
    def get_instance(self, agent_address, agent_port):
        try:
            self.logger.info("Getting instance.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            instance = get_instance(self.db_session, agent_address, agent_port)
            groups = get_group_list(self.db_session, 'instance')
            if not instance:
                raise TemboardUIError(404, "Instance entry not found.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            self.logger.info("Done.")
            return JSONAsyncResult(
                200, {
                    'agent_address':
                    instance.agent_address,
                    'agent_port':
                    instance.agent_port,
                    'agent_key':
                    instance.agent_key,
                    'hostname':
                    instance.hostname,
                    'cpu':
                    instance.cpu,
                    'memory_size':
                    instance.memory_size,
                    'pg_port':
                    instance.pg_port,
                    'pg_version':
                    instance.pg_version,
                    'pg_data':
                    instance.pg_data,
                    'in_groups':
                    [group.group_name for group in instance.groups],
                    'enabled_plugins':
                    [plugin.plugin_name for plugin in instance.plugins],
                    'groups': [{
                        'name': group.group_name,
                        'description': group.group_description
                    } for group in groups],
                    'loaded_plugins':
                    self.application.loaded_plugins
                })
        except (TemboardUIError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if isinstance(e, TemboardUIError):
                return JSONAsyncResult(e.code, {'error': e.message})
            else:
                return JSONAsyncResult(500, {'error': "Internal error."})
Ejemplo n.º 8
0
 def get_current_user(self, ):
     if self.auth_cookie and self.db_session:
         try:
             return get_role_by_cookie(self.db_session, self.auth_cookie)
         except Exception as e:
             self.logger.traceback(get_tb())
             self.logger.error(e.message)
     return
Ejemplo n.º 9
0
    def get_group(self, group_kind, group_name):
        try:
            self.logger.info("Getting group by name.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            group = get_group(self.db_session, group_name, group_kind)
            self.logger.debug(group)

            if group_kind == 'role':
                self.db_session.expunge_all()
                self.db_session.commit()
                self.db_session.close()
                self.logger.info("Done")
                return JSONAsyncResult(
                    200, {
                        'name': group.group_name,
                        'kind': group.group_kind,
                        'description': group.group_description
                    })
            else:
                user_groups = get_group_list(self.db_session)
                self.db_session.expunge_all()
                self.db_session.commit()
                self.db_session.close()
                self.logger.info("Done.")
                return JSONAsyncResult(
                    200, {
                        'name':
                        group.group_name,
                        'kind':
                        group.group_kind,
                        'description':
                        group.group_description,
                        'user_groups':
                        [{
                            'name': user_group.group_name,
                            'description': user_group.group_description
                        } for user_group in user_groups],
                        'in_groups':
                        [ari.role_group_name for ari in group.ari]
                    })

        except (TemboardUIError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if isinstance(e, TemboardUIError):
                return JSONAsyncResult(e.code, {'error': e.message})
            else:
                return JSONAsyncResult(500, {'error': "Internal error."})
Ejemplo n.º 10
0
    def get_activity_w_b(self, agent_address, agent_port, mode):
        try:
            self.logger.info("Getting waiting/blocking sessions (proxy).")
            role = None
            instance = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")
            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not activated.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()

            xsession = self.request.headers.get('X-Session')
            if not xsession:
                raise TemboardUIError(401, 'X-Session header missing')

            # Load activity.
            if mode == 'waiting':
                data_activity = temboard_activity_waiting(
                    self.ssl_ca_cert_file, instance.agent_address,
                    instance.agent_port, xsession)
            elif mode == 'blocking':
                data_activity = temboard_activity_blocking(
                    self.ssl_ca_cert_file, instance.agent_address,
                    instance.agent_port, xsession)
            else:
                raise TemboardUIError(404, "Mode unknown.")
            self.logger.info("Done.")
            return JSONAsyncResult(http_code=200, data=data_activity)
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                return JSONAsyncResult(http_code=e.code,
                                       data={'error': e.message})
            else:
                return JSONAsyncResult(http_code=500,
                                       data={'error': e.message})
Ejemplo n.º 11
0
    def post_hba(self, agent_address, agent_port):
        try:
            self.logger.info("Posting HBA (proxy).")
            instance = None
            role = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not active.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")

            data = temboard_post_conf_file(
                self.ssl_ca_cert_file, 'hba', instance.agent_address,
                instance.agent_port, xsession,
                tornado.escape.json_decode(self.request.body))
            # And reload postgresql configuration.
            ret_reload = temboard_post_administration_control(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession, {'action': 'reload'})
            self.logger.info("Done.")
            return JSONAsyncResult(http_code=200, data=data)
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                return JSONAsyncResult(http_code=e.code,
                                       data={'error': e.message})
            else:
                return JSONAsyncResult(http_code=500,
                                       data={'error': e.message})
Ejemplo n.º 12
0
 def start_db_session(self):
     """
     Try to start a new DB session (local to current thread).
     """
     MetaData.bind = self.application.engine
     try:
         session_factory = sessionmaker(bind=self.application.engine)
         Session = scoped_session(session_factory)
         self.db_session = Session()
     except Exception as e:
         self.logger.traceback(get_tb())
         self.logger.error(e.message)
         raise TemboardUIError(500,
                               "Unable to create a new database session.")
Ejemplo n.º 13
0
    def prepare(self):
        # Incorporate request JSON into arguments dictionary.
        if self.request.body:
            try:
                json_data = json.loads(self.request.body)
                self.request.arguments.update(json_data)
            except Exception as e:
                self.logger.traceback(get_tb())
                self.logger.error(e.message)
                message = 'Unable to parse JSON.'
                self.send_error(400, error=message)

        # Set up response dictionary.
        self.response = dict()
Ejemplo n.º 14
0
    def delete_hba(self, agent_address, agent_port):
        try:
            self.logger.info("Deleting HBA (proxy).")
            instance = None
            role = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not active.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")

            res = temboard_delete_hba_version(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession,
                self.get_argument('version', None))
            self.logger.info("Done.")
            return JSONAsyncResult(http_code=200, data=res)
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                return JSONAsyncResult(http_code=e.code,
                                       data={'error': e.message})
            else:
                return JSONAsyncResult(http_code=500,
                                       data={'error': e.message})
Ejemplo n.º 15
0
    def post_login(self, agent_address, agent_port):
        try:
            self.logger.info("Posting to agent login.")
            instance = None
            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()

            xsession = temboard_login(self.ssl_ca_cert_file,
                                      instance.agent_address,
                                      instance.agent_port,
                                      self.get_argument("username"),
                                      self.get_argument("password"))

            self.set_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port),
                xsession,
                expires_days=0.5)
            self.logger.info("Done.")
            return HTMLAsyncResult(
                        http_code = 302,
                        redirection = self.get_secure_cookie('referer_uri') \
                            if self.get_secure_cookie('referer_uri') is not None \
                            else "/server/%s/%s/dashboard" % (instance.agent_address, instance.agent_port))
        except (TemboardError, TemboardUIError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception as e:
                pass
            return HTMLAsyncResult(http_code=200,
                                   template_file='agent-login.html',
                                   data={
                                       'nav': True,
                                       'error': e.message,
                                       'instance': instance,
                                       'username': None
                                   })
Ejemplo n.º 16
0
    def post_kill(self, agent_address, agent_port):
        try:
            self.logger.info("Posting terminate backend.")
            role = None
            instance = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")
            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not activated.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()

            xsession = self.request.headers.get('X-Session')
            if not xsession:
                raise TemboardUIError(401, 'X-Session header missing')

            self.logger.debug(tornado.escape.json_decode(self.request.body))
            data_kill = temboard_activity_kill(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession,
                tornado.escape.json_decode(self.request.body))
            self.logger.info("Done.")
            return JSONAsyncResult(http_code=200, data=data_kill)
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                return JSONAsyncResult(http_code=e.code,
                                       data={'error': e.message})
            else:
                return JSONAsyncResult(http_code=500,
                                       data={'error': e.message})
Ejemplo n.º 17
0
    def get_login(self):
        role = None
        try:
            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
        except Exception as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
        if role is not None:
            return HTMLAsyncResult(http_code=302, redirection='/home')
        return HTMLAsyncResult(http_code=200,
                               template_file='login.html',
                               data={'nav': False})
Ejemplo n.º 18
0
 def get_home(self):
     try:
         self.logger.info("Loading home.")
         self.load_auth_cookie()
         self.start_db_session()
         role = self.current_user
         if not role:
             raise TemboardUIError(302, 'Current role unknown.')
         instance_list = get_instances_by_role_name(self.db_session,
                                                    role.role_name)
         self.db_session.expunge_all()
         self.db_session.commit()
         self.db_session.close()
         self.logger.info("Done.")
         return HTMLAsyncResult(http_code=200,
                                template_file='home.html',
                                data={
                                    'nav': True,
                                    'role': role,
                                    'instance_list': instance_list
                                })
     except (TemboardUIError, Exception) as e:
         self.logger.traceback(get_tb())
         self.logger.error(str(e))
         self.logger.info("Failed.")
         try:
             self.db_session.expunge_all()
             self.db_session.rollback()
             self.db_session.close()
         except Exception:
             pass
         if isinstance(e, TemboardUIError):
             if e.code == 302:
                 return HTMLAsyncResult(302, '/login')
             elif e.code == 401:
                 return HTMLAsyncResult(401,
                                        None, {'nav': False},
                                        template_file='unauthorized.html')
         return HTMLAsyncResult(500,
                                None, {
                                    'nav': False,
                                    'error': e.message
                                },
                                template_file='error.html')
Ejemplo n.º 19
0
    def get_index(self, group_kind):
        try:
            self.logger.info("Group list.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            group_list = get_group_list(self.db_session, group_kind)
            self.logger.debug(group_list)

            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            self.logger.info("Done.")
            return HTMLAsyncResult(200,
                                   None, {
                                       'nav': True,
                                       'role': self.current_user,
                                       'group_list': group_list,
                                       'group_kind': group_kind
                                   },
                                   template_file='manage/group.html')
        except (TemboardUIError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if isinstance(e, TemboardUIError):
                if e.code == 302:
                    return HTMLAsyncResult(302, '/login')
                elif e.code == 401:
                    return HTMLAsyncResult(401,
                                           None, {'nav': False},
                                           template_file='unauthorized.html')
            return HTMLAsyncResult(500,
                                   None, {
                                       'nav': False,
                                       'error': e.message
                                   },
                                   template_file='manage/error.html')
Ejemplo n.º 20
0
    def get_role(self, username):
        try:
            self.logger.info("Getting role by name.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            role = get_role(self.db_session, username)
            groups = get_group_list(self.db_session)

            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            self.logger.info("Done.")
            return JSONAsyncResult(
                200, {
                    'role_name':
                    role.role_name,
                    'role_email':
                    role.role_email,
                    'is_active':
                    role.is_active,
                    'is_admin':
                    role.is_admin,
                    'in_groups': [group.group_name for group in role.groups],
                    'groups': [{
                        'name': group.group_name,
                        'description': group.group_description
                    } for group in groups]
                })
        except (TemboardUIError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if isinstance(e, TemboardUIError):
                return JSONAsyncResult(e.code, {'error': e.message})
            else:
                return JSONAsyncResult(500, {'error': "Internal error."})
Ejemplo n.º 21
0
    def post_login(self):
        try:
            self.logger.info("Login (API).")
            post = tornado.escape.json_decode(self.request.body)
            p_role_name = post['username']
            p_role_password = post['password']
            role_hash_password = hash_password(p_role_name, p_role_password)

            self.start_db_session()
            role = get_role_by_auth(self.db_session, p_role_name,
                                    role_hash_password)
            self.logger.info("Role '%s' authentificated." % (role.role_name))
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            sleep(1)
            self.logger.info("Done.")

            return JSONAsyncResult(http_code=200,
                                   data={"message": "OK"},
                                   secure_cookie={
                                       'name':
                                       'temboard',
                                       'content':
                                       gen_cookie(role.role_name,
                                                  role_hash_password)
                                   })

        except (TemboardUIError, Exception) as e:
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            sleep(1)
            return JSONAsyncResult(http_code=401,
                                   data={"error": "Wrong username/password."})
Ejemplo n.º 22
0
    def post_login(self):
        try:
            self.logger.info("Login.")
            p_role_name = self.get_argument('username')
            p_role_password = self.get_argument('password')
            role_hash_password = hash_password(p_role_name, p_role_password)

            self.start_db_session()
            role = get_role_by_auth(self.db_session, p_role_name,
                                    role_hash_password)
            self.logger.info("Role '%s' authentificated." % (role.role_name))
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            sleep(1)
            self.logger.info("Done.")
            return HTMLAsyncResult(
                http_code=302,
                redirection=self.get_secure_cookie('referer_uri') if
                self.get_secure_cookie('referer_uri') is not None else '/home',
                secure_cookie={
                    'name': 'temboard',
                    'content': gen_cookie(role.role_name, role_hash_password)
                })
        except (TemboardUIError, Exception) as e:
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            sleep(1)
            return HTMLAsyncResult(http_code=401,
                                   template_file='login.html',
                                   data={
                                       'nav': False,
                                       'error': 'Wrong username/password.'
                                   })
Ejemplo n.º 23
0
def load_plugins(plugin_names, config):
    """
    Intend to load plugins and run their configuration() function.
    Plugins are defined as a module located in plugins/ directory. Plugins list
    to load is declared into temboard section of the configuration file:
        [temboard]
        plugins = [ "plugin1", "plugin2" ]
    """

    # Get this module's path.
    path = os.path.dirname(os.path.realpath(__file__))
    ret = dict()
    # Get the logger.
    logger = get_logger(config)
    # Loop through declared plugins.
    for plugin_name in plugin_names:
        # Locate and load the module with imp.
        logger.info("Loading plugin '%s'." % (plugin_name, ))
        fp, pathname, description = imp.find_module(plugin_name,
                                                    [path + '/plugins'])
        try:
            module = imp.load_module(plugin_name, fp, pathname, description)
            # Try to run module's configuration() function.
            logger.info("Loading plugin '%s' configuration." % (plugin_name, ))
            ret.update({
                module.__name__: {
                    'configuration': getattr(module, 'configuration')(config),
                    'routes': getattr(module, 'get_routes')(config)
                }
            })
            fp.close()
        except AttributeError as e:
            if fp:
                fp.close()
        except Exception as e:
            logger.traceback(get_tb())
            logger.error(str(e))
    return ret
Ejemplo n.º 24
0
    def get_all(self, group_kind):
        try:
            self.logger.info("Getting group list.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            groups = get_group_list(self.db_session, group_kind)
            self.logger.debug(groups)

            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            self.logger.info("Done.")
            return JSONAsyncResult(
                200, {
                    'groups': [{
                        'name': group.group_name,
                        'kind': group.group_kind,
                        'description': group.group_description
                    } for group in groups],
                    'loaded_plugins':
                    self.application.loaded_plugins
                })
        except (TemboardUIError, Exception) as e:
            self.logger.info("Failed.")
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            try:
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if isinstance(e, TemboardUIError):
                return JSONAsyncResult(e.code, {'error': e.message})
            else:
                return JSONAsyncResult(500, {'error': "Internal error."})
Ejemplo n.º 25
0
    def get_activity(self, agent_address, agent_port):
        try:
            self.logger.info("Getting activity.")
            instance = None
            role = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not activated.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")

            # Load activity.
            activity_data = temboard_activity(self.ssl_ca_cert_file,
                                              instance.agent_address,
                                              instance.agent_port, xsession)
            self.logger.info("Done.")
            return HTMLAsyncResult(http_code=200,
                                   template_path=self.template_path,
                                   template_file='activity.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'activities': activity_data,
                                       'xsession': xsession
                                   })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.expunge_all()
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                if e.code == 401:
                    return HTMLAsyncResult(http_code=401,
                                           redirection="/server/%s/%s/login" %
                                           (agent_address, agent_port))
                elif e.code == 302:
                    return HTMLAsyncResult(http_code=401, redirection="/login")
                code = e.code
            else:
                code = 500
            return HTMLAsyncResult(http_code=code,
                                   template_file='error.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'code': e.code,
                                       'error': e.message
                                   })
Ejemplo n.º 26
0
    def get_dashboard(self, agent_address, agent_port):
        try:
            self.logger.info("Getting dashboard.")
            instance = None
            role = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not active.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()

            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")

            dashboard_history = temboard_dashboard_history(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession)
            if dashboard_history and isinstance(
                    dashboard_history, list) and len(dashboard_history) > 0:
                last_data = dashboard_history[-1]
                history = json.dumps(dashboard_history)
            else:
                # If dashboard history is empty, let's try to get data from the live data source.
                last_data = temboard_dashboard_live(self.ssl_ca_cert_file,
                                                    instance.agent_address,
                                                    instance.agent_port,
                                                    xsession)
                history = ''
            self.logger.info("Done.")
            return HTMLAsyncResult(http_code=200,
                                   template_file='dashboard.html',
                                   template_path=self.template_path,
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'dashboard': last_data,
                                       'history': history,
                                       'buffers_delta': 0,
                                       'readratio':
                                       (100 - last_data['hitratio']),
                                       'xsession': xsession
                                   })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.expunge_all()
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                if e.code == 401:
                    return HTMLAsyncResult(http_code=401,
                                           redirection="/server/%s/%s/login" %
                                           (agent_address, agent_port))
                elif e.code == 302:
                    return HTMLAsyncResult(http_code=401, redirection="/login")
                code = e.code
            else:
                code = 500
            return HTMLAsyncResult(http_code=code,
                                   template_file='error.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'code': e.code,
                                       'error': e.message
                                   })
Ejemplo n.º 27
0
    def post_configuration(self, agent_address, agent_port, category=None):
        try:
            self.logger.info("Posting configuration.")
            instance = None
            role = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not active.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")

            query_filter = self.get_argument('filter', None, True)
            error_code = None
            error_message = None
            post_settings = self.request.arguments
            ret_post = None
            settings = {'settings': []}
            for setting_name, setting_value in post_settings.iteritems():
                # 'filter' is not a setting, just ignore it.
                if setting_name == 'filter':
                    continue
                settings['settings'].append({
                    'name': setting_name,
                    'setting': setting_value[0]
                })
            try:
                # Try to send settings to the agent.
                ret_post = temboard_post_configuration(self.ssl_ca_cert_file,
                                                       instance.agent_address,
                                                       instance.agent_port,
                                                       xsession, settings)
            except TemboardError as e:
                error_code = e.code
                error_message = e.message
            # Get PostgreSQL configuration status: needs restart, reload or is fine.
            configuration_status = temboard_get_configuration_status(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession)
            # Load settings categories.
            configuration_cat = temboard_get_configuration_categories(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession)
            if category == None:
                category = tornado.escape.url_escape(
                    configuration_cat['categories'][0])
            # Load settings depending on the current category or the filter value.
            configuration_data = temboard_get_configuration(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession,
                tornado.escape.url_escape(
                    tornado.escape.url_unescape(category)), query_filter)
            self.logger.info("Done.")
            return HTMLAsyncResult(http_code=200,
                                   template_path=self.template_path,
                                   template_file='configuration.html',
                                   data={
                                       'nav':
                                       True,
                                       'role':
                                       role,
                                       'instance':
                                       instance,
                                       'data':
                                       configuration_data,
                                       'xsession':
                                       xsession,
                                       'current_cat':
                                       tornado.escape.url_unescape(category),
                                       'configuration_categories':
                                       configuration_cat,
                                       'configuration_status':
                                       configuration_status,
                                       'error_code':
                                       error_code,
                                       'error_message':
                                       error_message,
                                       'ret_post':
                                       ret_post,
                                       'query_filter':
                                       query_filter
                                   })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.expunge_all()
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                if e.code == 401:
                    return HTMLAsyncResult(http_code=401,
                                           redirection="/server/%s/%s/login" %
                                           (agent_address, agent_port))
                elif e.code == 302:
                    return HTMLAsyncResult(http_code=401, redirection="/login")
                code = e.code
            else:
                code = 500
            return HTMLAsyncResult(http_code=code,
                                   template_file='error.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'code': e.code,
                                       'error': e.message
                                   })
Ejemplo n.º 28
0
    def get_configuration_file(self, agent_address, agent_port):
        try:
            self.logger.info("Getting configuration (file).")
            instance = None
            role = None
            self.load_auth_cookie()
            self.start_db_session()
            mode = self.get_argument('mode', None)
            version = self.get_argument('version', None)
            role = self.current_user

            if not role:
                raise TemboardUIError(302, "Current role unknown.")
            if mode is None and len(self.available_modes) > 0:
                mode = self.available_modes[0]
            if not (mode in self.available_modes):
                raise TemboardUIError(404, "Editing mode not available.")
            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not active.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")
            file_versions = temboard_get_conf_file_versions(
                self.ssl_ca_cert_file, self.file_type, instance.agent_address,
                instance.agent_port, xsession)
            if mode == 'raw':
                # Load file content.
                conf_file_raw = temboard_get_conf_file_raw(
                    self.ssl_ca_cert_file, self.file_type, version,
                    instance.agent_address, instance.agent_port, xsession)
                self.logger.info("Done.")
                return HTMLAsyncResult(http_code=200,
                                       template_path=self.template_path,
                                       template_file='edit_conf_file_raw.html',
                                       data={
                                           'nav': True,
                                           'role': role,
                                           'instance': instance,
                                           'file_versions': file_versions,
                                           'file_type': self.file_type,
                                           'conf_file_raw': conf_file_raw,
                                           'xsession': xsession
                                       })
            if mode == 'advanced':
                hba_options = None
                if self.file_type == 'hba':
                    hba_options = temboard_get_hba_options(
                        self.ssl_ca_cert_file, instance.agent_address,
                        instance.agent_port, xsession)
                conf_file = temboard_get_conf_file(self.ssl_ca_cert_file,
                                                   self.file_type, version,
                                                   instance.agent_address,
                                                   instance.agent_port,
                                                   xsession)
                self.logger.info("Done.")
                return HTMLAsyncResult(
                    http_code=200,
                    template_path=self.template_path,
                    template_file='edit_conf_file_advanced.html',
                    data={
                        'nav': True,
                        'role': role,
                        'instance': instance,
                        'file_versions': file_versions,
                        'file_type': self.file_type,
                        'conf_file': conf_file,
                        'hba_options': hba_options,
                        'xsession': xsession
                    })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.expunge_all()
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                if e.code == 401:
                    return HTMLAsyncResult(http_code=401,
                                           redirection="/server/%s/%s/login" %
                                           (agent_address, agent_port))
                elif e.code == 302:
                    return HTMLAsyncResult(http_code=401, redirection="/login")
                code = e.code
            else:
                code = 500
            return HTMLAsyncResult(http_code=code,
                                   template_file='error.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'code': e.code,
                                       'error': e.message
                                   })
Ejemplo n.º 29
0
    def get_configuration(self, agent_address, agent_port, category=None):
        try:
            self.logger.info("Getting configuration.")
            instance = None
            role = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not active.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")

            configuration_status = temboard_get_configuration_status(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession)
            configuration_cat = temboard_get_configuration_categories(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession)
            query_filter = self.get_argument('filter', None, True)
            if category == None:
                category = tornado.escape.url_escape(
                    configuration_cat['categories'][0])
            configuration_data = temboard_get_configuration(
                self.ssl_ca_cert_file, instance.agent_address,
                instance.agent_port, xsession,
                tornado.escape.url_escape(
                    tornado.escape.url_unescape(category)), query_filter)
            self.logger.info("Done.")
            return HTMLAsyncResult(http_code=200,
                                   template_path=self.template_path,
                                   template_file='configuration.html',
                                   data={
                                       'nav':
                                       True,
                                       'role':
                                       role,
                                       'instance':
                                       instance,
                                       'data':
                                       configuration_data,
                                       'xsession':
                                       xsession,
                                       'current_cat':
                                       tornado.escape.url_unescape(category),
                                       'configuration_categories':
                                       configuration_cat,
                                       'configuration_status':
                                       configuration_status,
                                       'query_filter':
                                       query_filter
                                   })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.expunge_all()
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                if e.code == 401:
                    return HTMLAsyncResult(http_code=401,
                                           redirection="/server/%s/%s/login" %
                                           (agent_address, agent_port))
                elif e.code == 302:
                    return HTMLAsyncResult(http_code=401, redirection="/login")
                code = e.code
            else:
                code = 500
            return HTMLAsyncResult(http_code=code,
                                   template_file='error.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'code': e.code,
                                       'error': e.message
                                   })
Ejemplo n.º 30
0
    def post_configuration_file(self, agent_address, agent_port):
        error_code = None
        error_message = None
        ret_post = None
        try:
            self.logger.info("Posting configuration (file).")
            instance = None
            role = None

            self.load_auth_cookie()
            self.start_db_session()

            role = self.current_user
            if not role:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance not found.")
            if __name__ not in [
                    plugin.plugin_name for plugin in instance.plugins
            ]:
                raise TemboardUIError(408, "Plugin not active.")
            self.db_session.expunge_all()
            self.db_session.commit()
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if not xsession:
                raise TemboardUIError(401, "Authentication cookie is missing.")
            try:
                # Send file content ..
                ret_post = temboard_post_file_content(
                    self.ssl_ca_cert_file, self.file_type,
                    instance.agent_address, instance.agent_port, xsession, {
                        'content': self.request.arguments['content'][0],
                        'new_version': True
                    })
                # .. and reload configuration.
                ret_post = temboard_post_administration_control(
                    self.ssl_ca_cert_file, instance.agent_address,
                    instance.agent_port, xsession, {'action': 'reload'})
            except (TemboardError, Exception) as e:
                self.logger.traceback(get_tb())
                self.logger.error(str(e))
                if isinstance(TemboardError, e):
                    error_code = e.code
                    error_message = e.message
                else:
                    error_code = 500
                    error_message = "Internale error."
            # Load file content.
            file_content = temboard_get_file_content(self.ssl_ca_cert_file,
                                                     self.file_type,
                                                     instance.agent_address,
                                                     instance.agent_port,
                                                     xsession)
            self.logger.info("Done.")
            return HTMLAsyncResult(http_code=200,
                                   template_path=self.template_path,
                                   template_file='edit_file.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'file_type': self.file_type,
                                       'file_content': file_content,
                                       'error_code': error_code,
                                       'error_message': error_message,
                                       'xsession': xsession,
                                       'ret_post': ret_post
                                   })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.traceback(get_tb())
            self.logger.error(str(e))
            self.logger.info("Failed.")
            try:
                self.db_session.expunge_all()
                self.db_session.rollback()
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                if e.code == 401:
                    return HTMLAsyncResult(http_code=401,
                                           redirection="/server/%s/%s/login" %
                                           (agent_address, agent_port))
                elif e.code == 302:
                    return HTMLAsyncResult(http_code=401, redirection="/login")
                code = e.code
            else:
                code = 500
            return HTMLAsyncResult(http_code=code,
                                   template_file='error.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'code': e.code,
                                       'error': e.message
                                   })