Exemplo n.º 1
0
def update_all_rules():
    """Set next active rules for all branches."""
    try:
        for i in range(1, len(RULES_FOR_BRANCHES)):
            set_next_rule_to_redis(i, database.get_next_active_rule(i))
        logging.info("Rules updated")
    except Exception as e:
        logging.error(
            "Exeption occured while updating all rules. {0}".format(e))
Exemplo n.º 2
0
def deactivate_branch():
    """Route is used to disable branch."""
    """Can be executed manaully - row will be added to database
    or with rules service - no new row will be added to database"""
    branch_id = int(request.args.get('id'))
    mode = request.args.get('mode')
    if (mode is None):
        logging.error("no 'mode' parameter passed")
        abort(500)

    try:
        response_off = retry_branch_off(branch_id=branch_id)
    except Exception as e:
        logging.error(e)
        logging.error("Can't turn off branch id={0}. Exception occured".format(
            branch_id))
        abort(500)

    if (mode == 'manually'):
        now = datetime.datetime.now()
        if get_next_rule_from_redis(branch_id) is not None:
            database.update(database.QUERY[mn() + '_1'].format(
                get_next_rule_from_redis(branch_id)['interval_id']))
        else:
            database.update(database.QUERY[mn() + '_2'].format(
                branch_id, 2, 4, now.date(), now, None))

        set_next_rule_to_redis(branch_id,
                               database.get_next_active_rule(branch_id))
        logging.info("Rule '{0}' added".format(
            str(get_next_rule_from_redis(branch_id))))

        logging.info("Branch '{0}' deactivated manually".format(branch_id))
    else:
        logging.info('No new entries is added to database.')

    arr = form_responce_for_branches(response_off)
    send_branch_status_message('branch_status', arr)

    return jsonify(branches=arr)
Exemplo n.º 3
0
def form_responce_for_branches(payload):
    """Return responce with rules."""
    try:
        res = [None] * BRANCHES_LENGTH
        payload = convert_to_obj(payload)
        for branch in payload:
            status = branch['state']
            branch_id = branch['id']

            last_rule = database.get_last_start_rule(branch_id)
            next_rule = database.get_next_active_rule(branch_id)

            res[int(branch_id)] = {
                'id': branch_id,
                'status': status,
                'next_rule': next_rule,
                'last_rule': last_rule
            }
        return res
    except Exception as e:
        logging.error(e)
        logging.error("Can't form responce. Exception occured")
        raise e
Exemplo n.º 4
0
def enable_rule():
    """Synch with redis each 10 seconds. Execute rules if any."""
    try:
        logging.info("enable rule thread started.")

        logging.info("Updating rules on start.")
        update_all_rules()
        logging.debug("rules updated")

        sync_rules_from_redis()
        rules_to_log()

        now_time = datetime.datetime.now()
        while True:
            # logging.info("enable_rule_daemon heartbeat. RULES_FOR_BRANCHES: {0}".format(str(RULES_FOR_BRANCHES)))
            time.sleep(10)
            sync_rules_from_redis()

            for rule in RULES_FOR_BRANCHES:
                if rule is None:
                    continue

                delta = datetime.datetime.now() - now_time
                if delta.seconds >= 60 * 10:
                    rules_to_log()
                    now_time = datetime.datetime.now()

                if (datetime.datetime.now() >=
                    (rule['timer'] -
                     datetime.timedelta(minutes=VIBER_SENT_TIMEOUT))):
                    try:
                        send_to_viber_bot(rule)
                    except Exception as e:
                        logging.error(
                            "Can't send rule {0} to viber. Exception occured. {1}"
                            .format(str(rule), e))

                if (datetime.datetime.now() >= rule['timer']):
                    if (inspect_conditions(rule) is False):
                        logging.info(
                            "Rule can't be executed cause of rain volume too high"
                        )
                        database.update(
                            database.QUERY[mn() + "_canceled_by_rain"].format(
                                rule['id']))
                        set_next_rule_to_redis(
                            rule['line_id'],
                            database.get_next_active_rule(rule['line_id']))
                        continue

                    logging.info("Rule '{0}' execution started".format(
                        str(rule)))

                    try:
                        if rule['rule_id'] == 1:
                            branch_on(rule['line_id'], rule['time'])

                        if rule['rule_id'] == 2:
                            branch_off(rule['line_id'])

                    except Exception as e:
                        logging.error(
                            "Rule '{0}' can't be executed. Exception occured. {1}"
                            .format(str(rule), e))
                        # Set failed state
                        database.update(
                            database.QUERY[mn() + '_cancel_interval'].format(
                                rule['interval_id'], 3))
                        database.update(database.QUERY[mn()].format(
                            rule['id'], 3))
                    else:
                        logging.info("Rule '{0}' is done.".format(str(rule)))
                        # Set ok state
                        database.update(database.QUERY[mn()].format(
                            rule['id'], 2))
                    finally:
                        logging.info("get next active rule")
                        set_next_rule_to_redis(
                            rule['line_id'],
                            database.get_next_active_rule(rule['line_id']))
    except Exception as e:
        logging.error("enable rule thread exception occured. {0}".format(e))
    finally:
        logging.info("enable rule thread stopped.")
Exemplo n.º 5
0
def activate_branch():
    """Blablbal."""
    # ============ check input params =======================
    mode = request.args.get('mode')
    if (mode is None):
        logging.error("no 'mode' parameter passed")
        abort(500)

    if (mode == 'single'):
        branch_id = int(request.args.get('id'))
        time_min = int(request.args.get('time_min'))
    elif (mode == 'interval'):
        branch_id = int(request.args.get('id'))
        time_min = int(request.args.get('time_min'))
        time_wait = int(request.args.get('time_wait'))
        num_of_intervals = int(request.args.get('quantity'))
    elif (mode == 'auto'):
        branch_id = int(request.args.get('id'))
        time_min = int(request.args.get('time_min'))
    else:
        logging.error("incorrect mode parameter passed: {0}".format(mode))
        abort(500)
    # ============ check input params =======================

    try:
        response_arr = retry_branch_on(branch_id=branch_id, time_min=time_min)
    except Exception as e:
        logging.error(e)
        logging.error(
            "Can't turn on branch id={0}. Exception occured".format(branch_id))
        abort(500)

    # needs to be executed in both cases single and interval, but in in auto
    if (mode != 'auto'):
        interval_id = str(uuid.uuid4())
        now = datetime.datetime.now()
        stop_time = now + datetime.timedelta(minutes=time_min)

        database.update(database.QUERY[mn() + '_1'].format(
            branch_id, 1, 2, now.date(), now, interval_id, time_min))
        lastid = database.update(database.QUERY[mn() + '_1'].format(
            branch_id, 2, 1, now.date(), stop_time, interval_id, 0))
        logging.debug("lastid:{0}".format(lastid))

        res = database.select(database.QUERY[mn() + '_2'].format(lastid),
                              'fetchone')
        logging.debug("res:{0}".format(res[0]))

        set_next_rule_to_redis(
            branch_id, {
                'id': res[0],
                'line_id': res[1],
                'rule_id': res[2],
                'user_friendly_name': res[6],
                'timer': res[3],
                'interval_id': res[4],
                'time': res[5]
            })
        logging.info("Rule '{0}' added".format(
            str(database.get_next_active_rule(branch_id))))

    if (mode == 'interval'):
        # first interval is already added
        for x in range(2, num_of_intervals + 1):
            start_time = stop_time + datetime.timedelta(minutes=time_wait)
            stop_time = start_time + datetime.timedelta(minutes=time_min)
            database.update(database.QUERY[mn() + '_1'].format(
                branch_id, 1, 1, now.date(), start_time, interval_id,
                time_min))
            database.update(database.QUERY[mn() + '_1'].format(
                branch_id, 2, 1, now.date(), stop_time, interval_id, 0))
            logging.info(
                "Start time: {0}. Stop time: {1} added to database".format(
                    str(start_time), str(stop_time)))

    if (mode == 'auto'):
        logging.info(
            "Branch '{0}' activated from rules service".format(branch_id))
    else:
        logging.info("Branch '{0}' activated manually".format(branch_id))

    arr = form_responce_for_branches(response_arr)
    send_branch_status_message('branch_status', arr)

    return jsonify(branches=arr)