Beispiel #1
0
 def test_case_5(self):
     song = song_list[5]['song']
     true_genre = song.genre
     run_all(rule_list=self.rules,
             defined_variables=SongVariables(song),
             defined_actions=SongActions(song),
             stop_on_first_trigger=False)
Beispiel #2
0
def checkout_order(order_number):

    order = Order.objects.get(order_number=order_number)
    rules = get_rules()

    # implement promotion rules
    order_regular_price = 0
    order_actual_price = 0

    for od in order.details.all():

        run_all(rule_list=rules,
                defined_variables=OrderDetailVariables(od),
                defined_actions=OrderDetailActions(od),
                )

        order_regular_price += od.regular_price
        order_actual_price += od.actual_price or 0

    order.regular_price = order_regular_price
    order.actual_price = order_actual_price
    order.status = Order.ORDER_STATUS_READY
    order.save()

    return order
Beispiel #3
0
def renewal_event_is_fired_after_one_month(context):
    # after 1 month , AllocationSourceSnapshot is first updated.

    report_start_date = context.ts
    report_end_date = context.ts + timedelta(days=30)
    query = EventTable.objects.filter(name='allocation_source_renewed',
                                      payload__name__exact='DefaultAllocationSource')
    assert len(query) == 0
    source_snapshot = AllocationSourceSnapshot.objects.filter(allocation_source=context.allocation_source_2).order_by(
        'updated').last()
    assert total_usage(context.amit.user.username, report_start_date,
                       allocation_source_name=context.allocation_source_2.name,
                       end_date=report_end_date) == 72.0
    source_snapshot.compute_used = total_usage(context.amit.user.username, report_start_date,
                                               allocation_source_name=context.allocation_source_2.name,
                                               end_date=report_end_date)
    source_snapshot.updated = context.ts + timedelta(days=29)
    source_snapshot.save()

    assert AllocationSourceSnapshot.objects.filter(allocation_source=context.allocation_source_2).order_by(
        'updated').last().compute_used == 72.0

    # rules engine is explicitly run

    current_time = context.ts + timedelta(days=30)
    run_all(rule_list=cyverse_rules,
            defined_variables=CyverseTestRenewalVariables(context.allocation_source_2, current_time),
            defined_actions=CyverseTestRenewalActions(context.allocation_source_2, current_time),
            )

    query = EventTable.objects.filter(name='allocation_source_renewed', payload__name__exact='DefaultAllocationSource')
    assert len(query) == 1
Beispiel #4
0
    def get_feed_for_username(username):
        Logger(__name__).info('Getting feed for user {}.'.format(username))

        # get all stories by iterating over usernames, use username to filter private, non-friend ones
        stories_feed_data = User.get_feed_data(username)

        Logger(__name__).info(
            'Prioritizing {} stories for user {}\'s feed.'.format(
                len(stories_feed_data), username))

        # calculate priorities
        for story_feed_data in stories_feed_data:
            set_score(story_feed_data, INITIAL_SCORE)

            run_all(rule_list=rules,
                    stop_on_first_trigger=False,
                    defined_actions=StoryActions(story_feed_data),
                    defined_variables=StoryVariables(story_feed_data))

        prioritized_stories = [
            story_feed_data['story_id']
            for story_feed_data in sorted(stories_feed_data,
                                          key=lambda sfd: get_score(sfd),
                                          reverse=True)
        ]

        Logger(__name__).info('Serving feed for user {}.'.format(username))
        # get stories in according order, add feed-specific fields of user's name and profile pic
        return [
            FeedBuilder._format_feed_story(story_id)
            for story_id in prioritized_stories
        ]
Beispiel #5
0
 def iterate(self, *args, **kwargs):
     vehicles = Vehicle.objects.filter(Vehicle_DELETED=False)
     for i in vehicles:
         run_all(rule_list=self.rules,
                 defined_variables=VehicleVariable(i),
                 defined_actions=VehicleActions(i, self.recall),
                 stop_on_first_trigger=False)
Beispiel #6
0
    def update(self, request, *args, **kwargs):
        order = self.get_object()
        new_status = order.status
        if order.status == UNASSIGNED_STATUS:
            if not request.user.is_delivery:
                return Response(
                    {'error': 'only a delivery user can self-assign an order'},
                    status=status.HTTP_400_BAD_REQUEST)
            new_status = IN_PROGRESS_STATUS
            order.delivery_price = BASE_PRICE
            run_all(rule_list=rules,
                    defined_variables=OrderVariables(order),
                    defined_actions=OrderActions(order))
            order.delivery_user = request.user
        elif order.status == IN_PROGRESS_STATUS:
            new_status = DELIVERED_STATUS
            order.delivery_user.balance += DELIVERY_PERCENTAGE_FEE * order.delivery_price
            order.delivery_user.save()
        elif order.status == DELIVER_ERROR_STATUS:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        order.status = new_status
        order.save()
        self.notify_client(new_status, order.client_user, order.delivery_user)
        return Response(status=status.HTTP_200_OK)
Beispiel #7
0
def update_snapshot_cyverse(start_date=None, end_date=None):
    logger.debug("update_snapshot_cyverse task started at %s." %
                 datetime.now())
    end_date = timezone.now().replace(
        microsecond=0) if not end_date else end_date

    for allocation_source in AllocationSource.objects.order_by('name'):
        # calculate and save snapshots here
        allocation_source_name = allocation_source.name
        last_renewal_event = EventTable.objects.filter(
            name='allocation_source_created_or_renewed',
            payload__allocation_source_name__exact=str(
                allocation_source_name)).order_by('timestamp')

        if not last_renewal_event:
            logger.info('Allocation Source %s Create/Renewal event missing',
                        allocation_source_name)
            continue

        start_date = last_renewal_event.last().timestamp.replace(
            microsecond=0) if not start_date else start_date

        total_compute_used = 0
        total_burn_rate = 0
        for user in allocation_source.all_users:
            compute_used, burn_rate = total_usage(
                user.username,
                start_date=start_date,
                end_date=end_date,
                allocation_source_name=allocation_source_name,
                burn_rate=True)

            UserAllocationSnapshot.objects.update_or_create(
                allocation_source=allocation_source,
                user=user,
                defaults={
                    'compute_used': compute_used,
                    'burn_rate': burn_rate
                })
            total_compute_used += compute_used
            total_burn_rate += burn_rate
        AllocationSourceSnapshot.objects.update_or_create(
            allocation_source=allocation_source,
            defaults={
                'compute_used': total_compute_used,
                'global_burn_rate': total_burn_rate
            })

        run_all(
            rule_list=cyverse_rules,
            defined_variables=CyverseTestRenewalVariables(
                allocation_source, end_date, start_date),
            defined_actions=CyverseTestRenewalActions(allocation_source,
                                                      end_date),
        )
    # At the end of the task, fire-off an allocation threshold check
    logger.debug("update_snapshot_cyverse task finished at %s." %
                 datetime.now())
    allocation_threshold_check.apply_async()
Beispiel #8
0
 def test_case_26_to_50(self):
     for i in range(26, 50):
         song = song_list[i]['song']
         true_genre = song.genre
         run_all(rule_list=self.rules,
                 defined_variables=SongVariables(song),
                 defined_actions=SongActions(song),
                 stop_on_first_trigger=False)
def set_importance(video, rules):
    video['importance'] = 0
    variables = VideoVariables(video)
    actions = VideoActions(video, variables)
    run_all(rule_list=rules,
            defined_variables=variables,
            defined_actions=actions,
            stop_on_first_trigger=False)
Beispiel #10
0
 def run(self):
     self.get_attribs()
     run_all(rule_list=self.rules,
             defined_variables=SongVariables(self.song),
             defined_actions=SongActions(self.song),
             stop_on_first_trigger=False)
     self.genre_var.set(self.song.genre)
     self.update_idletasks()
Beispiel #11
0
 def calculate_price(self):
     run_all(
         rule_list=self.user_rules,
         defined_actions=DeliveryActions(self),
         defined_variables=DeliveryVariables(self)
     )
     price = self.base_price - self.get_total_discounts() + self.get_total_charges()
     if price < 0: return 0
     return price
Beispiel #12
0
 def calculate_delivery_pay(self):
     if not self.base_price: self.calculate_price()
     price = self.base_price*0.85
     run_all(
         rule_list=self.delivery_rules,
         defined_actions=DeliveryActions(self),
         defined_variables=DeliveryVariables(self)
     )
     price = price - self.get_delivery_discounts(price) + self.get_delivery_raises(price)
     if price < 0: return 0
     return price
Beispiel #13
0
    def evaluate_rule_set(self,
                          rule_set: RuleSet,
                          data: dict,
                          stop_on_first_trigger: bool = True):
        variables = self._build_variables_object(data)
        actions = self._build_action_object()

        run_all(rule_list=self._generate_rules(rule_set, data),
                defined_variables=variables(data),
                defined_actions=actions(data),
                stop_on_first_trigger=stop_on_first_trigger)
Beispiel #14
0
def runRule(request, physicianId):
    p = get_object_or_404(Physician, pk=physicianId)
    objs = Rule.objects.all()
    rules = []
    for obj in objs:
        rules.append(json.loads(obj.content))
    products = Physician.objects.all()
    for product in products:
        run_all(rules, ProductVariables(product), ProductActions(product),
                False)
    return HttpResponseRedirect(reverse('view', args=[physicianId]))
Beispiel #15
0
    def process_data(data):
        rules = []
        rules.extend(comments_rules)
        rules.extend(reactions_rules)
        rules.extend(past_days_rules)
        rules.extend(friends_rules)
        rules.extend(stories_rules)

        run_all(rule_list=rules,
                defined_variables=StoriePriorityDataVariables(data),
                defined_actions=StoriePriorityDataActions(data),
                stop_on_first_trigger=False)
Beispiel #16
0
 def confusion_matrix(self):
     df = DataFrame(index=range(0, 50), columns=['true', 'predict'])
     for i in range(0, 50):
         song = song_list[i]['song']
         true_genre = str(song.genre)
         run_all(rule_list=self.rules,
                 defined_variables=SongVariables(song),
                 defined_actions=SongActions(song),
                 stop_on_first_trigger=False)
         df.loc[i] = [true_genre, song.genre]
     cnf_matrix = ConfusionMatrix(df['true'], df['predict'])
     cnf_matrix.plot()
     plt.show()
Beispiel #17
0
    def priorizar(self, videos, autores):
        '''
        Dado un iterable de diccionarios que representan videos,
        devuelve una lista con los diccionarios ordenados por
        importancia.
        '''
        videos_procesados = []
        for video in map(lambda va: Video(va[0], va[1]), zip(videos, autores)):
            run_all(self.reglas,
                    defined_variables=VariablesVideo(video),
                    defined_actions=AccionesVideo(video))
            videos_procesados.append(video)

        return [(video.importancia, video.datos_video) for video in sorted(
            videos_procesados, key=lambda e: e.importancia, reverse=True)]
Beispiel #18
0
def info(request,patient_id):
    hb = request.POST.get('heartratebeat')
    ol = request.POST.get('oxygenlevel')
    ll = request.POST.get('liquidlevel')
    patient = Patient.objects.get(id=int(patient_id))
    try:
        monitoring = MonitoringInfo.objects.create(heartratebeat=int(hb),oxygenlevel=int(ol),liquidlevel=int(ll),patient=patient)
        monitoring.save()
    except:
        return HttpResponse(status=400)
    rules = Rule.objects.filter(ruletype=Rule.monitoringRule).order_by('-priority')
    engRules = []
    for rule in rules:
        engRules.append(json.loads(rule.content))

    my_file = Path("./monitoring/custom_variables_m.py")
    if my_file.is_file():
        module = import_module('.custom_variables_m',package="monitoring")
        for rule in engRules:
            l = []
            l.append(rule)
            monitoringActions = MonitoringActions()
            run_all(rule_list=l,
                defined_variables=module.CustomMonitoringVariables(monitoring,patient),
                defined_actions=monitoringActions,
                stop_on_first_trigger=False
            )
            if monitoringActions.alarm:
                if Alarm.objects.filter(alarm=monitoringActions.name,patientId=patient.id,solved=False).first() is None:
                    alarm  = Alarm.objects.create(alarm=monitoringActions.name,patientId=patient.id,patient=patient.name+" "+patient.surname,solved=False)
                    alarm.save()
            
    else:
        for rule in engRules:
            l = []
            l.append(rule)
            monitoringActions = MonitoringActions()
            run_all(rule_list=l,
                defined_variables=MonitoringVariables(monitoring,patient),
                defined_actions=monitoringActions,
                stop_on_first_trigger=False
            )
            if monitoringActions.alarm:
                if Alarm.objects.filter(alarm=monitoringActions.name,patientId=patient.id,solved=False).first() is None:
                    alarm  = Alarm.objects.create(alarm=monitoringActions.name,patientId=patient.id,patient=patient.name+" "+patient.surname,solved=False)
                    alarm.save()
    
    return HttpResponse(status=200)
    def test_renewal_rules(self):
        """Check renewal rules"""
        import datetime
        from business_rules import run_all
        from django.utils import timezone
        from cyverse_allocation.cyverse_rules_engine_setup import CyverseTestRenewalVariables, \
            CyverseTestRenewalActions, cyverse_rules
        from core.models import EventTable

        source_01 = AllocationSourceFactory.create(
            uuid='98e9aed3-1f4c-415c-9ea3-618a8c318eaa',
            name='default_source_01',
            compute_allowed=168,
            start_date=datetime.datetime(2017, 7, 4, hour=12, tzinfo=timezone.utc),
            end_date=None,
            renewal_strategy='default'
        )

        renewal_events_count_before = EventTable.objects.filter(name='allocation_source_created_or_renewed').count()
        self.assertEqual(renewal_events_count_before, 0)

        current_time = datetime.datetime(2017, 7, 5, hour=12, tzinfo=timezone.utc)
        run_all(rule_list=cyverse_rules,
                defined_variables=CyverseTestRenewalVariables(source_01, current_time=current_time,
                                                              last_renewal_event_date=source_01.start_date),
                defined_actions=CyverseTestRenewalActions(source_01, current_time=current_time))

        renewal_events_count_after_one = EventTable.objects.filter(name='allocation_source_created_or_renewed').count()
        self.assertEqual(renewal_events_count_after_one, 0)

        current_time = datetime.datetime(2017, 8, 1, hour=12, tzinfo=timezone.utc)
        run_all(rule_list=cyverse_rules,
                defined_variables=CyverseTestRenewalVariables(source_01, current_time=current_time,
                                                              last_renewal_event_date=source_01.start_date),
                defined_actions=CyverseTestRenewalActions(source_01, current_time=current_time))

        renewal_events_count_after_two = EventTable.objects.filter(name='allocation_source_created_or_renewed').count()
        self.assertEqual(renewal_events_count_after_two, 1)
        last_renewal_event_date = current_time

        current_time = datetime.datetime(2017, 8, 3, hour=12, tzinfo=timezone.utc)
        run_all(rule_list=cyverse_rules,
                defined_variables=CyverseTestRenewalVariables(source_01, current_time=current_time,
                                                              last_renewal_event_date=last_renewal_event_date),
                defined_actions=CyverseTestRenewalActions(source_01, current_time=current_time))

        renewal_events_count_after_three = EventTable.objects.filter(
            name='allocation_source_created_or_renewed').count()
        self.assertEqual(renewal_events_count_after_three, 1)

        current_time = datetime.datetime(2017, 9, 1, hour=12, tzinfo=timezone.utc)
        run_all(rule_list=cyverse_rules,
                defined_variables=CyverseTestRenewalVariables(source_01, current_time=current_time,
                                                              last_renewal_event_date=last_renewal_event_date),
                defined_actions=CyverseTestRenewalActions(source_01, current_time=current_time))

        renewal_events_count_after_four = EventTable.objects.filter(name='allocation_source_created_or_renewed').count()
        self.assertEqual(renewal_events_count_after_four, 2)
Beispiel #20
0
    def run_rules_t(self, a):  # executa a regra

        obj_parameters = Parameters(
            10, 30, 10)  #id_gateway futuramente será trabalhado
        rules = self.get_rules(a)
        # print(rules)
        for i in range(0, len(rules),
                       1):  # percorre a lista que contem as regras
            #print(i)
            if (rules[i]['status']):
                rule = json.loads(
                    rules[i]['jsonRule'])  # extrai as regras do json
                run_all(rule_list=rule,
                        defined_variables=ConditionsRules(obj_parameters),
                        defined_actions=ActionRules(obj_parameters),
                        stop_on_first_trigger=True)
def process_rules(custom_rule_file, descriptor_file_name):
    rules = load_rules_yaml(custom_rule_file)
    storage = DescriptorStorage()

    func = storage.create_function(descriptor_file_name)
    if not func:
        evtLOG.log(
            "Invalid function descriptor, Couldn't store "
            "VNF of file '{0}'".format(descriptor_file_name),
            descriptor_file_name, 'evt_function_invalid_descriptor')
        exit(1)

    for vdu in func.content.get("virtual_deployment_units"):
        descriptor = DescriptorVDU(func.id)
        descriptor._vdu_id = vdu.get("id")
        descriptor._storage = vdu.get("resource_requirements").get("storage")
        descriptor._cpu = vdu.get("resource_requirements").get("cpu")
        descriptor._memory = vdu.get("resource_requirements").get("memory")
        descriptor._network = vdu.get("resource_requirements").get("network")
        descriptor._vdu_images_format = vdu.get("vm_image_format")
        triggered = run_all(
            rule_list=rules,
            defined_variables=DescriptorVariablesVDU(descriptor),
            defined_actions=DescriptorActions(descriptor),
            stop_on_first_trigger=False)
    return descriptor._errors
Beispiel #22
0
    def _callback(ch, method, properties, body):
        try:
            d = json.loads(body)
            idx = np.argwhere(np.asarray(d['idxs']) == args.class_idx)
            if idx.shape[0] < 1:
                return

            conf = d['inferences'][idx[0, 0]]

            inf.last_conf = conf

            run_all(rule_list=rules,
                    defined_variables=InferenceVars(inf),
                    defined_actions=InferenceActs(inf),
                    stop_on_first_trigger=False)

        except Exception as e:
            print('exception ', e)
    def test_rule_engine(self):

        triggered = run_all(rule_list=rules,
                defined_variables=ProductVariables(product),
                defined_actions=ProductActions(product),
                stop_on_first_trigger=True
                )
        assert triggered == True
        assert product.action_triggered == True
Beispiel #24
0
 def test_accuracy(self):
     total = 50
     correct = 0
     df = DataFrame(index=range(0, 50), columns=['true', 'predict'])
     for i in range(0, 50):
         song = song_list[i]['song']
         true_genre = song.genre
         run_all(rule_list=self.rules,
                 defined_variables=SongVariables(song),
                 defined_actions=SongActions(song),
                 stop_on_first_trigger=False)
         df.loc[i] = [true_genre, song.genre]
         if true_genre == song.genre:
             correct += 1
     print(correct / total)
     cnf_matrix = ConfusionMatrix(df['true'], df['predict'])
     cnf_matrix.plot()
     plt.show()
     self.assertGreater((correct / total), 0.5)
Beispiel #25
0
    def _callback(ch, method, properties, body):
        try:
            d = json.loads(body)
            idx = np.argwhere(np.asarray(d['idxs']) == 500)
            if idx.shape[0] < 1:
                print('no receiving inference for class idx', 500)
                sys.exit()

            conf = d['inferences'][idx[0, 0]]

            inf.last_conf = conf

            run_all(rule_list=rules,
                    defined_variables=base.InferenceVars(inf),
                    defined_actions=BackoffActs(inf),
                    stop_on_first_trigger=False)

        except Exception as e:
            print('exception ', e)
    def test_rule_engine_custom_operator(self):

        triggered = run_all(rule_list=rules_custom_operator,
                defined_variables=ProductVariables(product),
                defined_actions=ProductActions(product),
                defined_operators=CustomOperator(CustomType),
                stop_on_first_trigger=False
                )
        assert triggered == True
        assert product.action_triggered == True
Beispiel #27
0
    def _callback(ch, method, properties, body):
        try:
            d = json.loads(body)
            idx = np.argwhere(np.asarray(d['idxs']) == args.index)
            if idx.shape[0] < 1:
                return

            conf = d['inferences'][idx[0, 0]]

            inf.last_conf = conf
            inf.embeddings = np.asarray(d['embeddings'], dtype=np.uint8)
            inf.time = d['time']

            run_all(rule_list=rules,
                    defined_variables=base.InferenceVars(inf),
                    defined_actions=NotificationActs(inf),
                    stop_on_first_trigger=False)

        except Exception as e:
            print('exception ', e)
Beispiel #28
0
def update_snapshot_cyverse(start_date=None, end_date=None):
    logger.debug("update_snapshot_cyverse task started at %s." % datetime.now())
    end_date = timezone.now().replace(microsecond=0) if not end_date else end_date

    for allocation_source in AllocationSource.objects.order_by('name'):
        # calculate and save snapshots here
        allocation_source_name = allocation_source.name
        last_renewal_event = EventTable.objects.filter(
            name='allocation_source_created_or_renewed',
            payload__allocation_source_name__exact=str(allocation_source_name)).order_by('timestamp')

        if not last_renewal_event:
            logger.info('Allocation Source %s Create/Renewal event missing', allocation_source_name)
            continue

        start_date = last_renewal_event.last().timestamp.replace(microsecond=0) if not start_date else start_date

        total_compute_used = 0
        total_burn_rate = 0
        for user in allocation_source.all_users:
            compute_used, burn_rate = total_usage(user.username, start_date=start_date,
                                                  end_date=end_date, allocation_source_name=allocation_source_name,
                                                  burn_rate=True)

            UserAllocationSnapshot.objects.update_or_create(allocation_source=allocation_source, user=user,
                                                            defaults={'compute_used': compute_used,
                                                                      'burn_rate': burn_rate})
            total_compute_used += compute_used
            total_burn_rate += burn_rate
        AllocationSourceSnapshot.objects.update_or_create(allocation_source=allocation_source,
                                                          defaults={'compute_used': total_compute_used,
                                                                    'global_burn_rate': total_burn_rate})

        run_all(rule_list=cyverse_rules,
                defined_variables=CyverseTestRenewalVariables(allocation_source, current_time=end_date,
                                                              last_renewal_event_date=start_date),
                defined_actions=CyverseTestRenewalActions(allocation_source, current_time=end_date))
    # At the end of the task, fire-off an allocation threshold check
    logger.debug("update_snapshot_cyverse task finished at %s." % datetime.now())
    allocation_threshold_check.apply_async()
Beispiel #29
0
    def run_rules_event(
        self, datas_of_rules
    ):  # atributos do datas_of_rules: id da regra que gerou o evento, o status de execução, o valor de sensor, a regra a ser executada

        data_received_of_broker = json.loads(datas_of_rules)

        obj_parameters = Parameters(
            datas_of_rules)  #gera os parametros para executar a regra
        rules = self.get_rules(datas_of_rules)
        obj_parameters = Parameters(
        )  #aqui vai passar o true/false da regra que gerou o evento

        for i in range(0, len(rules),
                       1):  # percorre a lista que contem as regras
            if (rules[i]['status']):
                rule = json.loads(
                    rules[i]['jsonRule'])  # extrai as regras do json
                run_all(rule_list=rule,
                        defined_variables=ConditionsRules(
                            obj_parameters, self.core),
                        defined_actions=ActionRules(obj_parameters, self.core),
                        stop_on_first_trigger=True)
Beispiel #30
0
def run_business():
    beispiel = Vehicle.objects.get(pk=1)
    rules = [{
        "conditions": {
            "all": [
                {
                    "name": "first_registration_date_from",
                    "operator": "greater_than_or_equal_to",
                    "value": "2017-08-01"
                },
            ]
        },
        "actions": [
            {
                "name": "print_result",
            },
        ],
    }]
    run_all(rule_list=rules,
            defined_variables=VehicleVariable(beispiel),
            defined_actions=VehicleActions(beispiel),
            stop_on_first_trigger=True)
def mediainfoRuleEngine(event, context):

    logger.info(json.dumps(event))

    try:
        rulesTable = dynamodb_resource.Table(os.environ['RULEWEB_RULETABLE'])
        mediaInfo = event['mediainfo']
        ruleMappings = event['ruleMappings']

        video = Mediainfo(mediaInfo)

        # Determine Encoding template by running the encoding rules and selecting
        # the first mapped template whose rules is true.

        for ruleMapping in event['ruleMappings']:

            ruleMapping['testCreateTime'] = datetime.utcnow().strftime(
                '%Y-%m-%d %H:%M.%S')

            logger.info("rule: {}".format(
                json.dumps(ruleMapping, indent=4, sort_keys=True)))

            # retrieve the rule expression from the dyanamodb
            response = rulesTable.get_item(
                Key={'name': ruleMapping['ruleName']}, ConsistentRead=True)
            businessRules = response['Item']['rules']

            logger.info("running test {}".format(
                json.dumps(businessRules, cls=DecimalEncoder)))

            ruleMapping['testResult'] = run_all(
                rule_list=[businessRules],
                defined_variables=MediainfoVariables(video),
                defined_actions=MediainfoActions(video),
                stop_on_first_trigger=True)

            logger.info("test result {}".format(
                json.dumps(ruleMapping['testResult'], cls=DecimalEncoder)))

            # Stop on the first rule that evaluates to True as we have found our mapping
            if ruleMapping['testResult'] == True:
                event['selectedRuleString'] = ruleMapping['ruleString']
                break

    except Exception as e:
        logger.info("Exception {}".format(e))
        raise ChaliceViewError("Exception '%s'" % e)

    logger.info('Event: %s', json.dumps(event))

    return event
def process_rules(custom_rule_file, descriptor_file_name):
    # def process_rules(custom_rule_file):

    # Read YAML rule file
    if not os.path.isfile(custom_rule_file):
        log.error("Invalid custom rule file")
        exit(1)

    try:
        fn_custom_rule = open(custom_rule_file, "r")
    except IOError:
        log.error("Error opening custom rule file: "
                  "File does not appear to exist.")
        exit(1)

    try:
        rules = yaml.load(fn_custom_rule)
    except (yaml.YAMLError, yaml.MarkedYAMLError) as e:
        log.error("The rule file seems to have contain invalid YAML syntax."
                  " Please fix and try again. Error: {}".format(str(e)))
        exit(1)

    storage = DescriptorStorage()
    # descriptor_source = read_descriptor_file(descriptor_file_name)
    func = storage.create_function(descriptor_file_name)
    if not func:
        evtlog.log(
            "Invalid function descriptor, Couldn't store "
            "VNF of file '{0}'".format(descriptor_file_name),
            descriptor_file_name, 'evt_function_invalid_descriptor')
        exit(1)

    # TODO populate descriptor from file
    # descriptor= Descriptor(func,"cona",1000,5,5,1)
    descriptor = Descriptor(func)

    variables = DescriptorVariables(descriptor)
    rule_to_export = export_rule_data(DescriptorVariables, DescriptorActions)

    # print("DUMP OF RULES: \n"+json.dumps(rules))
    # Execute all the rules

    triggered = run_all(rule_list=rules,
                        defined_variables=DescriptorVariables(descriptor),
                        defined_actions=DescriptorActions(descriptor),
                        stop_on_first_trigger=False)
    return descriptor.errors
Beispiel #33
0
    def run(self, rules, variables, patient):

        # load variables and actions for rule;
        v = Variables(variables)
        a = Actions(patient)

        # if rule is not a list, wrap the rule in list;
        if isinstance(rules, dict):
            rules = [rules]

        # run all the rules given progressively;
        check = run_all(rule_list=rules,
                        defined_variables=v,
                        defined_actions=a,
                        stop_on_first_trigger=False)

        return a._patient
Beispiel #34
0
def renewal_event_is_fired_twice(context):
    # after another 14 days , AllocationSourceSnapshot is updated.

    report_start_date = context.ts + timedelta(days=30)
    report_end_date = report_start_date + timedelta(days=43)
    query = EventTable.objects.filter(name='allocation_source_renewed',
                                      payload__name__exact='DefaultAllocationSource')
    assert len(query) == 1
    source_snapshot = AllocationSourceSnapshot.objects.filter(allocation_source=context.allocation_source_2).order_by(
        'updated').last()

    amit_usage = total_usage(context.amit.user.username, report_start_date,
                             allocation_source_name=context.allocation_source_2.name,
                             end_date=report_end_date)

    julian_usage = total_usage(context.julian.user.username, report_start_date,
                               allocation_source_name=context.allocation_source_2.name,
                               end_date=report_end_date)

    assert amit_usage == 120.0
    assert julian_usage == 96.0

    source_snapshot.compute_used = amit_usage + julian_usage
    source_snapshot.updated = context.ts + timedelta(days=43)
    source_snapshot.save()

    assert AllocationSourceSnapshot.objects.filter(allocation_source=context.allocation_source_2).order_by(
        'updated').last().compute_used == 216.0

    # rules engine is explicitly run

    current_time = context.ts + timedelta(days=44)
    run_all(rule_list=cyverse_rules,
            defined_variables=CyverseTestRenewalVariables(context.allocation_source_2, current_time),
            defined_actions=CyverseTestRenewalActions(context.allocation_source_2, current_time),
            )

    assert EventTable.objects.filter(name='allocation_source_renewed') == 2

    # after another 14 days , AllocationSourceSnapshot is updated.

    report_start_date = context.ts + timedelta(days=44)
    report_end_date = report_start_date + timedelta(days=57)
    query = EventTable.objects.filter(name='allocation_source_renewed',
                                      payload__name__exact='DefaultAllocationSource')

    source_snapshot = AllocationSourceSnapshot.objects.filter(allocation_source=context.allocation_source_2).order_by(
        'updated').last()

    amit_usage = total_usage(context.amit.user.username, report_start_date,
                             allocation_source_name=context.allocation_source_2.name,
                             end_date=report_end_date)

    julian_usage = total_usage(context.julian.user.username, report_start_date,
                               allocation_source_name=context.allocation_source_2.name,
                               end_date=report_end_date)

    assert amit_usage == 0.0
    assert julian_usage == 192.0

    source_snapshot.compute_used = amit_usage + julian_usage
    source_snapshot.updated = context.ts + timedelta(days=57)
    source_snapshot.save()

    assert AllocationSourceSnapshot.objects.filter(allocation_source=context.allocation_source_2).order_by(
        'updated').last().compute_used == 192.0

    # rules engine is explicitly run

    current_time = context.ts + timedelta(days=58)
    run_all(rule_list=cyverse_rules,
            defined_variables=CyverseTestRenewalVariables(context.allocation_source_2, current_time),
            defined_actions=CyverseTestRenewalActions(context.allocation_source_2, current_time),
            )

    assert EventTable.objects.filter(name='allocation_source_renewed') == 3
Beispiel #35
0
            "value": "True",
        }, {
            "name": "today",
            "operator": "after_than_or_equal_to",
            "value": "2017-01-16",
        }]
    },
    "actions": [{
        "name": "log",
        "params": {
            "message": "All criteria met!",
        }
    }]
}, {
    "actions": [{
        "name": "log",
        "params": {
            "message": "Rule with no conditions triggered!",
        }
    }]
}]

hot_drink = Item(code=1, name='Hot Drink', line_number=1, quantity=1)
pastry = Item(code=2, name='Pastry', line_number=2, quantity=1)
basket = Basket(id=0, items=[hot_drink, pastry])
run_all(
    rule_list=rules,
    defined_variables=ExampleVariables(basket),
    defined_actions=ExampleActions(basket),
)