def hosts_edit(): host_id = request.form.get("host-id") name = request.form.get("name") host = request.form.get("host") description = request.form.get("description") auth_key = request.form.get("auth-key") check_certificate = bool(request.form.get("check-certificate")) if not (name and host and auth_key): return error_response("Name, host and auth key are required") hosts = Host.query.filter(and_(or_(Host.name == name, Host.host == host), Host.id != host_id)).count() if hosts: return error_response("A host with that name or host already exists") h = Host.query.get(host_id) if not h: return error_response("Host could not be found!") success, message = test_agent_connection(host, auth_key, check_certificate) if not success: return error_response(message) h.id = host_id h.name = name h.host = host h.description = description h.auth_key = auth_key h.check_certificate = check_certificate session.commit() return jsonify(success=True, message="Host has been saved successfully")
def checks_add(): name = request.form.get("name") description = request.form.get("description") host_groups = request.form.getlist("host-groups[]") hosts = request.form.getlist("hosts[]") plugins = request.form.getlist("plugins[]") if not name: return error_response("You must supply a name for this check") c = Check(name=name, description=description) session.add(c) session.flush() for host_id in hosts: ca = CheckAssignment(host_id=host_id, check_id=c.id) session.add(ca) for host_group_id in host_groups: ca = CheckAssignment(host_group_id=host_group_id, check_id=c.id) session.add(ca) for plugin_id in plugins: cp = CheckPlugin(plugin_id=plugin_id, check_id=c.id) session.add(cp) session.commit() return jsonify(success=True, message="Check has been added successfully!")
def scheduling_add(): name = request.form.get("name") description = request.form.get("description") interval_starts = request.form.getlist("interval-start[]") interval_values = request.form.getlist("interval-value[]") interval_units = request.form.getlist("interval-unit[]") checks = request.form.getlist("checks[]") if not name: return error_response("You must supply a name for this schedule") s = Schedule(name=name, description=description) session.add(s) session.flush() for check_id in checks: sc = ScheduleCheck(check_id=check_id, schedule_id=s.id) session.add(sc) for interval in zip(interval_starts, interval_values, interval_units): try: start_timestamp = datetime.strptime(interval[0], "%Y-%m-%d %H:%M:%S") except ValueError: return error_response("Start timestamp for interval was not " "understood") si = ScheduleInterval(schedule_id=s.id, start_timestamp=start_timestamp) try: si.set_interval(int(interval[1]), interval[2]) except ValueError: return error_response("Interval must be an integer") session.add(si) session.commit() return jsonify(success=True, message="Schedule has been added successfully")
def setUp(self): session.commit() drop_all() create_all() session.add(Host(id=1)) # Contains alerts 1,2,4 session.add(Host(id=2)) # Contains alert 6,7 for i in range(1,8): session.add(Alert(id=i, name=i)) session.add(HostGroup(id=1)) session.add(HostGroup(id=2)) session.add(HostGroupAssignment(member_host_id=1, host_group_id=1)) session.add(Service(id=1)) session.add(Service(id=2)) session.add(Service(id=3)) session.add(ServiceDependency(host_id=1, service_id=1)) session.add(RedundancyGroup(id=1, service_id=3)) session.add(RedundancyGroupComponent(host_id=2, redundancy_group_id=1)) session.add(ServiceDependency(redundancy_group_id=1, service_id=3)) session.add(AlertCheckEntity(host_id=1, alert_id=1)) session.add(AlertCheckEntity(host_group_id=1, alert_id=2)) session.add(AlertCheckEntity(host_group_id=2, alert_id=3)) session.add(AlertCheckEntity(service_id=1, alert_id=4)) session.add(AlertCheckEntity(service_id=2, alert_id=5)) session.add(AlertCheckEntity(host_id=2, alert_id=6)) session.add(AlertCheckEntity(service_id=3, alert_id=7)) session.commit()
def setUp(self): session.commit() drop_all() create_all() session.add(Host(id=1)) # Contains alerts 1,2,4 session.add(Host(id=2)) # Contains alert 6,7 for i in range(1, 8): session.add(Alert(id=i, name=i)) session.add(HostGroup(id=1)) session.add(HostGroup(id=2)) session.add(HostGroupAssignment(member_host_id=1, host_group_id=1)) session.add(Service(id=1)) session.add(Service(id=2)) session.add(Service(id=3)) session.add(ServiceDependency(host_id=1, service_id=1)) session.add(RedundancyGroup(id=1, service_id=3)) session.add(RedundancyGroupComponent(host_id=2, redundancy_group_id=1)) session.add(ServiceDependency(redundancy_group_id=1, service_id=3)) session.add(AlertCheckEntity(host_id=1, alert_id=1)) session.add(AlertCheckEntity(host_group_id=1, alert_id=2)) session.add(AlertCheckEntity(host_group_id=2, alert_id=3)) session.add(AlertCheckEntity(service_id=1, alert_id=4)) session.add(AlertCheckEntity(service_id=2, alert_id=5)) session.add(AlertCheckEntity(host_id=2, alert_id=6)) session.add(AlertCheckEntity(service_id=3, alert_id=7)) session.commit()
def users_add(): username = request.form.get("username") email = request.form.get("email") first_name = request.form.get("first-name") last_name = request.form.get("last-name") password = request.form.get("password") confirm_password = request.form.get("confirm-password") if not (username.strip() and email.strip() and first_name.strip() and \ last_name.strip() and password.strip() and confirm_password.strip()): return error_response("All fields are required") if password != confirm_password: return error_response("Passwords do not match") if User.query.filter(User.username==username).count(): return error_response("A user with that username already exists") password_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()) u = User(username=username, first_name=first_name, last_name=last_name, password_hash=password_hash.decode("utf-8"), email=email) session.add(u) session.commit() return jsonify(success=True, message="User has been added successfully!")
def host_groups_add(): name = request.form.get("name") description = request.form.get("description") hosts = request.form.getlist("hosts[]") host_groups = request.form.getlist("host-groups[]") if not name: return error_response("You must supply a name for this group") groups = HostGroup.query.filter(HostGroup.name == name).count() if groups: return error_response("A group with that name already exists") host_group = HostGroup(name=name, description=description) session.add(host_group) session.flush() for host in hosts: a = HostGroupAssignment(host_group_id=host_group.id, member_host_id=host) session.add(a) for group in host_groups: a = HostGroupAssignment(host_group_id=host_group.id, member_host_group_id=group) session.add(a) session.commit() return jsonify(success=True, message="Host Group added successfully")
def users_edit(): username = request.form.get("username") email = request.form.get("email") first_name = request.form.get("first-name") last_name = request.form.get("last-name") password = request.form.get("password") confirm_password = request.form.get("confirm-password") user_id = request.form.get("user-id") if not (username.strip() and email.strip() and first_name.strip() and last_name.strip()): return error_response("Username, email, first name and last name " "are required") if password != confirm_password: return error_response("Passwords do not match") if User.query.filter(User.username == username).filter(User.id != user_id).count(): return error_response("A user with that username already exists") u = User.query.get(user_id) if not u: return error_response("User could not be found!") u.username = username u.email = email u.first_name = first_name u.last_name = last_name if password: u.password_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") session.commit() return jsonify(success=True, message="User has been saved successfully!")
def host_groups_edit(): host_group_id = request.form.get("host-group-id") name = request.form.get("name") description = request.form.get("description") hosts = request.form.getlist("hosts[]") host_groups = request.form.getlist("host-groups[]") if not name: return error_response("You must supply a name for this group") groups = HostGroup.query.filter(and_(HostGroup.name == name, HostGroup.id != host_group_id)).count() if groups: return error_response("A group with that name already exists") g = HostGroup.query.get(host_group_id) if not g: return error_response("Host Group could not be found!") g.name = name g.description = description # Remove all current assignments, they will be replaced with the new ones HostGroupAssignment.query.filter(HostGroupAssignment.host_group_id == host_group_id).delete() for host in hosts: a = HostGroupAssignment(host_group_id=host_group_id, member_host_id=host) session.add(a) for group in host_groups: a = HostGroupAssignment(host_group_id=host_group_id, member_host_group_id=group) session.add(a) session.commit() return jsonify(success=True, message="Host Group has been saved successfully")
def alerts_add(): name = request.form.get("name") entity_selection = request.form.get("entity-selection") host_groups = request.form.getlist("host-groups[]") hosts = request.form.getlist("hosts[]") checks = request.form.getlist("checks[]") services = request.form.getlist("services[]") plugins = request.form.getlist("plugins[]") from_states = request.form.getlist("from-states[]") to_states = request.form.getlist("to-states[]") module_selection = request.form.get("module-selection") if not name: return error_response("You must specify a name for this alert") if not from_states or not to_states: return error_response("You must specify at least one from state and at " "least one to state") if not module_selection: return error_response("You must select a module to use for this alert") alert = Alert(name=name, entity_selection_type=entity_selection, module=module_selection) session.add(alert) session.flush() for state in to_states: session.add(AlertTransitionTo(alert_id=alert.id, state=state)) for state in from_states: session.add(AlertTransitionFrom(alert_id=alert.id, state=state)) if entity_selection == "custom": added_entity = False for host_id in hosts: session.add(AlertCheckEntity(alert_id=alert.id, host_id=host_id)) added_entity = True for host_group_id in host_groups: session.add(AlertCheckEntity(alert_id=alert.id, host_group_id=host_group_id)) added_entity = True for service_id in services: session.add(AlertCheckEntity(alert_id=alert.id, service_id=service_id)) added_entity = True if not added_entity: session.rollback() return error_response("You must select at least one entity to alert" " for state changes in") for check_id in checks: session.add(AlertRestrictToEntity(alert_id=alert.id, check_id=check_id)) for plugin_id in plugins: session.add(AlertRestrictToEntity(alert_id=alert.id, plugin_id=plugin_id)) for key in request.form.keys(): if key.startswith("module-option-"): option_key = key.replace("module-option-", "", 1) option_value = request.form.get(key) session.add(AlertModuleOption(alert_id=alert.id, key=option_key, value=option_value)) session.commit() return jsonify(success=True, message="Alert has been added successfully")
def alerts_delete(): alert_id = request.form.get("alert-id") alert = Alert.query.get(alert_id) if not alert: return error_response("Alert could not be found!") session.delete(alert) session.commit() return jsonify(success=True, message="Alert has been deleted successfully")
def perform_check(host, plugin, check_id): a = Agent(host.host, host.auth_key, verify_certs=host.check_certificate) error = None result_type = "plugin" try: update_required = a.check_plugin_verison(plugin.id, plugin.version) if update_required: plugin_file = os.path.join(get_config_value(config, "plugin_repo"), plugin.archive_file) if plugin.signature_file: signature_file = os.path.join( get_config_value(config, "plugin_repo"), plugin.signature_file) with open(plugin_file, "rb") as pf: if plugin.signature_file: with open(signature_file, "rb") as sf: a.update_plugin(plugin.id, pf, sf) else: a.update_plugin(plugin.id, pf) (value, message) = a.get_plugin_data(plugin.id) except CommandUnsuccessfulError as e: error = "CommandUnsuccessfulError: {}".format(str(e)) result_type = "command_unsuccessful" except AuthenticationError as e: error = "AuthenticationError: {}".format(str(e)) result_type = "authentication_error" except RequestError as e: error = "RequestError: {}".format(str(e)) result_type = "request_error" except ConnectionError as e: error = "ConnectionError: {}".format(str(e)) result_type = "connection_error" except Timeout as e: error = "Timeout: {}".format(str(e)) result_type = "connection_timeout" if error: log_message("Dispatcher", error) message = error value = None old_health = Host.query.get(host.id).health pr = PluginResult(host_id=host.id, plugin_id=plugin.id, check_id=check_id, value=value, message=message, result_type=result_type, timestamp=datetime.now()) pr.health_status = classify(pr, check_id) session.add(pr) session.commit() new_health = Host.query.get(host.id).health process_alerts(host.id, plugin.id, check_id, old_health, new_health)
def system_logs(): messages = LogMessage.query.order_by(LogMessage.timestamp.desc()).all() for message in messages: message.previous_read_status = message.read if not message.read: message.read = True session.commit() return render_template("system-logs.html", nav_section="system-logs", section="System Logs", title="View Logs", messages=messages)
def services_edit(): name = request.form.get("name") description = request.form.get("description") service_id = request.form.get("service-id") try: dependencies = json.loads(request.form.get("dependencies")) except ValueError: return error_response("Could not understand format of request sent") if not name.strip(): return error_response("You must specify a name") try: service = Service.query.get(service_id) if not service: return error_response("Service could not be found") service.name = name service.description = description gs = RedundancyGroup.query.filter(RedundancyGroup.service_id == service.id) for g in gs: session.delete(g) ds = ServiceDependency.query.filter(ServiceDependency.service_id == service.id) for d in ds: session.delete(d) for dependency in dependencies["dependencies"]: if dependency["type"] == "host": sd = ServiceDependency(service_id=service.id, host_id=dependency["id"]) else: sd = ServiceDependency(service_id=service.id, host_group_id=dependency["id"]) session.add(sd) for redundancy_group in dependencies["redundancyGroups"]: rg = RedundancyGroup(service_id=service.id) session.add(rg) session.flush() sd = ServiceDependency(service_id=service.id, redundancy_group_id=rg.id) session.add(sd) for item in redundancy_group["items"]: if item["type"] == "host": rgc = RedundancyGroupComponent(redundancy_group_id=rg.id, host_id=item["id"]) else: rgc = RedundancyGroupComponent(redundancy_group_id=rg.id, host_group_id=item["id"]) session.add(rgc) session.commit() except ValueError: session.rollback() return error_response( "The data sent to the server could not be " "understood. Please refresh the page and try again." ) return jsonify(success=True, message="Service has been saved successfully")
def host_groups_delete(): host_group_id = request.form.get("host-group-id") g = HostGroup.query.get(host_group_id) if not g: return error_response("Host Group could not be found!") session.delete(g) session.commit() return jsonify(success=True, message="Host Group has been deleted successfully")
def checks_delete(): check_id = request.form.get("check-id") check = Check.query.get(check_id) if not check: return error_response("The check you are trying to delete could not " "be found") session.delete(check) session.commit() return jsonify(success=True, message="Check has been deleted successfully!")
def scheduling_delete(): schedule_id = request.form.get("schedule-id") s = Schedule.query.get(schedule_id) if not s: return error_response("The schedule you are trying to delete does " "not exist") session.delete(s) session.commit() return jsonify(success=True, message="Schedule has been deleted " "successfully!")
def hosts_delete(): host_id = request.form.get("host-id") h = Host.query.get(host_id) if not h: return error_response("Host could not be found!") session.delete(h) session.commit() return jsonify(success=True, message="Host has been deleted successfully")
def users_delete(): user_id = request.form.get("user-id") u = User.query.get(user_id) if not u: return error_response("The user you are trying to delete does not exist") session.delete(u) session.commit() return jsonify(success=True, message="User has been deleted successfully!")
def services_delete(): service_id = request.form.get("service-id") s = Service.query.get(service_id) if not s: return error_response("The service you are trying to delete could not " "be found") session.delete(s) session.commit() return jsonify(success=True, message="Service has been deleted successfully")
def users_delete(): user_id = request.form.get("user-id") u = User.query.get(user_id) if not u: return error_response( "The user you are trying to delete does not exist") session.delete(u) session.commit() return jsonify(success=True, message="User has been deleted successfully!")
def perform_check(host, plugin, check_id): a = Agent(host.host, host.auth_key, verify_certs=host.check_certificate) error = None result_type = "plugin" try: update_required = a.check_plugin_verison(plugin.id, plugin.version) if update_required: plugin_file = os.path.join(get_config_value(config, "plugin_repo"), plugin.archive_file) if plugin.signature_file: signature_file = os.path.join(get_config_value(config, "plugin_repo"), plugin.signature_file) with open(plugin_file, "rb") as pf: if plugin.signature_file: with open(signature_file, "rb") as sf: a.update_plugin(plugin.id, pf, sf) else: a.update_plugin(plugin.id, pf) (value, message) = a.get_plugin_data(plugin.id) except CommandUnsuccessfulError as e: error = "CommandUnsuccessfulError: {}".format(str(e)) result_type = "command_unsuccessful" except AuthenticationError as e: error = "AuthenticationError: {}".format(str(e)) result_type = "authentication_error" except RequestError as e: error = "RequestError: {}".format(str(e)) result_type = "request_error" except ConnectionError as e: error = "ConnectionError: {}".format(str(e)) result_type = "connection_error" except Timeout as e: error = "Timeout: {}".format(str(e)) result_type = "connection_timeout" if error: log_message("Dispatcher", error) message = error value = None old_health = Host.query.get(host.id).health pr = PluginResult(host_id=host.id, plugin_id=plugin.id, check_id=check_id, value=value, message=message, result_type=result_type, timestamp=datetime.now()) pr.health_status = classify(pr, check_id) session.add(pr) session.commit() new_health = Host.query.get(host.id).health process_alerts(host.id, plugin.id, check_id, old_health, new_health)
def setUp(self): create_all() # Insert all plugins for letter in ["A", "B", "C", "D"]: p = Plugin(id=letter, name=letter) session.add(p) g = HostGroup(name="G") session.add(g) g2 = HostGroup(name="G2") session.add(g2) # Insert all hosts for number in range(1, 8): h = Host(name=number) session.add(h) session.flush() if number in [3, 4]: hga = HostGroupAssignment(member_host_id=h.id, host_group_id=g.id) session.add(hga) if number == 7: hga = HostGroupAssignment(member_host_id=h.id, host_group_id=g2.id) session.add(hga) hga = HostGroupAssignment(member_host_group_id=g.id, host_group_id=g2.id) session.add(hga) # Insert all checks and do assignments for number in range(1, 6): c = Check(name=number) session.add(c) session.add(CheckAssignment(check_id=1, host_id=1)) session.add(CheckAssignment(check_id=1, host_id=2)) session.add(CheckAssignment(check_id=1, host_id=4)) session.add(CheckAssignment(check_id=2, host_id=3)) session.add(CheckAssignment(check_id=4, host_id=5)) session.add(CheckAssignment(check_id=3, host_group_id=1)) session.add(CheckAssignment(check_id=5, host_group_id=2)) session.add(CheckPlugin(check_id=1, plugin_id=2)) session.add(CheckPlugin(check_id=1, plugin_id=3)) session.add(CheckPlugin(check_id=2, plugin_id=2)) session.add(CheckPlugin(check_id=3, plugin_id=1)) session.add(CheckPlugin(check_id=4, plugin_id=1)) session.add(CheckPlugin(check_id=4, plugin_id=2)) session.add(CheckPlugin(check_id=4, plugin_id=3)) session.add(CheckPlugin(check_id=5, plugin_id=4)) session.commit()
def setUp(self): session.commit() drop_all() create_all() session.add(Alert(id=1)) session.add(Alert(id=2)) session.add(Check(id=1)) session.add(Plugin(id=1)) session.add(AlertRestrictToEntity(alert_id=1, plugin_id=1)) session.add(AlertRestrictToEntity(alert_id=1, check_id=1)) session.commit()
def services_add(): name = request.form.get("name") description = request.form.get("description") try: dependencies = json.loads(request.form.get("dependencies")) except ValueError: return error_response("Could not understand format of request sent") if not name.strip(): return error_response("You must specify a name") try: service = Service(name=name, description=description) session.add(service) session.flush() for dependency in dependencies["dependencies"]: if dependency["type"] == "host": sd = ServiceDependency(service_id=service.id, host_id=dependency["id"]) else: sd = ServiceDependency(service_id=service.id, host_group_id=dependency["id"]) session.add(sd) for redundancy_group in dependencies["redundancyGroups"]: rg = RedundancyGroup(service_id=service.id) session.add(rg) session.flush() sd = ServiceDependency(service_id=service.id, redundancy_group_id=rg.id) session.add(sd) for item in redundancy_group["items"]: if item["type"] == "host": rgc = RedundancyGroupComponent(redundancy_group_id=rg.id, host_id=item["id"]) else: rgc = RedundancyGroupComponent(redundancy_group_id=rg.id, host_group_id=item["id"]) session.add(rgc) session.commit() except ValueError: session.rollback() return error_response("The data sent to the server could not be " "understood. Please refresh the page and try again.") return jsonify(success=True, message="Service has been added successfully")
def scheduling_edit(): schedule_id = request.form.get("schedule-id") name = request.form.get("name") description = request.form.get("description") interval_starts = request.form.getlist("interval-start[]") interval_values = request.form.getlist("interval-value[]") interval_units = request.form.getlist("interval-unit[]") checks = request.form.getlist("checks[]") if not name: return error_response("You must supply a name for this schedule") s = Schedule.query.get(schedule_id) if not s: abort(404) s.name = name s.description = description ScheduleCheck.query.filter(ScheduleCheck.schedule_id == s.id).delete() for check_id in checks: sc = ScheduleCheck(check_id=check_id, schedule_id=s.id) session.add(sc) ScheduleInterval.query.filter( ScheduleInterval.schedule_id == s.id).delete() for interval in zip(interval_starts, interval_values, interval_units): try: start_timestamp = datetime.strptime(interval[0], "%Y-%m-%d %H:%M:%S") except ValueError: session.rollback() return error_response("Start timestamp for interval was not " "understood") si = ScheduleInterval(schedule_id=s.id, start_timestamp=start_timestamp) try: si.set_interval(int(interval[1]), interval[2]) except ValueError: session.rollback() return error_response("Interval must be an integer") session.add(si) session.commit() return jsonify(success=True, message="Schedule has been saved successfully")
def scheduler_loop(callback): while True: try: current_timestamp = datetime.now() intervals = ScheduleInterval.query.filter( ScheduleInterval.execute_next == None) for i in intervals: i.execute_next = current_timestamp (num_iterations, execute_next) = walk_execute_next(i.execute_next, i.interval_seconds, current_timestamp) session.commit() intervals = ScheduleInterval.query.filter( ScheduleInterval.execute_next < current_timestamp).filter(or_( ScheduleInterval.last_executed < \ ScheduleInterval.execute_next, ScheduleInterval.last_executed == None )) for i in intervals: # Only execute if it is not too late, however still walk the # timestamp, otherwise late schedules will never execute again! if i.execute_next >= current_timestamp - lateness_delta: callback(i.schedule) (num_iterations, execute_next) = walk_execute_next(i.execute_next, i.interval_seconds, current_timestamp) i.execute_next = execute_next i.last_executed = current_timestamp session.commit() except Exception as ex: print(str(ex)) log_message( "Scheduler", "An exception occurred in the scheduler: " "{}".format(str(ex))) time.sleep(scheduler_delay)
def plugins_thresholds_save(): plugin_id = request.form.get("plugin-id") thresholds = list(zip( request.form.getlist("check[]"), request.form.getlist("n-historical[]"), request.form.getlist("classification-code[]") )) used_check_ids = [] for threshold in thresholds: check_id, n_historical, classification_code = threshold if check_id == "-1": return error_response("You must specify a check for all thresholds") if not n_historical or int(n_historical) < 1: return error_response("Number of historical values must be greater " "than 0 and must be specified") if not classification_code.strip(): return error_response("You must supply classification code") if check_id in used_check_ids: return error_response("You cannot have multiple thresholds related " "to the same check") used_check_ids.append(check_id) PluginThreshold.query.filter(PluginThreshold.plugin_id==plugin_id).delete() for threshold in thresholds: check_id, n_historical, classification_code = threshold pt = PluginThreshold( plugin_id=plugin_id, n_historical=n_historical, classification_code=classification_code ) if check_id != "default": pt.check_id = check_id pt.default = False else: pt.default = True session.add(pt) session.commit() return jsonify(success=True, message="Thresholds have been saved " "successfully!")
def scheduling_edit(): schedule_id = request.form.get("schedule-id") name = request.form.get("name") description = request.form.get("description") interval_starts = request.form.getlist("interval-start[]") interval_values = request.form.getlist("interval-value[]") interval_units = request.form.getlist("interval-unit[]") checks = request.form.getlist("checks[]") if not name: return error_response("You must supply a name for this schedule") s = Schedule.query.get(schedule_id) if not s: abort(404) s.name = name s.description = description ScheduleCheck.query.filter(ScheduleCheck.schedule_id == s.id).delete() for check_id in checks: sc = ScheduleCheck(check_id=check_id, schedule_id=s.id) session.add(sc) ScheduleInterval.query.filter(ScheduleInterval.schedule_id == s.id).delete() for interval in zip(interval_starts, interval_values, interval_units): try: start_timestamp = datetime.strptime(interval[0], "%Y-%m-%d %H:%M:%S") except ValueError: session.rollback() return error_response("Start timestamp for interval was not " "understood") si = ScheduleInterval(schedule_id=s.id, start_timestamp=start_timestamp) try: si.set_interval(int(interval[1]), interval[2]) except ValueError: session.rollback() return error_response("Interval must be an integer") session.add(si) session.commit() return jsonify(success=True, message="Schedule has been saved successfully")
def plugins_delete(): plugin_id = request.form.get("plugin-id") p = Plugin.query.get(plugin_id) if not p: return error_response("Plugin does not exist") plugin_repo = get_config_value(config, "plugin_repo") try: os.remove(os.path.join(plugin_repo, p.archive_file)) if p.signature_file: os.remove(os.path.join(plugin_repo, p.signature_file)) except FileNotFoundError: # We are deleting so we don't care if the file doesn't exist pass session.delete(p) session.commit() return jsonify(success=True, message="Plugin has been deleted successfully")
def setUp(self): session.commit() drop_all() create_all() # Add Hosts for i in range(1,5): session.add(Host(id=i, name="Host {}".format(i))) # Add Groups for i in range(1,9): session.add(HostGroup(id=i, name="Group {}".format(i))) session.flush() # Assign hosts to groups session.add(HostGroupAssignment(member_host_id=1, host_group_id=1)) session.add(HostGroupAssignment(member_host_id=1, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=2, host_group_id=1)) session.add(HostGroupAssignment(member_host_id=2, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=2, host_group_id=3)) session.add(HostGroupAssignment(member_host_id=3, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=3, host_group_id=3)) session.add(HostGroupAssignment(member_host_id=3, host_group_id=5)) session.add(HostGroupAssignment(member_host_id=4, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=4, host_group_id=6)) session.add(HostGroupAssignment(member_host_id=4, host_group_id=5)) # Assign groups to groups session.add(HostGroupAssignment(member_host_group_id=4, host_group_id=5)) session.add(HostGroupAssignment(member_host_group_id=3, host_group_id=4)) session.add(HostGroupAssignment(member_host_group_id=6, host_group_id=7)) session.add(HostGroupAssignment(member_host_group_id=7, host_group_id=8)) session.add(HostGroupAssignment(member_host_group_id=8, host_group_id=6)) session.commit()
def setUp(self): session.commit() drop_all() create_all() # Add Hosts for i in range(1, 5): session.add(Host(id=i, name="Host {}".format(i))) # Add Groups for i in range(1, 9): session.add(HostGroup(id=i, name="Group {}".format(i))) session.flush() # Assign hosts to groups session.add(HostGroupAssignment(member_host_id=1, host_group_id=1)) session.add(HostGroupAssignment(member_host_id=1, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=2, host_group_id=1)) session.add(HostGroupAssignment(member_host_id=2, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=2, host_group_id=3)) session.add(HostGroupAssignment(member_host_id=3, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=3, host_group_id=3)) session.add(HostGroupAssignment(member_host_id=3, host_group_id=5)) session.add(HostGroupAssignment(member_host_id=4, host_group_id=2)) session.add(HostGroupAssignment(member_host_id=4, host_group_id=6)) session.add(HostGroupAssignment(member_host_id=4, host_group_id=5)) # Assign groups to groups session.add( HostGroupAssignment(member_host_group_id=4, host_group_id=5)) session.add( HostGroupAssignment(member_host_group_id=3, host_group_id=4)) session.add( HostGroupAssignment(member_host_group_id=6, host_group_id=7)) session.add( HostGroupAssignment(member_host_group_id=7, host_group_id=8)) session.add( HostGroupAssignment(member_host_group_id=8, host_group_id=6)) session.commit()
def host_groups_edit(): host_group_id = request.form.get("host-group-id") name = request.form.get("name") description = request.form.get("description") hosts = request.form.getlist("hosts[]") host_groups = request.form.getlist("host-groups[]") if not name: return error_response("You must supply a name for this group") groups = HostGroup.query.filter(and_(HostGroup.name == name, HostGroup.id != host_group_id)).count() if groups: return error_response("A group with that name already exists") g = HostGroup.query.get(host_group_id) if not g: return error_response("Host Group could not be found!") g.name = name g.description = description # Remove all current assignments, they will be replaced with the new ones HostGroupAssignment.query.filter( HostGroupAssignment.host_group_id == host_group_id).delete() for host in hosts: a = HostGroupAssignment(host_group_id=host_group_id, member_host_id=host) session.add(a) for group in host_groups: a = HostGroupAssignment(host_group_id=host_group_id, member_host_group_id=group) session.add(a) session.commit() return jsonify(success=True, message="Host Group has been saved successfully")
def scheduler_loop(callback): while True: try: current_timestamp = datetime.now() intervals = ScheduleInterval.query.filter(ScheduleInterval.execute_next == None) for i in intervals: i.execute_next = current_timestamp (num_iterations, execute_next) = walk_execute_next( i.execute_next, i.interval_seconds, current_timestamp ) session.commit() intervals = ScheduleInterval.query.filter(ScheduleInterval.execute_next < current_timestamp).filter( or_( ScheduleInterval.last_executed < ScheduleInterval.execute_next, ScheduleInterval.last_executed == None, ) ) for i in intervals: # Only execute if it is not too late, however still walk the # timestamp, otherwise late schedules will never execute again! if i.execute_next >= current_timestamp - lateness_delta: callback(i.schedule) (num_iterations, execute_next) = walk_execute_next( i.execute_next, i.interval_seconds, current_timestamp ) i.execute_next = execute_next i.last_executed = current_timestamp session.commit() except Exception as ex: print(str(ex)) log_message("Scheduler", "An exception occurred in the scheduler: " "{}".format(str(ex))) time.sleep(scheduler_delay)
def checks_edit(): name = request.form.get("name") description = request.form.get("description") host_groups = request.form.getlist("host-groups[]") hosts = request.form.getlist("hosts[]") plugins = request.form.getlist("plugins[]") check_id = request.form.get("check-id") if not name: return error_response("You must supply a name for this check") c = Check.query.get(check_id) if not c: return error_response("Check could not be found!") c.name = name c.description = description session.flush() CheckAssignment.query.filter(CheckAssignment.check_id == check_id).delete() CheckPlugin.query.filter(CheckPlugin.check_id == check_id).delete() for host_id in hosts: ca = CheckAssignment(host_id=host_id, check_id=c.id) session.add(ca) for host_group_id in host_groups: ca = CheckAssignment(host_group_id=host_group_id, check_id=c.id) session.add(ca) for plugin_id in plugins: cp = CheckPlugin(plugin_id=plugin_id, check_id=c.id) session.add(cp) session.commit() return jsonify(success=True, message="Check has been saved successfully!")
def hosts_add(): name = request.form.get("name") host = request.form.get("host") description = request.form.get("description") auth_key = request.form.get("auth-key") check_certificate = bool(request.form.get("check-certificate")) if not (name and host and auth_key): return error_response("Name, host and auth key are required") hosts = Host.query.filter(Host.name == name or Host.host == host).count() if hosts: return error_response("A host with that name or host already exists") success, message = test_agent_connection(host, auth_key, check_certificate) if not success: return error_response(message) h = Host(name=name, host=host, description=description, auth_key=auth_key, check_certificate=check_certificate) session.add(h) session.commit() return jsonify(success=True, message="Host added successfully")
def users_edit(): username = request.form.get("username") email = request.form.get("email") first_name = request.form.get("first-name") last_name = request.form.get("last-name") password = request.form.get("password") confirm_password = request.form.get("confirm-password") user_id = request.form.get("user-id") if not (username.strip() and email.strip() and first_name.strip() and \ last_name.strip()): return error_response("Username, email, first name and last name " "are required") if password != confirm_password: return error_response("Passwords do not match") if User.query.filter(User.username==username).filter( User.id != user_id).count(): return error_response("A user with that username already exists") u = User.query.get(user_id) if not u: return error_response("User could not be found!") u.username = username u.email = email u.first_name = first_name u.last_name = last_name if password: u.password_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") session.commit() return jsonify(success=True, message="User has been saved successfully!")
def setUp(self): session.commit() drop_all() create_all() # Insert all plugins for letter in ["A", "B", "C"]: session.add(Plugin(id=letter, name=letter)) # Insert all hosts for number in range(1,9): session.add(Host(name=number)) # Mock the assigned_plugins method Host.assigned_plugins = property(lambda s: Plugin.query.all()) # All plugins OK session.add(PluginResult(host_id=1, plugin_id="A", health_status="ok")) session.add(PluginResult(host_id=1, plugin_id="B", health_status="ok")) session.add(PluginResult(host_id=1, plugin_id="C", health_status="ok")) # All plugins critical session.add(PluginResult(host_id=2, plugin_id="A", health_status="critical")) session.add(PluginResult(host_id=2, plugin_id="B", health_status="critical")) session.add(PluginResult(host_id=2, plugin_id="C", health_status="critical")) # All plugins unknown session.add(PluginResult(host_id=3, plugin_id="A", health_status="unknown")) session.add(PluginResult(host_id=3, plugin_id="B", health_status="unknown")) session.add(PluginResult(host_id=3, plugin_id="C", health_status="unknown")) # One plugin critical session.add(PluginResult(host_id=4, plugin_id="A", health_status="ok")) session.add(PluginResult(host_id=4, plugin_id="B", health_status="critical")) session.add(PluginResult(host_id=4, plugin_id="C", health_status="ok")) # One plugin unknown session.add(PluginResult(host_id=5, plugin_id="A", health_status="ok")) session.add(PluginResult(host_id=5, plugin_id="B", health_status="ok")) session.add(PluginResult(host_id=5, plugin_id="C", health_status="unknown")) # All plugins no_data (Host 6) # One plugin no data session.add(PluginResult(host_id=7, plugin_id="A", health_status="ok")) session.add(PluginResult(host_id=7, plugin_id="C", health_status="minor")) # Mixed results session.add(PluginResult(host_id=8, plugin_id="A", health_status="ok")) session.add(PluginResult(host_id=8, plugin_id="B", health_status="major")) session.add(PluginResult(host_id=8, plugin_id="C", health_status="minor")) session.commit()
def setUp(self): session.commit() drop_all() create_all() session.add(Plugin(id="Plugin", name="Plugin")) # Insert all hosts for number in range(1,7): session.add(Host(name=number)) # Mock the assigned_plugins method Host.assigned_plugins = property(lambda s: Plugin.query.all()) session.add(PluginResult(host_id=1, plugin_id="Plugin", health_status="ok")) session.add(PluginResult(host_id=2, plugin_id="Plugin", health_status="minor")) session.add(PluginResult(host_id=3, plugin_id="Plugin", health_status="major")) session.add(PluginResult(host_id=4, plugin_id="Plugin", health_status="critical")) session.add(PluginResult(host_id=5, plugin_id="Plugin", health_status="unknown")) # Host ID 6 has no data session.add(HostGroup(id=1)) session.add(HostGroupAssignment(host_group_id=1, member_host_id=1)) session.add(HostGroupAssignment(host_group_id=1, member_host_id=4)) for number in range(1,11): session.add(Service(id=number, name=number)) # test_failed_dependency session.add(ServiceDependency(service_id=1, host_id=1)) session.add(ServiceDependency(service_id=1, host_id=1)) session.add(ServiceDependency(service_id=1, host_id=3)) # test_ok_dependency session.add(ServiceDependency(service_id=2, host_id=1)) session.add(ServiceDependency(service_id=2, host_id=1)) session.add(ServiceDependency(service_id=2, host_id=1)) # test_failure_in_redundancy_group session.add(RedundancyGroup(id=1, service_id=3)) session.add(RedundancyGroupComponent(redundancy_group_id=1, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=1, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=1, host_id=4)) session.add(ServiceDependency(service_id=3, redundancy_group_id=1)) # test_failed_redundancy_group session.add(RedundancyGroup(id=2, service_id=4)) session.add(RedundancyGroupComponent(redundancy_group_id=2, host_id=2)) session.add(RedundancyGroupComponent(redundancy_group_id=2, host_id=2)) session.add(RedundancyGroupComponent(redundancy_group_id=2, host_id=4)) session.add(ServiceDependency(service_id=4, redundancy_group_id=2)) # redundancy_group_ok session.add(RedundancyGroup(id=3, service_id=5)) session.add(RedundancyGroupComponent(redundancy_group_id=3, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=3, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=3, host_id=1)) session.add(ServiceDependency(service_id=5, redundancy_group_id=3)) # test_failed_dependency_with_redundancy_group session.add(RedundancyGroup(id=4, service_id=6)) session.add(RedundancyGroupComponent(redundancy_group_id=4, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=4, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=4, host_id=1)) session.add(ServiceDependency(service_id=6, redundancy_group_id=4)) session.add(ServiceDependency(service_id=6, host_id=3)) # test_all_dependency_failed session.add(ServiceDependency(service_id=7, host_id=3)) session.add(ServiceDependency(service_id=7, host_id=3)) session.add(ServiceDependency(service_id=7, host_id=4)) # test_no_data session.add(ServiceDependency(service_id=8, host_id=1)) session.add(ServiceDependency(service_id=8, host_id=1)) session.add(ServiceDependency(service_id=8, host_id=6)) # test_host_group_dependency session.add(ServiceDependency(service_id=9, host_group_id=1)) # test_host_group_redundancy session.add(RedundancyGroup(id=5, service_id=10)) session.add(RedundancyGroupComponent(redundancy_group_id=5, host_group_id=1)) session.add(ServiceDependency(service_id=10, redundancy_group_id=5)) session.commit()
def setUp(self): session.commit() drop_all() create_all() # Insert all plugins for letter in ["A", "B", "C"]: session.add(Plugin(id=letter, name=letter)) # Insert all hosts for number in range(1, 9): session.add(Host(name=number)) # Mock the assigned_plugins method Host.assigned_plugins = property(lambda s: Plugin.query.all()) # All plugins OK session.add(PluginResult(host_id=1, plugin_id="A", health_status="ok")) session.add(PluginResult(host_id=1, plugin_id="B", health_status="ok")) session.add(PluginResult(host_id=1, plugin_id="C", health_status="ok")) # All plugins critical session.add( PluginResult(host_id=2, plugin_id="A", health_status="critical")) session.add( PluginResult(host_id=2, plugin_id="B", health_status="critical")) session.add( PluginResult(host_id=2, plugin_id="C", health_status="critical")) # All plugins unknown session.add( PluginResult(host_id=3, plugin_id="A", health_status="unknown")) session.add( PluginResult(host_id=3, plugin_id="B", health_status="unknown")) session.add( PluginResult(host_id=3, plugin_id="C", health_status="unknown")) # One plugin critical session.add(PluginResult(host_id=4, plugin_id="A", health_status="ok")) session.add( PluginResult(host_id=4, plugin_id="B", health_status="critical")) session.add(PluginResult(host_id=4, plugin_id="C", health_status="ok")) # One plugin unknown session.add(PluginResult(host_id=5, plugin_id="A", health_status="ok")) session.add(PluginResult(host_id=5, plugin_id="B", health_status="ok")) session.add( PluginResult(host_id=5, plugin_id="C", health_status="unknown")) # All plugins no_data (Host 6) # One plugin no data session.add(PluginResult(host_id=7, plugin_id="A", health_status="ok")) session.add( PluginResult(host_id=7, plugin_id="C", health_status="minor")) # Mixed results session.add(PluginResult(host_id=8, plugin_id="A", health_status="ok")) session.add( PluginResult(host_id=8, plugin_id="B", health_status="major")) session.add( PluginResult(host_id=8, plugin_id="C", health_status="minor")) session.commit()
def setUp(self): session.commit() drop_all() create_all() session.add(Plugin(id="Plugin", name="Plugin")) # Insert all hosts for number in range(1, 7): session.add(Host(name=number)) # Mock the assigned_plugins method Host.assigned_plugins = property(lambda s: Plugin.query.all()) session.add( PluginResult(host_id=1, plugin_id="Plugin", health_status="ok")) session.add( PluginResult(host_id=2, plugin_id="Plugin", health_status="minor")) session.add( PluginResult(host_id=3, plugin_id="Plugin", health_status="major")) session.add( PluginResult(host_id=4, plugin_id="Plugin", health_status="critical")) session.add( PluginResult(host_id=5, plugin_id="Plugin", health_status="unknown")) # Host ID 6 has no data session.add(HostGroup(id=1)) session.add(HostGroupAssignment(host_group_id=1, member_host_id=1)) session.add(HostGroupAssignment(host_group_id=1, member_host_id=4)) for number in range(1, 11): session.add(Service(id=number, name=number)) # test_failed_dependency session.add(ServiceDependency(service_id=1, host_id=1)) session.add(ServiceDependency(service_id=1, host_id=1)) session.add(ServiceDependency(service_id=1, host_id=3)) # test_ok_dependency session.add(ServiceDependency(service_id=2, host_id=1)) session.add(ServiceDependency(service_id=2, host_id=1)) session.add(ServiceDependency(service_id=2, host_id=1)) # test_failure_in_redundancy_group session.add(RedundancyGroup(id=1, service_id=3)) session.add(RedundancyGroupComponent(redundancy_group_id=1, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=1, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=1, host_id=4)) session.add(ServiceDependency(service_id=3, redundancy_group_id=1)) # test_failed_redundancy_group session.add(RedundancyGroup(id=2, service_id=4)) session.add(RedundancyGroupComponent(redundancy_group_id=2, host_id=2)) session.add(RedundancyGroupComponent(redundancy_group_id=2, host_id=2)) session.add(RedundancyGroupComponent(redundancy_group_id=2, host_id=4)) session.add(ServiceDependency(service_id=4, redundancy_group_id=2)) # redundancy_group_ok session.add(RedundancyGroup(id=3, service_id=5)) session.add(RedundancyGroupComponent(redundancy_group_id=3, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=3, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=3, host_id=1)) session.add(ServiceDependency(service_id=5, redundancy_group_id=3)) # test_failed_dependency_with_redundancy_group session.add(RedundancyGroup(id=4, service_id=6)) session.add(RedundancyGroupComponent(redundancy_group_id=4, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=4, host_id=1)) session.add(RedundancyGroupComponent(redundancy_group_id=4, host_id=1)) session.add(ServiceDependency(service_id=6, redundancy_group_id=4)) session.add(ServiceDependency(service_id=6, host_id=3)) # test_all_dependency_failed session.add(ServiceDependency(service_id=7, host_id=3)) session.add(ServiceDependency(service_id=7, host_id=3)) session.add(ServiceDependency(service_id=7, host_id=4)) # test_no_data session.add(ServiceDependency(service_id=8, host_id=1)) session.add(ServiceDependency(service_id=8, host_id=1)) session.add(ServiceDependency(service_id=8, host_id=6)) # test_host_group_dependency session.add(ServiceDependency(service_id=9, host_group_id=1)) # test_host_group_redundancy session.add(RedundancyGroup(id=5, service_id=10)) session.add( RedundancyGroupComponent(redundancy_group_id=5, host_group_id=1)) session.add(ServiceDependency(service_id=10, redundancy_group_id=5)) session.commit()
def alerts_edit(): name = request.form.get("name") alert_id = request.form.get("alert-id") entity_selection = request.form.get("entity-selection") host_groups = request.form.getlist("host-groups[]") hosts = request.form.getlist("hosts[]") checks = request.form.getlist("checks[]") services = request.form.getlist("services[]") plugins = request.form.getlist("plugins[]") from_states = request.form.getlist("from-states[]") to_states = request.form.getlist("to-states[]") module_selection = request.form.get("module-selection") if not name: return error_response("You must specify a name for this alert") alert = Alert.query.get(alert_id) if not alert: abort(404) if not from_states or not to_states: return error_response("You must specify at least one from state and at " "least one to state") alert.name = name alert.entity_selection_type = entity_selection alert.module = module_selection AlertTransitionTo.query.filter( AlertTransitionTo.alert_id==alert_id).delete() AlertTransitionFrom.query.filter( AlertTransitionFrom.alert_id==alert_id).delete() AlertCheckEntity.query.filter(AlertCheckEntity.alert_id==alert_id).delete() AlertRestrictToEntity.query.filter( AlertRestrictToEntity.alert_id==alert_id).delete() for state in to_states: session.add(AlertTransitionTo(alert_id=alert.id, state=state)) for state in from_states: session.add(AlertTransitionFrom(alert_id=alert.id, state=state)) if entity_selection == "custom": added_entity = False for host_id in hosts: session.add(AlertCheckEntity(alert_id=alert.id, host_id=host_id)) added_entity = True for host_group_id in host_groups: session.add(AlertCheckEntity(alert_id=alert.id, host_group_id=host_group_id)) added_entity = True for service_id in services: session.add(AlertCheckEntity(alert_id=alert.id, service_id=service_id)) added_entity = True if not added_entity: session.rollback() return error_response("You must select at least one entity to alert" " for state changes in") for check_id in checks: session.add(AlertRestrictToEntity(alert_id=alert.id, check_id=check_id)) for plugin_id in plugins: session.add(AlertRestrictToEntity(alert_id=alert.id, plugin_id=plugin_id)) AlertModuleOption.query.filter( AlertModuleOption.alert_id==alert.id).delete() for key in request.form.keys(): if key.startswith("module-option-"): option_key = key.replace("module-option-", "", 1) option_value = request.form.get(key) session.add(AlertModuleOption(alert_id=alert.id, key=option_key, value=option_value)) session.commit() return jsonify(success=True, message="Alert has been saved successfully")