Esempio n. 1
0
    def get_notifications(self, agent_address, agent_port):
        try:
            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.")
            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 notifications.
            notifications = temboard_get_notifications(self.ssl_ca_cert_file, instance.agent_address, instance.agent_port, xsession)
            return HTMLAsyncResult(
                    http_code = 200,
                    template_file = 'notifications.html',
                    data = {
                        'nav': True,
                        'role': role,
                        'instance': instance,
                        'notifications': notifications,
                        'xsession': xsession
                    })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.error(e.message)
            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
                        })
Esempio n. 2
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)
                                   })
Esempio n. 3
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})
Esempio 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.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})
Esempio n. 5
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})
Esempio n. 6
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
                                   })
Esempio n. 7
0
 def setUp(self, address=None, port=None):
     '''
     Start DB Session.
     Get instance and ensure that it exists.
     Authenticate user.
     '''
     self.start_db_session()
     self.load_auth_cookie()
     if not self.current_user:
         raise TemboardUIError(302, "Current role unknown.")
     self.role = self.current_user
     if address is not None and port is not None:
         self.instance = get_instance(self.db_session, address, port)
         self.require_instance()
Esempio n. 8
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})
Esempio n. 9
0
    def get_activity(self, agent_address, agent_port):
        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')

            data_activity = temboard_activity(self.ssl_ca_cert_file,
                                              instance.agent_address,
                                              instance.agent_port, xsession)
            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})
Esempio n. 10
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
                                   })
Esempio n. 11
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.")
            else:
                data_profile = temboard_profile(self.ssl_ca_cert_file,
                                                instance.agent_address,
                                                instance.agent_port, xsession)
                agent_username = data_profile['username']

            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,
                                       'plugin': 'dashboard',
                                       'dashboard': last_data,
                                       'history': history,
                                       'buffers_delta': 0,
                                       'readratio':
                                       (100 - last_data['hitratio']),
                                       'xsession': xsession,
                                       'agent_username': agent_username,
                                   })
        except (TemboardUIError, TemboardError, Exception) as e:
            self.logger.exception(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
                                   })
Esempio n. 12
0
    def get_index(self, agent_address, agent_port):
        try:
            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))

            # Here we want to get the current agent username if a session
            # already exists.
            # Monitoring plugin doesn't require agent authentication since we
            # already have the data.
            # Don't fail if there's a session error (for example when the agent
            # has been restarted)
            agent_username = None
            try:
                if xsession:
                    data_profile = temboard_profile(self.ssl_ca_cert_file,
                                                    instance.agent_address,
                                                    instance.agent_port,
                                                    xsession)
                    agent_username = data_profile['username']
            except TemboardError:
                pass

            return HTMLAsyncResult(http_code=200,
                                   template_path=self.template_path,
                                   template_file='index.html',
                                   data={
                                       'nav': True,
                                       'role': role,
                                       'instance': instance,
                                       'plugin': 'monitoring',
                                       'agent_username': agent_username
                                   })

        except (TemboardUIError, Exception) as e:
            self.logger.exception(str(e))
            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(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
                                   })
Esempio n. 13
0
    def get_data_probe(self, agent_address, agent_port, probe_name):
        try:
            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.")

            # Find host_id & instance_id
            host_id = get_host_id(self.db_session, instance.hostname)
            instance_id = get_instance_id(self.db_session, host_id,
                                          instance.pg_port)

            self.db_session.expunge_all()

            start = self.get_argument('start', default=None)
            end = self.get_argument('end', default=None)
            start_time = None
            end_time = None
            if start:
                try:
                    start_time = dateutil.parser.parse(start)
                except ValueError as e:
                    raise TemboardUIError(406, 'Datetime not valid.')
            if end:
                try:
                    end_time = dateutil.parser.parse(end)
                except ValueError as e:
                    raise TemboardUIError(406, 'Datetime not valid.')

            if probe_name == 'loadavg':
                interval = self.get_argument('interval', default='all')
                if interval not in ['load1', 'load5', 'load15', 'all']:
                    raise TemboardUIError(400, 'Interval not available')
                data = get_loadaverage(self.db_session, host_id, start_time,
                                       end_time, interval)
            elif probe_name == 'db_size':
                data = get_db_size(self.db_session, instance_id, start_time,
                                   end_time)
            elif probe_name == 'cpu':
                data = get_cpu(self.db_session, host_id, start_time, end_time)
            elif probe_name == 'tps':
                data = get_tps(self.db_session, instance_id, start_time,
                               end_time)
            elif probe_name == 'memory':
                data = get_memory(self.db_session, host_id, start_time,
                                  end_time)
            elif probe_name == 'swap':
                data = get_swap(self.db_session, host_id, start_time, end_time)
            elif probe_name == 'ctxforks':
                data = get_ctxforks(self.db_session, host_id, start_time,
                                    end_time)
            elif probe_name == 'sessions':
                data = get_sessions(self.db_session, instance_id, start_time,
                                    end_time)
            elif probe_name == 'blocks':
                data = get_blocks(self.db_session, instance_id, start_time,
                                  end_time)
            elif probe_name == 'hitreadratio':
                data = get_hitreadratio(self.db_session, instance_id,
                                        start_time, end_time)
            elif probe_name == 'checkpoints':
                data = get_checkpoints(self.db_session, instance_id,
                                       start_time, end_time)
            elif probe_name == 'w_buffers':
                data = get_written_buffers(self.db_session, host_id,
                                           start_time, end_time)
            elif probe_name == 'instance_size':
                data = get_instance_size(self.db_session, instance_id,
                                         start_time, end_time)
            elif probe_name == 'locks':
                data = get_locks(self.db_session, instance_id, start_time,
                                 end_time)
            elif probe_name == 'waiting_locks':
                data = get_waiting_locks(self.db_session, instance_id,
                                         start_time, end_time)
            elif probe_name == 'fs_size':
                data = get_fs_size(self.db_session, host_id, start_time,
                                   end_time)
            elif probe_name == 'fs_usage':
                data = get_fs_usage(self.db_session, host_id, start_time,
                                    end_time)
            elif probe_name == 'tblspc_size':
                data = get_tblspc_size(self.db_session, instance_id,
                                       start_time, end_time)
            elif probe_name == 'wal_files_size':
                data = get_wal_files_size(self.db_session, instance_id,
                                          start_time, end_time)
            elif probe_name == 'wal_files_count':
                data = get_wal_files_count(self.db_session, instance_id,
                                           start_time, end_time)
            elif probe_name == 'wal_files_rate':
                data = get_wal_files_rate(self.db_session, instance_id,
                                          start_time, end_time)
            else:
                raise TemboardUIError(404, 'Unknown probe.')

            self.db_session.commit()
            self.db_session.close()

            return CSVAsyncResult(http_code=200, data=data)
        except (TemboardUIError, Exception) as e:
            self.logger.exception(str(e))
            try:
                self.db_session.close()
            except Exception:
                pass
            if (isinstance(e, TemboardUIError)):
                return CSVAsyncResult(http_code=e.code,
                                      data={'error': e.message})
            else:
                return CSVAsyncResult(http_code=500, data={'error': e.message})
Esempio n. 14
0
    def post_instance(self, agent_address, agent_port):
        self.logger.info("Posting instance.")
        self.setUp()
        instance = None
        self.check_admin()
        if agent_address and agent_port:
            # Update instance case.
            instance = get_instance(self.db_session, agent_address, agent_port)
            if not instance:
                raise TemboardUIError(404, "Instance entry not found.")

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

        # Submited attributes checking.
        if 'new_agent_address' not in data or \
           data['new_agent_address'] == '':
            raise TemboardUIError(400, "Agent address is missing.")
        if 'new_agent_port' not in data or data['new_agent_port'] == '':
            raise TemboardUIError(400, "Agent port is missing.")
        if 'agent_key' not in data:
            raise TemboardUIError(400, "Agent key field is missing.")
        if 'hostname' not in data:
            raise TemboardUIError(400, "Hostname field is missing.")
        if 'cpu' not in data:
            raise TemboardUIError(400, "CPU field is missing.")
        if 'memory_size' not in data:
            raise TemboardUIError(400, "Memory size field is missing.")
        if 'pg_port' not in data:
            raise TemboardUIError(400, "PostgreSQL port field is missing.")
        if 'pg_version' not in data:
            raise TemboardUIError(400, "PostgreSQL version field is missing.")
        if 'pg_data' not in data:
            raise TemboardUIError(
                400, "PostgreSQL data directory field is missing.")
        if 'groups' not in data:
            raise TemboardUIError(400, "Groups field is missing.")
        if data['groups'] is not None and type(data['groups']) != list:
            raise TemboardUIError(400, "Invalid group list.")
        check_agent_address(data['new_agent_address'])
        check_agent_port(data['new_agent_port'])

        # At this point we can proceed with DB operations.
        # Update instance case.
        if instance:
            # First step is to remove the instance from the groups it
            # belongs to.
            instance_groups = get_groups_by_instance(self.db_session,
                                                     instance.agent_address,
                                                     instance.agent_port)
            if instance_groups:
                for instance_group in instance_groups:
                    delete_instance_from_group(self.db_session,
                                               instance.agent_address,
                                               instance.agent_port,
                                               instance_group.group_name)
            # Remove plugins
            purge_instance_plugins(self.db_session, instance.agent_address,
                                   instance.agent_port)

            instance = update_instance(
                self.db_session, instance.agent_address, instance.agent_port,
                data['new_agent_address'], data['new_agent_port'],
                data['agent_key'], data['hostname'], data['cpu'],
                data['memory_size'], data['pg_port'], data['pg_version'],
                data['pg_data'])
        # New instance case.
        else:
            instance = add_instance(self.db_session, data['new_agent_address'],
                                    data['new_agent_port'], data['hostname'],
                                    data['agent_key'], data['cpu'],
                                    data['memory_size'], data['pg_port'],
                                    data['pg_version'], data['pg_data'])

        # Add user into the new groups.
        if data['groups']:
            for group_name in data['groups']:
                add_instance_in_group(self.db_session, instance.agent_address,
                                      instance.agent_port, group_name)
        # Add each selected plugin.
        if data['plugins']:
            for plugin_name in data['plugins']:
                # 'administration' plugin case: the plugin is not currently
                # implemented on UI side
                if plugin_name != 'administration':
                    if plugin_name in self.application.loaded_plugins:
                        add_instance_plugin(self.db_session,
                                            instance.agent_address,
                                            instance.agent_port, plugin_name)
                    else:
                        raise TemboardUIError(
                            404, "Unknown plugin %s." % (plugin_name))
        self.tearDown()
        self.logger.info("Done.")
        return JSONAsyncResult(200, {"message": "OK"})
Esempio n. 15
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
                                   })
Esempio n. 16
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
                                   })
Esempio n. 17
0
    def get_index(self, agent_address, agent_port, period):
        try:
            instance = None
            role = None
            delta = 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()

            if period == 'day':
                delta = timedelta(hours=24)
            elif period == 'week':
                delta = timedelta(days=7)
            elif period == 'month':
                delta = timedelta(days=31)
            elif period == 'year':
                delta = timedelta(days=365)
            elif period == 'interval':
                start = self.get_argument('start', default=None)
                end = self.get_argument('end', default=None)
                try:
                    start_date = datetime.datetime.strptime(start, '%Y-%m-%dT%H:%M:%S')
                    end_date = datetime.datetime.strptime(end, '%Y-%m-%dT%H:%M:%S')
                except Exception as e:
                    raise TemboardUIError(406, 'Datetime not valid.')
            else:
                raise TemboardUIError(500, "Unknown period.")

            if period != 'interval':
                start_date = datetime.datetime.now() - delta
                end_date = datetime.datetime.now()
            return HTMLAsyncResult(
                    http_code = 200,
                    template_path = self.template_path,
                    template_file = 'index.html',
                    data = {
                        'nav': True,
                        'role': role,
                        'instance': instance,
                        'period': period,
                        'start_date': start_date.strftime('%Y-%m-%dT%H:%M:%S'),
                        'end_date': end_date.strftime('%Y-%m-%dT%H:%M:%S')
                    })

        except (TemboardUIError, Exception) as e:
            self.logger.error(e.message)
            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(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
                        })
Esempio n. 18
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
                                   })
Esempio n. 19
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
                                   })