Exemplo n.º 1
0
def get_instance(session, agent_address, agent_port):
    try:
        return session.query(Instances).options(joinedload(
            Instances.groups), joinedload(Instances.plugins)).filter_by(
                agent_address=unicode(agent_address),
                agent_port=agent_port).first()
    except AttributeError as e:
        raise TemboardUIError(
            400,
            "Instance entry '%s:%s' not found." % (agent_address, agent_port))
    except Exception as e:
        raise TemboardUIError(e.message)
Exemplo n.º 2
0
def delete_role_from_group(session, role_name, group_name):
    try:
        role_group = session.query(RoleGroups).filter(
            RoleGroups.group_name == unicode(group_name),
            RoleGroups.role_name == unicode(role_name)).one()
        session.delete(role_group)
    except NoResultFound as e:
        raise TemboardUIError(
            400,
            "Role '%s' not found in group '%s'." % (role_name, group_name))
    except Exception as e:
        raise TemboardUIError(400, e.message)
Exemplo n.º 3
0
def delete_instance(session, agent_address, agent_port):
    try:
        instance = session.query(Instances).filter(
            Instances.agent_address == unicode(agent_address),
            Instances.agent_port == agent_port).one()
        session.delete(instance)
    except NoResultFound as e:
        raise TemboardUIError(
            400, "Instance entry ('%s:%s') not found." %
            (agent_address, agent_port))
    except Exception as e:
        raise TemboardUIError(400, e.message)
Exemplo n.º 4
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.exception(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})
Exemplo n.º 5
0
def update_instance(session,
                    agent_address,
                    agent_port,
                    new_agent_address=None,
                    new_agent_port=None,
                    agent_key=None,
                    hostname=None,
                    cpu=None,
                    memory_size=None,
                    pg_port=None,
                    pg_version=None,
                    pg_data=None):
    try:
        instance = session.query(Instances).filter_by(
            agent_address=unicode(agent_address),
            agent_port=agent_port).first()
        if new_agent_address is not None:
            instance.agent_adresse = unicode(new_agent_address)
        if new_agent_port is not None:
            instance.agent_port = int(new_agent_port)
        if cpu is not None and cpu is not u'':
            instance.cpu = int(cpu)
        else:
            instance.cpu = None
        if memory_size is not None and memory_size is not u'':
            instance.memory_size = int(memory_size)
        else:
            instance.memory_size = None
        if pg_port is not None and pg_port is not u'':
            instance.pg_port = int(pg_port)
        else:
            instance.pg_port = None
        instance.agent_key = unicode(agent_key)
        instance.hostname = unicode(hostname)
        instance.pg_version = unicode(pg_version)
        instance.pg_data = unicode(pg_data)
        session.merge(instance)
        session.flush()
        return instance
    except IntegrityError as e:
        if e.message.find('instances_pkey') > 0:
            raise TemboardUIError(
                400, "Instance entry ('%s:%s') already exists." %
                (agent_address, agent_port))
        else:
            raise TemboardUIError(400, e.message)
    except AttributeError as e:
        raise TemboardUIError(
            400, "Instance entry ('%s:%s') not found." %
            (agent_address, agent_port))
    except Exception as e:
        raise TemboardUIError(400, e.message)
Exemplo n.º 6
0
    def get_state_changes(self, address, port, check_name):
        self.setUp(address, port)

        # Arguments
        start = self.get_argument('start', default=None)
        end = self.get_argument('end', default=None)
        key = self.get_argument('key', default=None)
        if check_name not in check_specs:
            raise TemboardUIError(404, "Unknown check '%s'" % check_name)

        start_time = None
        end_time = None
        if start:
            try:
                start_time = dt_parser.parse(start)
            except ValueError:
                raise TemboardUIError(406, 'Datetime not valid.')
        if end:
            try:
                end_time = dt_parser.parse(end)
            except ValueError:
                raise TemboardUIError(406, 'Datetime not valid.')

        data_buffer = cStringIO.StringIO()
        cur = self.db_session.connection().connection.cursor()
        cur.execute("SET search_path TO monitoring")
        query = """
        COPY (
            SELECT array_to_json(array_agg(json_build_object(
                'datetime', f.datetime,
                'state', f.state,
                'value', f.value,
                'warning', f.warning,
                'critical', f.critical
            ))) FROM get_state_changes(%s, %s, %s, %s, %s, %s) f
        ) TO STDOUT
        """  # noqa
        # build the query
        query = cur.mogrify(query, (self.host_id, self.instance_id, check_name,
                                    key, start_time, end_time))

        cur.copy_expert(query, data_buffer)
        cur.close()
        data = data_buffer.getvalue()
        data_buffer.close()
        try:
            data = json.loads(data)
        except Exception:
            # No data
            data = []

        return JSONAsyncResult(http_code=200, data=data)
Exemplo n.º 7
0
def delete_instance_from_group(session, agent_address, agent_port, group_name):
    try:
        instance_group = session.query(InstanceGroups).filter(
            InstanceGroups.agent_address == unicode(agent_address),
            InstanceGroups.agent_port == agent_port,
            InstanceGroups.group_name == unicode(group_name)).one()
        session.delete(instance_group)
    except NoResultFound as e:
        raise TemboardUIError(
            400, "Instance entry ('%s:%s)' not found in group '%s'." %
            (agent_address, agent_port, group_name))
    except Exception as e:
        raise TemboardUIError(400, e.message)
Exemplo n.º 8
0
    def get_activity_w_b(self, agent_address, agent_port, mode):
        try:
            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.")
            return JSONAsyncResult(http_code=200, data=data_activity)
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.error(e.message)
            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})
Exemplo n.º 9
0
def delete_role_group_from_instance_group(session, role_group_name,
                                          instance_group_name):
    try:
        ari = session.query(AccessRoleInstance).filter(
            AccessRoleInstance.role_group_name == unicode(role_group_name),
            AccessRoleInstance.instance_group_name == unicode(
                instance_group_name)).one()
        session.delete(ari)
    except NoResultFound as e:
        raise TemboardUIError(
            400, "Role group '%s' not found in instance group '%s'." %
            (role_role_name, instance_group_name))
    except Exception as e:
        raise TemboardUIError(400, e.message)
Exemplo n.º 10
0
def get_role_by_auth(session, role_name, role_password):
    try:
        role = session.query(Roles).filter(
            Roles.role_name == unicode(role_name),
            Roles.is_active == True).one()
        if role.role_password != unicode(role_password):
            raise TemboardUIError(
                400, "Wrong user/password: %s/%s" % (role_name, role_password))
        return role
    except NoResultFound as e:
        raise TemboardUIError(
            400, "Wrong user/password: %s/%s" % (role_name, role_password))
    except Exception as e:
        raise TemboardUIError(400, e.message)
Exemplo n.º 11
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})
Exemplo n.º 12
0
def delete_instance(session, agent_address, agent_port):
    from temboardui.plugins.monitoring.model.orm import (
        Host as MonitoringHost,
        Instance as MonitoringInstance,
    )

    try:
        instance = session.query(Instances).filter(
            Instances.agent_address == unicode(agent_address),
            Instances.agent_port == agent_port).one()
        session.delete(instance)
    except NoResultFound as e:
        raise TemboardUIError(
            400, "Instance entry ('%s:%s') not found." %
            (agent_address, agent_port))
    except Exception as e:
        raise TemboardUIError(400, e.message)

    # Also delete any monitoring data
    # First all instance data
    try:
        monitoring_instance = session.query(MonitoringInstance) \
            .join(MonitoringHost) \
            .filter(
                MonitoringHost.hostname == instance.hostname,
                MonitoringInstance.port == instance.pg_port).one()
        session.delete(monitoring_instance)
    except NoResultFound as e:
        pass
    except Exception as e:
        raise TemboardUIError(400, e.message)

    # Then delete host data if there's no instance left referenced for this
    # host
    count = session.query(MonitoringInstance.instance_id) \
        .join(MonitoringHost) \
        .filter(MonitoringHost.hostname == instance.hostname) \
        .count()
    if count == 0:
        # Using bulk delete query here to prevent errors on not null constraint
        # on checks::host_id column (ON CASCADE DELETE not working)
        # when using session.delete(host)
        try:
            session.query(MonitoringHost) \
                .filter(MonitoringHost.hostname == instance.hostname) \
                .delete()
        except NoResultFound as e:
            pass
        except Exception as e:
            raise TemboardUIError(400, e.message)
Exemplo n.º 13
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})
Exemplo n.º 14
0
    def delete_role(self):
        try:
            self.logger.info("Deleting role.")
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            data = tornado.escape.json_decode(self.request.body)
            self.logger.debug(data)

            if 'username' not in data or data['username'] == '':
                raise TemboardUIError(400, "Username field is missing.")
            delete_role(self.db_session, data['username'])
            self.db_session.commit()
            self.db_session.close()
            self.logger.info("Done.")
            return JSONAsyncResult(200, {'delete': True})

        except (TemboardUIError, Exception) as e:
            self.logger.exception(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."})
Exemplo n.º 15
0
def send_mail(host,
              port,
              subject,
              content,
              emails,
              tls=False,
              login=None,
              password=None,
              from_addr=None):

    msg = MIMEText(content, 'plain', 'utf-8')
    msg['Subject'] = subject

    try:
        if not tls:
            smtp = SMTP(host, port)
        else:
            smtp = SMTP_SSL(host, port)

        if login is not None and password is not None:
            smtp.login(login, password)

        smtp.sendmail(from_addr, emails, msg.as_string())
        smtp.quit()
    except Exception as e:
        raise TemboardUIError(
            500, "Could not send mail; %s\n"
            "SMTP server may be misconfigured." % e)
Exemplo n.º 16
0
def check_group_description(group_description):
    if len(group_description) > 255:
        raise TemboardUIError(
            400,
            "Invalid group description, must be a 256 char (max) length "
            "string."
        )
Exemplo n.º 17
0
    def get_dashboard(self, agent_address, agent_port):
        self.logger.info("Getting dashboard.")

        self.setUp(agent_address, agent_port)
        self.check_active_plugin(__name__)

        xsession = self.get_secure_cookie("temboard_%s_%s" %
                                          (agent_address, agent_port))
        if not xsession:
            raise TemboardUIError(401, "Authentication cookie is missing.")
        else:
            data_profile = temboard_profile(self.ssl_ca_cert_file,
                                            agent_address, agent_port,
                                            xsession)
            agent_username = data_profile['username']

        try:
            config = temboard_dashboard_config(
                self.ssl_ca_cert_file, agent_address, agent_port, xsession)
        except TemboardError as e:
            # Agent may not be able to send config (old agent)
            # Use a default one
            if e.code == 404:
                config = {
                    'history_length': 150,
                    'scheduler_interval': 2
                }
            else:
                raise e

        dashboard_history = temboard_dashboard_history(
            self.ssl_ca_cert_file, agent_address, 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, agent_address, 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': self.current_user,
                'instance': self.instance,
                'plugin': __name__,
                'dashboard': last_data,
                'config': json.dumps(config),
                'history': history,
                'buffers_delta': 0,
                'readratio': (100 - last_data['hitratio']),
                'xsession': xsession,
                'agent_username': agent_username,
            })
Exemplo n.º 18
0
def get_group(session, group_name, group_kind):
    try:
        if group_kind == 'role':
            return session.query(Groups).filter_by(
                group_name=unicode(group_name),
                group_kind=unicode(group_kind)).one()
        else:
            return session.query(Groups).options(
                joinedload(Groups.ari)).filter(
                    Groups.group_name == unicode(group_name),
                    Groups.group_kind == unicode(group_kind)).one()
    except AttributeError as e:
        raise TemboardUIError(
            400, "Group '%s' (%s) not found." % (group_name, group_kind))
    except Exception as e:
        raise TemboardUIError(e.message)
Exemplo n.º 19
0
    def delete_instance(self):
        self.logger.info("Deleting instance.")
        self.setUp()
        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.tearDown()
        self.logger.info("Done.")
        return JSONAsyncResult(200, {'delete': True})
Exemplo n.º 20
0
def send_sms(config, content, phones):
    sid = config.twilio_account_sid
    token = config.twilio_auth_token
    from_ = config.twilio_from
    uri = 'https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json' % sid
    s = base64.b64encode('%s:%s' % (sid, token))

    errors = []
    for recipient in phones:
        req = urllib2.Request(url=uri)
        req.add_header('Authorization', 'Basic %s' % s)
        data = {'From': from_, 'Body': content, 'To': recipient}
        req.add_data(urllib.urlencode(data))
        try:
            urllib2.urlopen(req)
        except urllib2.HTTPError as e:
            response = json.loads(e.read())
            logger.error("Could not send SMS; %s" % response.get('message'))
            errors.append(recipient)
        except Exception as e:
            logger.error("Could not send SMS; %s" % e)
            errors.append(recipient)

    if errors:
        raise TemboardUIError(
            500,
            "Could not send SMS to %s; \n See logs for more information" %
            ', '.join(errors))
Exemplo n.º 21
0
    def get_notifications(self, agent_address, agent_port):
        self.logger.info("Getting notifications.")

        self.setUp(agent_address, agent_port)

        xsession = self.get_secure_cookie("temboard_%s_%s" %
                                          (agent_address, agent_port))
        if not xsession:
            raise TemboardUIError(401, "Authentication cookie is missing.")
        else:
            data_profile = temboard_profile(self.ssl_ca_cert_file,
                                            agent_address, agent_port,
                                            xsession)
            agent_username = data_profile['username']

        # Load notifications.
        notifications = temboard_get_notifications(self.ssl_ca_cert_file,
                                                   agent_address, agent_port,
                                                   xsession)
        self.tearDown(commit=False)
        self.logger.info("Done.")
        return HTMLAsyncResult(http_code=200,
                               template_file='notifications.html',
                               data={
                                   'nav': True,
                                   'role': self.current_user,
                                   'instance': self.instance,
                                   'plugin': 'notifications',
                                   'notifications': notifications,
                                   'xsession': xsession,
                                   'agent_username': agent_username,
                               })
Exemplo n.º 22
0
    def get_configuration_file(self, agent_address, agent_port):
        self.logger.info("Getting configuration (file).")

        self.setUp(agent_address, agent_port)
        self.check_active_plugin(__name__)

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

        # Load file content.
        file_content = temboard_get_file_content(self.ssl_ca_cert_file,
                                                 self.file_type, agent_address,
                                                 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': self.current_user,
                                   'instance': self.instance,
                                   'plugin': __name__,
                                   'file_type': self.file_type,
                                   'file_content': file_content,
                                   'xsession': xsession
                               })
Exemplo n.º 23
0
def check_group_name(group_name):
    p_group_name = r'^([a-z0-9_\-.]{3,16})$'
    r_group_name = re.compile(p_group_name)
    if not r_group_name.match(group_name):
        raise TemboardUIError(
            400, "Invalid group name, must satisfy this regexp pattern: %s" %
            (p_group_name))
Exemplo n.º 24
0
    def delete_group(self, group_kind):
        try:
            self.load_auth_cookie()
            self.start_db_session()
            self.check_admin()

            data = tornado.escape.json_decode(self.request.body)
            if 'group_name' not in data or data['group_name'] == '':
                raise TemboardUIError(400, "Group name field is missing.")
            delete_group(self.db_session, data['group_name'], group_kind)
            self.db_session.commit()
            self.db_session.close()
            return JSONAsyncResult(200, {'delete': True})

        except (TemboardUIError, Exception) as e:
            self.logger.error(e.message)
            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."})
Exemplo n.º 25
0
    def get_activity(self, agent_address, agent_port, mode):
        self.logger.info("Getting activity.")

        self.setUp(agent_address, agent_port)
        self.check_active_plugin(__name__)

        xsession = self.get_secure_cookie("temboard_%s_%s" %
                                          (agent_address, agent_port))
        if not xsession:
            raise TemboardUIError(401, "Authentication cookie is missing.")
        else:
            data_profile = temboard_profile(self.ssl_ca_cert_file,
                                            agent_address, agent_port,
                                            xsession)
            agent_username = data_profile['username']

        self.logger.info("Done.")
        return HTMLAsyncResult(http_code=200,
                               template_path=self.template_path,
                               template_file='activity.html',
                               data={
                                   'nav': True,
                                   'role': self.current_user,
                                   'instance': self.instance,
                                   'plugin': __name__,
                                   'mode': mode,
                                   'xsession': xsession,
                                   'agent_username': agent_username,
                               })
Exemplo n.º 26
0
    def get_activity(self, agent_address, agent_port, mode):
        self.logger.info("Getting activity (proxy).")

        self.setUp(agent_address, agent_port)
        self.check_active_plugin(__name__)

        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,
                                                      agent_address,
                                                      agent_port, xsession)
        elif mode == 'blocking':
            data_activity = temboard_activity_blocking(self.ssl_ca_cert_file,
                                                       agent_address,
                                                       agent_port, xsession)
        else:
            data_activity = temboard_activity(self.ssl_ca_cert_file,
                                              agent_address, agent_port,
                                              xsession)
        self.logger.info("Done.")
        return JSONAsyncResult(http_code=200, data=data_activity)
Exemplo n.º 27
0
    def get_hba_options(self, agent_address, agent_port):
        try:
            self.logger.info("Getting HBA options (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')

            hba_options = temboard_get_hba_options(self.ssl_ca_cert_file,
                                                   instance.agent_address,
                                                   instance.agent_port,
                                                   xsession)
            self.logger.info("Done.")
            return JSONAsyncResult(http_code=200, data=hba_options)
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.exception(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})
Exemplo n.º 28
0
    def get_login(self, agent_address, agent_port):
        try:
            instance = None
            role = None
            agent_username = None
            self.start_db_session()
            try:
                self.load_auth_cookie()
                role = self.current_user
            except Exception as e:
                pass
            if role is None:
                raise TemboardUIError(302, "Current role unknown.")

            instance = get_instance(self.db_session, agent_address, agent_port)
            self.db_session.close()
            xsession = self.get_secure_cookie(
                "temboard_%s_%s" %
                (instance.agent_address, instance.agent_port))
            if xsession:
                try:
                    data_profile = temboard_profile(self.ssl_ca_cert_file,
                                                    instance.agent_address,
                                                    instance.agent_port,
                                                    xsession)
                    agent_username = data_profile['username']
                    self.logger.error(agent_username)
                except Exception as e:
                    self.logger.exception(str(e))

            return HTMLAsyncResult(http_code=200,
                                   template_file='agent-login.html',
                                   data={
                                       'nav': True,
                                       'instance': instance,
                                       'role': role,
                                       'username': agent_username
                                   })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.exception(str(e))
            try:
                self.db_session.close()
            except Exception as e:
                pass
            if (isinstance(e, TemboardUIError)
                    or isinstance(e, TemboardError)):
                if 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,
                                       'instance': instance,
                                       'code': str(e.code),
                                       'message': str(e.message)
                                   })
Exemplo n.º 29
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."})
Exemplo n.º 30
0
 def load_auth_cookie(self,):
     """
     Try to load secure cookie content.
     """
     cookie_content = self.get_secure_cookie('temboard')
     if cookie_content is None:
         raise TemboardUIError(302, "Authentication cookie is missing.")
     self.auth_cookie = cookie_content