Ejemplo n.º 1
0
def get_probe_edit_form(probe_class):
    """get the form to edit a Probe"""

    probe_obj = Factory.create_obj(probe_class)

    probe_info = probe_obj.get_plugin_vars()
    probe_vars = ProbeVars(None, probe_class,
                           probe_obj.get_default_parameter_values())

    # Get only the default Checks for this Probe class
    checks_avail = probe_obj.get_checks_info_defaults()
    checks_avail = probe_obj.expand_check_vars(checks_avail)

    for check_class in checks_avail:
        check_obj = Factory.create_obj(check_class)
        check_params = check_obj.get_default_parameter_values()
        probe_check_param_defs = \
            probe_info['CHECKS_AVAIL'][check_class]['PARAM_DEFS']
        for param in probe_check_param_defs:
            if 'value' in probe_check_param_defs[param]:
                check_params[param] = probe_check_param_defs[param]['value']

        # Appends 'check_vars' to 'probe_vars' (SQLAlchemy)
        CheckVars(probe_vars, check_class, check_params)

    return render_template('includes/probe_edit_form.html',
                           lang=g.current_lang,
                           probe=probe_vars,
                           probe_info=probe_info)
Ejemplo n.º 2
0
def get_check_edit_form(check_class):
    """get the form to edit a Check"""

    check_obj = Factory.create_obj(check_class)
    check_info = check_obj.get_plugin_vars()
    check_vars = CheckVars(
        None, check_class, check_obj.get_default_parameter_values())

    return render_template('includes/check_edit_form.html',
                           lang=g.current_lang,
                           check=check_vars, check_info=check_info)
Ejemplo n.º 3
0
def update(resource_identifier):
    """update a resource"""

    update_counter = 0
    status = 'success'

    try:
        resource_identifier_dict = request.get_json()

        resource = Resource.query.filter_by(
            identifier=resource_identifier).first()

        for key, value in resource_identifier_dict.items():
            if key == 'tags':
                resource_tags = [t.name for t in resource.tags]

                tags_to_add = set(value) - set(resource_tags)
                tags_to_delete = set(resource_tags) - set(value)

                # Existing Tags: create relation else add new Tag
                all_tag_objs = Tag.query.all()
                for tag in tags_to_add:
                    tag_add_obj = None
                    for tag_obj in all_tag_objs:
                        if tag == tag_obj.name:
                            # use existing
                            tag_add_obj = tag_obj
                            break

                    if not tag_add_obj:
                        # add new
                        tag_add_obj = Tag(name=tag)
                        DB.session.add(tag_add_obj)

                    resource.tags.append(tag_add_obj)

                for tag in tags_to_delete:
                    tag_to_delete = Tag.query.filter_by(name=tag).first()
                    resource.tags.remove(tag_to_delete)

                update_counter += 1
            elif key == 'probes':
                # Remove all existing ProbeVars for Resource
                for probe_var in resource.probe_vars:
                    resource.probe_vars.remove(probe_var)

                # Add ProbeVars anew each with optional CheckVars
                for probe in value:
                    print('adding Probe class=%s parms=%s' %
                          (probe['probe_class'], str(probe)))
                    probe_vars = ProbeVars(resource, probe['probe_class'],
                                           probe['parameters'])
                    for check in probe['checks']:
                        check_vars = CheckVars(probe_vars,
                                               check['check_class'],
                                               check['parameters'])
                        probe_vars.check_vars.append(check_vars)

                    resource.probe_vars.append(probe_vars)

                update_counter += 1

            elif getattr(resource, key) != resource_identifier_dict[key]:
                # Update other resource attrs, mainly 'name'
                setattr(resource, key, resource_identifier_dict[key])
                update_counter += 1

    except Exception as err:
        DB.session.rollback()
        status = str(err)
        update_counter = 0
    # finally:
    #     DB.session.close()

    if update_counter > 0:
        err = db_commit()
        if err:
            status = str(err)

    return jsonify({'status': status})
Ejemplo n.º 4
0
def add():
    """add resource"""
    if not g.user.is_authenticated():
        return render_template('add.html')
    if request.method == 'GET':
        return render_template('add.html')

    tag_list = []

    resource_type = request.form['resource_type']
    tags = request.form.getlist('tags')
    url = request.form['url'].strip()
    resource = Resource.query.filter_by(resource_type=resource_type,
                                        url=url).first()
    if resource is not None:
        msg = gettext('Service already registered')
        flash('%s (%s, %s)' % (msg, resource_type, url), 'danger')
        if 'resource_type' in request.args:
            rtype = request.args.get('resource_type')
            return redirect(
                url_for('add', lang=g.current_lang, resource_type=rtype))
        return redirect(url_for('add', lang=g.current_lang))

    [title, success, response_time, message,
     start_time] = sniff_test_resource(APP.config, resource_type, url)

    if not success:
        flash(message, 'danger')
        return redirect(
            url_for('add', lang=g.current_lang, resource_type=resource_type))

    if tags:
        for tag in tags:
            tag_found = False
            for tag_obj in Tag.query.all():
                if tag == tag_obj.name:  # use existing
                    tag_found = True
                    tag_list.append(tag_obj)
            if not tag_found:  # add new
                tag_list.append(Tag(name=tag))

    resource_to_add = Resource(current_user,
                               resource_type,
                               title,
                               url,
                               tags=tag_list)

    probe_to_add = None
    checks_to_add = []

    # Always add a default Probe and Check(s)  from the GHC_PROBE_DEFAULTS conf
    if resource_type in APP.config['GHC_PROBE_DEFAULTS']:
        resource_settings = APP.config['GHC_PROBE_DEFAULTS'][resource_type]
        probe_class = resource_settings['probe_class']
        if probe_class:
            # Add the default Probe
            probe_obj = Factory.create_obj(probe_class)
            probe_to_add = ProbeVars(resource_to_add, probe_class,
                                     probe_obj.get_default_parameter_values())

            # Add optional default (parameterized) Checks to add to this Probe
            checks_info = probe_obj.get_checks_info()
            checks_param_info = probe_obj.get_plugin_vars()['CHECKS_AVAIL']
            for check_class in checks_info:
                check_param_info = checks_param_info[check_class]
                if 'default' in checks_info[check_class]:
                    if checks_info[check_class]['default']:
                        # Filter out params for Check with fixed values
                        param_defs = check_param_info['PARAM_DEFS']
                        param_vals = {}
                        for param in param_defs:
                            if param_defs[param]['value']:
                                param_vals[param] = param_defs[param]['value']
                        check_vars = CheckVars(probe_to_add, check_class,
                                               param_vals)
                        checks_to_add.append(check_vars)

    result = run_test_resource(resource_to_add)

    run_to_add = Run(resource_to_add, result)

    DB.session.add(resource_to_add)
    if probe_to_add:
        DB.session.add(probe_to_add)
    for check_to_add in checks_to_add:
        DB.session.add(check_to_add)
    DB.session.add(run_to_add)

    try:
        DB.session.commit()
        msg = gettext('Service registered')
        flash('%s (%s, %s)' % (msg, resource_type, url), 'success')
    except Exception as err:
        DB.session.rollback()
        flash(str(err), 'danger')
        return redirect(url_for('home', lang=g.current_lang))
    else:
        return edit_resource(resource_to_add.identifier)
Ejemplo n.º 5
0
def update(resource_identifier):
    """update a resource"""

    update_counter = 0
    status = 'success'

    try:
        resource_identifier_dict = request.get_json()

        resource = Resource.query.filter_by(
            identifier=resource_identifier).first()

        for key, value in resource_identifier_dict.items():
            if key == 'tags':
                resource_tags = [t.name for t in resource.tags]

                tags_to_add = set(value) - set(resource_tags)
                tags_to_delete = set(resource_tags) - set(value)

                # Existing Tags: create relation else add new Tag
                all_tag_objs = Tag.query.all()
                for tag in tags_to_add:
                    tag_add_obj = None
                    for tag_obj in all_tag_objs:
                        if tag == tag_obj.name:
                            # use existing
                            tag_add_obj = tag_obj
                            break

                    if not tag_add_obj:
                        # add new
                        tag_add_obj = Tag(name=tag)
                        DB.session.add(tag_add_obj)

                    resource.tags.append(tag_add_obj)

                for tag in tags_to_delete:
                    tag_to_delete = Tag.query.filter_by(name=tag).first()
                    resource.tags.remove(tag_to_delete)

                update_counter += 1
            elif key == 'probes':
                # Remove all existing ProbeVars for Resource
                for probe_var in resource.probe_vars:
                    resource.probe_vars.remove(probe_var)

                # Add ProbeVars anew each with optional CheckVars
                for probe in value:
                    LOGGER.info('adding Probe class=%s parms=%s' %
                                (probe['probe_class'], str(probe)))
                    probe_vars = ProbeVars(resource, probe['probe_class'],
                                           probe['parameters'])
                    for check in probe['checks']:
                        check_vars = CheckVars(probe_vars,
                                               check['check_class'],
                                               check['parameters'])
                        probe_vars.check_vars.append(check_vars)

                    resource.probe_vars.append(probe_vars)

                update_counter += 1
            elif key == 'notify_emails':
                resource.set_recipients('email',
                                        [v for v in value if v.strip()])
            elif key == 'notify_webhooks':
                resource.set_recipients('webhook',
                                        [v for v in value if v.strip()])
            elif getattr(resource, key) != resource_identifier_dict[key]:
                # Update other resource attrs, mainly 'name'
                setattr(resource, key, resource_identifier_dict[key])
                min_run_freq = CONFIG['GHC_MINIMAL_RUN_FREQUENCY_MINS']
                if int(resource.run_frequency) < min_run_freq:
                    resource.run_frequency = min_run_freq
                update_counter += 1

        # Always update geo-IP: maybe failure on creation or
        # IP-address of URL may have changed.
        latitude, longitude = geocode(resource.url)
        if latitude != 0.0 and longitude != 0.0:
            # Only update for valid lat/lon
            resource.latitude = latitude
            resource.longitude = longitude
            update_counter += 1

    except Exception as err:
        LOGGER.error("Cannot update resource: %s", err, exc_info=err)
        DB.session.rollback()
        status = str(err)
        update_counter = 0
    # finally:
    #     DB.session.close()

    if update_counter > 0:
        err = db_commit()
        if err:
            status = str(err)

    return jsonify({'status': status})
Ejemplo n.º 6
0
def add():
    """add resource"""
    if not g.user.is_authenticated():
        return render_template('add.html')
    if request.method == 'GET':
        return render_template('add.html')
    resource_type = request.form['resource_type']
    tags = request.form.getlist('tags')
    url = request.form['url'].strip()
    resources_to_add = []

    from healthcheck import sniff_test_resource, run_test_resource
    sniffed_resources = sniff_test_resource(CONFIG, resource_type, url)

    if not sniffed_resources:
        msg = gettext("No resources detected")
        LOGGER.exception()
        flash(msg, 'danger')

    for (
            resource_type,
            resource_url,
            title,
            success,
            response_time,
            message,
            start_time,
            resource_tags,
    ) in sniffed_resources:

        # sniffed_resources may return list of resource
        # types different from initial one
        # so we need to test each row separately
        resource = Resource.query.filter_by(resource_type=resource_type,
                                            url=url).first()
        if resource is not None:
            msg = gettext('Service already registered')
            flash('%s (%s, %s)' % (msg, resource_type, url), 'danger')

            if len(sniffed_resources) == 1 and 'resource_type' in request.args:
                return redirect(url_for('add', lang=g.current_lang))

        tags_to_add = []
        for tag in chain(tags, resource_tags):
            tag_obj = tag
            if not isinstance(tag, Tag):
                tag_obj = Tag.query.filter_by(name=tag).first()
                if tag_obj is None:
                    tag_obj = Tag(name=tag)
            tags_to_add.append(tag_obj)

        resource_to_add = Resource(current_user,
                                   resource_type,
                                   title,
                                   resource_url,
                                   tags=tags_to_add)

        resources_to_add.append(resource_to_add)
        probe_to_add = None
        checks_to_add = []

        # Always add a default Probe and Check(s)
        # from the GHC_PROBE_DEFAULTS conf
        if resource_type in CONFIG['GHC_PROBE_DEFAULTS']:
            resource_settings = CONFIG['GHC_PROBE_DEFAULTS'][resource_type]
            probe_class = resource_settings['probe_class']
            if probe_class:
                # Add the default Probe
                probe_obj = Factory.create_obj(probe_class)
                probe_to_add = ProbeVars(
                    resource_to_add, probe_class,
                    probe_obj.get_default_parameter_values())

                # Add optional default (parameterized)
                # Checks to add to this Probe
                checks_info = probe_obj.get_checks_info()
                checks_param_info = probe_obj.get_plugin_vars()['CHECKS_AVAIL']
                for check_class in checks_info:
                    check_param_info = checks_param_info[check_class]
                    if 'default' in checks_info[check_class]:
                        if checks_info[check_class]['default']:
                            # Filter out params for Check with fixed values
                            param_defs = check_param_info['PARAM_DEFS']
                            param_vals = {}
                            for param in param_defs:
                                if param_defs[param]['value']:
                                    param_vals[param] = \
                                        param_defs[param]['value']
                            check_vars = CheckVars(probe_to_add, check_class,
                                                   param_vals)
                            checks_to_add.append(check_vars)

        result = run_test_resource(resource_to_add)

        run_to_add = Run(resource_to_add, result)

        DB.session.add(resource_to_add)
        # prepopulate notifications for current user
        resource_to_add.set_recipients('email', [g.user.email])

        if probe_to_add:
            DB.session.add(probe_to_add)
        for check_to_add in checks_to_add:
            DB.session.add(check_to_add)
            DB.session.add(run_to_add)

    try:
        DB.session.commit()
        msg = gettext('Services registered')
        flash('%s (%s, %s)' % (msg, resource_type, url), 'success')
    except Exception as err:
        DB.session.rollback()
        flash(str(err), 'danger')
        return redirect(url_for('home', lang=g.current_lang))

    if len(resources_to_add) == 1:
        return edit_resource(resources_to_add[0].identifier)
    return redirect(url_for('home', lang=g.current_lang))