summaryrefslogtreecommitdiffstats
path: root/docs/apex
diff options
context:
space:
mode:
authoraditya.puthuparambil <aditya.puthuparambil@est.tech>2020-04-06 16:00:03 +0100
committeraditya puthuparambil <aditya.puthuparambil@est.tech>2020-04-06 15:01:41 +0000
commit935358b4bfcf551ec780a4f6342032ac2a00376d (patch)
tree3a6747bab03c8608503aaa3cdaa629cd056b5110 /docs/apex
parentc80213e91c20dca8794a7d7540d9afb876b6d693 (diff)
Apex-pdp documentation conversion from .adoc to .rst
Issue-ID: POLICY-2424 Signed-off-by: aditya.puthuparambil <aditya.puthuparambil@est.tech> Change-Id: Ic72f5cabe74d389ebafbcc8008525ef0831bd9b4
Diffstat (limited to 'docs/apex')
-rw-r--r--docs/apex/APEX-MyFirstPolicyExample.rst2268
-rw-r--r--docs/apex/APEX-PCVS-Example.rst2954
-rw-r--r--docs/apex/APEX-Policy-Examples.rst83
-rw-r--r--docs/apex/APEX-Policy-Guide.rst76
-rw-r--r--docs/apex/events/1/EventIn_BoozeItem_084106GMT.json12
-rw-r--r--docs/apex/events/1/EventIn_BoozeItem_201713GMT.json12
-rw-r--r--docs/apex/events/1/EventIn_NonBoozeItem_101309GMT.json13
-rw-r--r--docs/apex/events/1/EventOut_BoozeItem_084106GMT.json17
-rw-r--r--docs/apex/events/1/EventOut_BoozeItem_201713GMT.json17
-rw-r--r--docs/apex/events/1/EventOut_NonBoozeItem_101309GMT.json17
-rw-r--r--docs/apex/events/1/EventsIn.json.txt37
-rw-r--r--docs/apex/events/1/EventsOut.json.txt51
-rw-r--r--docs/apex/events/2/EventIn_BoozeItem_101433CET_thurs.json12
-rw-r--r--docs/apex/events/2/EventIn_BoozeItem_171937CET_sun.json13
-rw-r--r--docs/apex/events/2/EventIn_NonBoozeItem_111309CET_mon.json13
-rw-r--r--docs/apex/events/2/EventOut_BoozeItem_101433CET_thurs.json17
-rw-r--r--docs/apex/events/2/EventOut_BoozeItem_171937CET_sun.json17
-rw-r--r--docs/apex/events/2/EventOut_NonBoozeItem_111309CET_mon.json17
-rw-r--r--docs/apex/events/2/EventsIn.json.txt75
-rw-r--r--docs/apex/events/2/EventsOut.json.txt102
-rw-r--r--docs/apex/images/pcvs/vpnsla-arch.pngbin0 -> 118373 bytes
21 files changed, 5747 insertions, 76 deletions
diff --git a/docs/apex/APEX-MyFirstPolicyExample.rst b/docs/apex/APEX-MyFirstPolicyExample.rst
new file mode 100644
index 00000000..52991add
--- /dev/null
+++ b/docs/apex/APEX-MyFirstPolicyExample.rst
@@ -0,0 +1,2268 @@
+.. This work is licensed under a Creative Commons Attribution 4.0 International License.
+.. http://creativecommons.org/licenses/by/4.0
+
+.. _apex-myFirstExample:
+
+HowTo: My First Policy
+**********************
+
+.. contents::
+ :depth: 3
+
+Introduction
+^^^^^^^^^^^^
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ Consider a scenario where a supermarket chain called
+ *HyperM* controls how it sells items in a policy-based
+ manner. Each time an item is processed by *HyperM*'s
+ point-of-sale (PoS) system an event is generated and
+ published about that item of stock being sold. This
+ event can then be used to update stock levels, etc..
+
+ .. container:: paragraph
+
+ *HyperM* want to extend this approach to allow some
+ checks to be performed before the sale can be
+ completed. This can be achieved by requesting a
+ policy-controlled decision as each item is processed
+ by for sale by each PoS system. The decision process
+ is integrated with *HyperM*'s other IT systems that
+ manage stock control, sourcing and purchasing,
+ personnel systems, etc.
+
+ .. container:: paragraph
+
+ In this document we will show how APEX and APEX
+ Policies can be used to achieve this, starting with a
+ simple policy, building up to more complicated policy
+ that demonstrates the features of APEX.
+
+Data Models
+^^^^^^^^^^^
+
+ .. container:: sectionbody
+
+ .. container:: sect2
+
+ .. rubric:: Sales Decision Event
+ :name: sales_decision_event
+
+ .. container:: paragraph
+
+ Each time a PoS system processes a sales item an
+ event with the following format is emitted:
+
+ .. table:: Table 1. Sale Input Event
+
+ +----------------------+----------------------+-----------------------+
+ | Event | Fields | Description |
+ +======================+======================+=======================+
+ | SALE_INPUT | time, sale_ID, | Event indicating a |
+ | | amount, item_ID, | sale of an item is |
+ | | quantity, | occurring |
+ | | assistant_ID, | |
+ | | branch_ID, notes, …​ | |
+ +----------------------+----------------------+-----------------------+
+
+ .. container:: paragraph
+
+ In each ``SALE_INPUT`` event the ``sale_ID`` field
+ is a unique ID generated by the PoS system. A
+ timestamp for the event is stored in the ``time``
+ field. The ``amount`` field refers to the value of
+ the item(s) to be sold (in cents). The ``item_ID``
+ field is a unique identifier for each item type,
+ and can be used to retrieve more information about
+ the item from *HyperM*'s stock control system. The
+ ``quantity`` field refers to the quantity of the
+ item to be sold. The ``assistant_ID`` field is a
+ unique identifier for the PoS operator, and can be
+ used to retrieve more information about the
+ operator from the *HyperM*'s personnel system.
+ Since *HyperM* has many branches the ``branch_ID``
+ identifies the shop. The ``notes`` field contains
+ arbitrary notes about the sale.
+
+ .. container:: sect2
+
+ .. rubric:: Sales Decision Event
+ :name: sales_decision_event
+
+ .. container:: paragraph
+
+ After a ``SALE_INPUT`` event is emitted by the PoS
+ system *HyperM*'s policy-based controlled sales
+ checking system emits a Sale Authorization Event
+ indicating whether the sale is authorized or
+ denied. The PoS system can then listen for this
+ event before continuing with the sale.
+
+ .. table:: Table 2. Sale Authorisation Event
+
+ +----------------------+----------------------+-----------------------+
+ | Event | Fields | Description |
+ +======================+======================+=======================+
+ | SALE_AUTH | sale_ID, time, | Event indicating a |
+ | | authorized, amount, | sale of an item is |
+ | | item_ID, quantity, | authorized or denied |
+ | | assistant_ID, | |
+ | | branch_ID, notes, | |
+ | | message…​ | |
+ +----------------------+----------------------+-----------------------+
+
+ .. container:: paragraph
+
+ In each ``SALE_AUTH`` event the ``sale_ID`` field
+ is copied from the ``SALE_INPUT`` event that
+ trigger the decision request. The ``SALE_AUTH``
+ event is also timestamped using the ``time`` field,
+ and a field called ``authorised`` is set to
+ ``true`` or ``false`` depending on whether the sale
+ is authorized or denied. The ``message`` field
+ carries an optional message about why a sale was
+ not authorized. The other fields from the
+ ``SALE_INPUT`` event are also included for
+ completeness.
+
+ .. container:: sect2
+
+ .. rubric:: Stock Control: Items
+ :name: stock_control_items
+
+ .. container:: paragraph
+
+ *HyperM* maintains information about each item for
+ sale in a database table called ``ITEMS``.
+
+ .. table:: Table 3. Items Database
+
+ +----------------------+----------------------+-----------------------+
+ | Table | Fields | Description |
+ +======================+======================+=======================+
+ | ITEMS | item_ID, | Database table |
+ | | description, | describing each item |
+ | | cost_price, barcode, | for sale |
+ | | supplier_ID, | |
+ | | category, …​ | |
+ +----------------------+----------------------+-----------------------+
+
+ .. container:: paragraph
+
+ The database table ``ITEMS`` has a row for each
+ items that *HyperM* sells. Each item is identified
+ by an ``item_ID`` value. The ``description`` field
+ stores a description of the item. The cost price of
+ the item is given in ``cost_price``. The barcode of
+ the item is encoded in ``barcode``, while the item
+ supplier is identified by ``supplier_ID``. Items
+ may also be classified into categories using the
+ ``category`` field. Useful categories might
+ include: ``soft drinks``, ``alcoholic drinks``,
+ ``cigarettes``, ``knives``, ``confectionery``,
+ ``bakery``, ``fruit&vegetables``, ``meat``, etc..
+
+ .. container:: sect2
+
+ .. rubric:: Personnel System: Assistants
+ :name: personnel_system_assistants
+
+ .. table:: Table 4. Assistants Database
+
+ +----------------------+----------------------+-----------------------+
+ | Table | Fields | Description |
+ +======================+======================+=======================+
+ | ASSISTANTS | assistant_ID, | Database table |
+ | | surname, firstname, | describing each |
+ | | middlename, age, | *HyperM* sales |
+ | | grade, phone_number, | assistant |
+ | | …​ | |
+ +----------------------+----------------------+-----------------------+
+
+ .. container:: paragraph
+
+ The database table ``ASSISTANTS`` has a row for
+ each sales assistant employed by *HyperM*. Each
+ assistant is identified by an ``assistant_ID``
+ value, with their name given in the ``firstname``,
+ ``middlename`` and ``surname`` fields. The
+ assistant’s age in years is given in ``age``, while
+ their phone number is contained in the
+ ``phone_number`` field. The assistant’s grade is
+ encoded in ``grade``. Useful values for ``grade``
+ might include: ``trainee``, ``operator``,
+ ``supervisor``, etc..
+
+ .. container:: sect2
+
+ .. rubric:: Locations: Branches
+ :name: locations_branches
+
+ .. table:: Table 5. Branches Database
+
+ +----------------------+----------------------+-----------------------+
+ | Table | Fields | Description |
+ +======================+======================+=======================+
+ | BRANCHES | branch_ID, | Database table |
+ | | branch_Name, | describing each |
+ | | category, street, | *HyperM* branch |
+ | | city, country, | |
+ | | postcode, …​ | |
+ +----------------------+----------------------+-----------------------+
+
+ .. container:: paragraph
+
+ *HyperM* operates a number of branches. Each branch
+ is described in the ``BRANCHES`` database table.
+ Each branch is identified by a ``branch_ID``, with
+ a branch name given in ``branch_Name``. The address
+ for the branch is encoded in ``street``, ``city``,
+ ``country`` and ``postcode``. The branch category
+ is given in the ``category`` field. Useful values
+ for ``category`` might include: ``Small``,
+ ``Large``, ``Super``, ``Hyper``, etc..
+
+
+Policy Step 1
+^^^^^^^^^^^^^
+
+ .. container:: sectionbody
+
+ .. container:: sect1
+
+ .. rubric:: Scenario
+ :name: scenario
+
+ .. container:: paragraph
+
+ For the first version of our policy, let’s start
+ with something simple. Let us assume that there
+ exists some restriction that alcohol products
+ cannot be sold before 11:30am. In this section we
+ will go through the necessary steps to define a
+ policy that can enforce this for *HyperM*.
+
+ .. container:: ulist
+
+ - Alcohol cannot be sold before 11:30am... container::
+
+New Policy Model
+----------------
+
+ .. container:: sectionbody
+
+ .. container:: sect1
+
+ .. rubric:: Create the an new empty Policy Model ``MyFirstPolicyModel``
+ :name: create_the_an_new_empty_policy_model_code_myfirstpolicymodel_code
+
+ .. container:: paragraph
+
+ Since an organisation like *HyperM* may have many
+ policies covering many different domains, policies should
+ be grouped into policy sets. In order to edit or deploy a
+ policy, or policy set, the definition of the policy(ies)
+ and all required events, tasks, states, etc., are grouped
+ together into a 'Policy Model'. An organization might
+ define many Policy Models, each containing a different
+ set of policies.
+
+ .. container:: paragraph
+
+ So the first step is to create a new empty Policy Model
+ called ``MyFirstPolicyModel``. Using the APEX Policy
+ Editor, click on the 'File' menus and select 'New'. Then
+ define our new policy model called
+ ``MyFirstPolicyModel``. Use the 'Generate UUID' button to
+ create a new unique ID for the policy model, and fill in
+ a description for the policy model. Press the ``Submit``
+ button to save your changes.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |File > New to create a new Policy Model|
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Create a new Policy Model|
+
+Events
+------
+
+ .. container:: sectionbody
+
+ .. container:: sect1
+
+ .. rubric:: Create the input event ``SALE_INPUT`` and the
+ output event ``SALE_AUTH``
+ :name: create_the_input_event_code_sale_input_code_and_the_output_event_code_sale_auth_code
+
+ .. container:: paragraph
+
+ Using the APEX Policy Editor, click on the 'Events' tab.
+ In the 'Events' pane, right click and select 'New':
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Right click to create a new event|
+
+ .. container:: paragraph
+
+ Create a new event type called ``SALE_INPUT``. Use the
+ 'Generate UUID' button to create a new unique ID for the
+ event type, and fill in a description for the event. Add
+ a namespace, e.g. ``com.hyperm``. We can add hard-coded
+ strings for the ``Source`` and ``Target``, e.g. ``POS``
+ and ``APEX``. At this stage we will not add any parameter
+ fields, we will leave this until later. Use the
+ ``Submit`` button to create the event.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Fill in the necessary information for the
+ 'SALE_INPUT' event and click 'Submit'|
+
+ .. container:: paragraph
+
+ Repeat the same steps for a new event type called
+ ``SALE_AUTH``. Just use ``APEX`` as source and ``POS`` as
+ target, since this is the output event coming from APEX
+ going to the sales point.
+
+ .. container:: paragraph
+
+ Before we can add parameter fields to an event we must
+ first define APEX Context Item Schemas that can be used
+ by those fields.
+
+ .. container:: paragraph
+
+ To create new item schemas, click on the 'Context Item
+ Schemas' tab. In that 'Context Item Schemas' pane, right
+ click and select 'Create new ContextSchema'.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Right click to create a new Item Schema|
+
+ .. container:: paragraph
+
+ Create item schemas with the following characteristics,
+ each with its own unique UUID:
+
+ .. table:: Table 1. Item Schemas
+
+ +-----------------+-----------------+-----------------+-----------------+
+ | Name | Schema Flavour | Schema | Description |
+ | | | Definition | |
+ +=================+=================+=================+=================+
+ | timestamp_type | Java | java.lang.Long | A type for |
+ | | | | ``time`` values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | sale_ID_type | Java | java.lang.Long | A type for |
+ | | | | ``sale_ID`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | price_type | Java | java.lang.Long | A type for |
+ | | | | ``amo |
+ | | | | unt``/``price`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | item_ID_type | Java | java.lang.Long | A type for |
+ | | | | ``item_ID`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | as | Java | java.lang.Long | A type for |
+ | sistant_ID_type | | | ` |
+ | | | | `assistant_ID`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | quantity_type | Java | ja | A type for |
+ | | | va.lang.Integer | ``quantity`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | branch_ID_type | Java | java.lang.Long | A type for |
+ | | | | ``branch_ID`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | notes_type | Java | j | A type for |
+ | | | ava.lang.String | ``notes`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | authorised_type | Java | ja | A type for |
+ | | | va.lang.Boolean | ``authorised`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+ | message_type | Java | j | A type for |
+ | | | ava.lang.String | ``message`` |
+ | | | | values |
+ +-----------------+-----------------+-----------------+-----------------+
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Create a new Item Schema|
+
+ .. container:: paragraph
+
+ The item schemas can now be seen on the 'Context Item
+ Schemas' tab, and can be updated at any time by
+ right-clicking on the item schemas on the 'Context Item
+ Schemas' tab. Now we can go back to the event definitions
+ for ``SALE_INPUT`` and ``SALE_AUTH`` and add some
+ parameter fields.
+
+ .. container:: admonitionblock tip
+
+ .. TIP::
+
+ .. container:: paragraph
+
+ APEX natively supports schema definitions in ``Java`` and ``Avro``.
+ ``Java`` schema definitions are simply the name of a Java Class. There are some restrictions:
+
+ .. container:: ulist
+
+ - the class must be instantiatable, i.e. not an Java interface or abstract class
+
+ - primitive types are not supported, i.e. use ``java.lang.Integer`` instead of ``int``, etc.
+
+ - it must be possible to find the class, i.e. the class must be contained in the Java classpath.
+
+ .. container:: paragraph
+
+ ``Avro`` schema definitions can be any valid `Avro <https://avro.apac
+ he.org/docs/current/spec.html>`__ schema. For events using fields defined with
+ Avro schemas, any incoming event containing that field must contain a value that conforms to the Avro schema.
+
+ .. container:: paragraph
+
+ Click on the 'Events' tab, then right click the
+ ``SALE_INPUT`` row and select 'Edit Event
+ :literal:`SALE_INPUT’. To add a new event parameter use the 'Add Event Parameter' button at the bottom of the screen. For the `SALE_INPUT`
+ event add the following event parameters:
+
+ .. table:: Table 2. Event Parameter Fields for the ``SALE_INPUT`` Event
+
+ +----------------------+----------------------+-----------------------+
+ | Parameter Name | Parameter Type | Optional |
+ +======================+======================+=======================+
+ | time | timestamp_type | no |
+ +----------------------+----------------------+-----------------------+
+ | sale_ID | sale_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | amount | price_type | no |
+ +----------------------+----------------------+-----------------------+
+ | item_ID | item_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | quantity | quantity_type | no |
+ +----------------------+----------------------+-----------------------+
+ | assistant_ID | assistant_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | branch_ID | branch_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | notes | notes_type | *yes* |
+ +----------------------+----------------------+-----------------------+
+
+ .. container:: paragraph
+
+ Remember to click the 'Submit' button at the bottom of
+ the event definition pane.
+
+ .. container:: admonitionblock tip
+
+ .. TIP::
+
+ .. container:: paragraph
+
+ Parameter fields can be *optional* in events. If a parameter is not marked as
+ *optional* then by default it is *mandatory*, so it must appear in any input event
+ passed to APEX. If an *optional* field is not set for an output event then value
+ will be set to ``null``.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Add new event parameters to an event|
+
+ .. container:: paragraph
+
+ Select the ``SALE_AUTH`` event and add the following
+ event parameters:
+
+ .. table:: Table 3. Event Parameter Fields for the ``SALE_AUTH`` Event
+
+ +----------------------+----------------------+-----------------------+
+ | Parameter Name | Parameter Type | no |
+ +======================+======================+=======================+
+ | sale_ID | sale_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | time | timestamp_type | no |
+ +----------------------+----------------------+-----------------------+
+ | authorised | authorised_type | no |
+ +----------------------+----------------------+-----------------------+
+ | message | message_type | *yes* |
+ +----------------------+----------------------+-----------------------+
+ | amount | price_type | no |
+ +----------------------+----------------------+-----------------------+
+ | item_ID | item_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | assistant_ID | assistant_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | quantity | quantity_type | no |
+ +----------------------+----------------------+-----------------------+
+ | branch_ID | branch_ID_type | no |
+ +----------------------+----------------------+-----------------------+
+ | notes | notes_type | *yes* |
+ +----------------------+----------------------+-----------------------+
+
+ .. container:: paragraph
+
+ Remember to click the 'Submit' button at the bottom of
+ the event definition pane.
+
+ .. container:: paragraph
+
+ The events for our policy are now defined.
+
+New Policy
+----------
+
+ .. container:: sectionbody
+
+ .. container:: sect1
+
+ .. rubric:: Create a new Policy and add the *"No Booze
+ before 11:30"* check
+ :name: create_a_new_policy_and_add_the_em_no_booze_before_11_30_em_check
+
+ .. container:: paragraph
+
+ APEX policies are defined using a state-machine model.
+ Each policy comprises one or more *states* that can be
+ individually executed. Where there is more than one
+ *state* the states are chained together to form a
+ `Directed Acyclic Graph
+ (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__
+ of states. A *state* is triggered by passing it a single
+ input (or 'trigger') event and once executed each state
+ then emits an output event. For each *state* the logic
+ for the *state* is embedded in one or more *tasks*. Each
+ *task* contains specific *task logic* that is executed by
+ the APEX execution environment each time the *task* is
+ invoked. Where there is more than one *task* in a *state*
+ then the *state* also defines some *task selection logic*
+ to select an appropriate task each time the *state* is
+ executed.
+
+ .. container:: paragraph
+
+ Therefore, to create a new policy we must first define
+ one or more tasks.
+
+ .. container:: paragraph
+
+ To create a new Task click on the 'Tasks' tab. In the
+ 'Tasks' pane, right click and select 'Create new Task'.
+ Create a new Task called ``MorningBoozeCheck``. Use the
+ 'Generate UUID' button to create a new unique ID for the
+ task, and fill in a description for the task.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Right click to create a new task|
+
+ .. container:: paragraph
+
+ Tasks are configured with a set of *input fields* and a
+ set of *output fields*. To add new input/output fields
+ for a task use the 'Add Task Input Field' and 'Add Task
+ Output Field' button. The list of input and out fields to
+ add for the ``MorningBoozeCheck`` task are given below.
+ The input fields are drawn from the parameters in the
+ state’s input event, and the task’s output fields are
+ used to populate the state’s output event. The task’s
+ input and output fields must be a subset of the event
+ parameters defined for the input and output events for
+ any state that uses that task. (You may have noticed that
+ the input and output fields for the ``MorningBoozeCheck``
+ task have the exact same names and reuse the item schemas
+ that we used for the parameters in the ``SALE_INPUT`` and
+ ``SALE_AUTH`` events respectively).
+
+ .. table:: Table 1. Input fields for ``MorningBoozeCheck`` task
+
+ +-----------------------------------+-----------------------------------+
+ | Parameter Name | Parameter Type |
+ +===================================+===================================+
+ | time | timestamp_type |
+ +-----------------------------------+-----------------------------------+
+ | sale_ID | sale_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | amount | price_type |
+ +-----------------------------------+-----------------------------------+
+ | item_ID | item_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | quantity | quantity_type |
+ +-----------------------------------+-----------------------------------+
+ | assistant_ID | assistant_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | branch_ID | branch_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | notes | notes_type |
+ +-----------------------------------+-----------------------------------+
+
+ .. table:: Table 2. Output fields for ``MorningBoozeCheck`` task
+
+ +-----------------------------------+-----------------------------------+
+ | Parameter Name | Parameter Type |
+ +===================================+===================================+
+ | sale_ID | sale_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | time | timestamp_type |
+ +-----------------------------------+-----------------------------------+
+ | authorised | authorised_type |
+ +-----------------------------------+-----------------------------------+
+ | message | message_type |
+ +-----------------------------------+-----------------------------------+
+ | amount | price_type |
+ +-----------------------------------+-----------------------------------+
+ | item_ID | item_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | assistant_ID | assistant_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | quantity | quantity_type |
+ +-----------------------------------+-----------------------------------+
+ | branch_ID | branch_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | notes | notes_type |
+ +-----------------------------------+-----------------------------------+
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Add input and out fields for the task|
+
+ .. container:: paragraph
+
+ Each task must include some 'Task Logic' that implements
+ the behaviour for the task. Task logic can be defined in
+ a number of different ways using a choice of languages.
+ For this task we will author the logic using the
+ Java-like scripting language called
+ ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__.
+
+ .. container:: paragraph
+
+ For simplicity use the following code for the task logic.
+ Paste the script text into the 'Task Logic' box, and use
+ "MVEL" as the 'Task Logic Type / Flavour'.
+
+ .. container:: paragraph
+
+ This logic assumes that all items with ``item_ID``
+ between 1000 and 2000 contain alcohol, which is not very
+ realistic, but we will see a better approach for this
+ later. It also uses the standard ``Java`` time utilities
+ to check if the current time is between ``00:00:00 GMT``
+ and ``11:30:00 GMT``. For a detailed guide to how to
+ write your own logic in
+ ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
+ ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
+ of the other supported languages please refer to APEX
+ Programmers Guide.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+ import java.util.Date;
+ import java.util.Calendar;
+ import java.util.TimeZone;
+ import java.text.SimpleDateFormat;
+
+ logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
+
+ outFields.put("amount" , inFields.get("amount"));
+ outFields.put("assistant_ID", inFields.get("assistant_ID"));
+ outFields.put("notes" , inFields.get("notes"));
+ outFields.put("quantity" , inFields.get("quantity"));
+ outFields.put("branch_ID" , inFields.get("branch_ID"));
+ outFields.put("item_ID" , inFields.get("item_ID"));
+ outFields.put("time" , inFields.get("time"));
+ outFields.put("sale_ID" , inFields.get("sale_ID"));
+
+ item_id = inFields.get("item_ID");
+
+ //The events used later to test this task use GMT timezone!
+ gmt = TimeZone.getTimeZone("GMT");
+ timenow = Calendar.getInstance(gmt);
+ df = new SimpleDateFormat("HH:mm:ss z");
+ df.setTimeZone(gmt);
+ timenow.setTimeInMillis(inFields.get("time"));
+
+ midnight = timenow.clone();
+ midnight.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),0,0,0);
+ eleven30 = timenow.clone();
+ eleven30.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),11,30,0);
+
+ itemisalcohol = false;
+ if(item_id != null && item_id >=1000 && item_id < 2000)
+ itemisalcohol = true;
+
+ if( itemisalcohol
+ && timenow.after(midnight) && timenow.before(eleven30)){
+ outFields.put("authorised", false);
+ outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime())+
+ ". Alcohol can not be sold between "+df.format(midnight.getTime())+
+ " and "+df.format(eleven30.getTime()));
+ return true;
+ }
+ else{
+ outFields.put("authorised", true);
+ outFields.put("message", "Sale authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime()));
+ return true;
+ }
+
+ /*
+ This task checks if a sale request is for an item that is an alcoholic drink.
+ If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
+ authorised. Otherwise the sale is authorised.
+ In this implementation we assume that items with item_ID value between 1000 and
+ 2000 are all alcoholic drinks :-)
+ */
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Add task logic the task|
+
+ .. container:: paragraph
+
+ An alternative version of the same logic is available in
+ JavaScript. Just use "JAVASCRIPT" as the 'Task Logic Type
+ / Flavour' instead.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+
+ // Load compatibility script for imports etc
+ load("nashorn:mozilla_compat.js");
+ importPackage(java.text);
+ importClass(java.text.SimpleDateFormat);
+
+ executor.logger.info("Task Execution: '"+executor.subject.id+"'. Input Fields: '"+executor.inFields+"'");
+
+ executor.outFields.put("amount" , executor.inFields.get("amount"));
+ executor.outFields.put("assistant_ID", executor.inFields.get("assistant_ID"));
+ executor.outFields.put("notes" , executor.inFields.get("notes"));
+ executor.outFields.put("quantity" , executor.inFields.get("quantity"));
+ executor.outFields.put("branch_ID" , executor.inFields.get("branch_ID"));
+ executor.outFields.put("item_ID" , executor.inFields.get("item_ID"));
+ executor.outFields.put("time" , executor.inFields.get("time"));
+ executor.outFields.put("sale_ID" , executor.inFields.get("sale_ID"));
+
+ item_id = executor.inFields.get("item_ID");
+
+ //All times in this script are in GMT/UTC since the policy and events assume time is in GMT.
+ var timenow_gmt = new Date(Number(executor.inFields.get("time")));
+
+ var midnight_gmt = new Date(Number(executor.inFields.get("time")));
+ midnight_gmt.setUTCHours(0,0,0,0);
+
+ var eleven30_gmt = new Date(Number(executor.inFields.get("time")));
+ eleven30_gmt.setUTCHours(11,30,0,0);
+
+ var timeformatter = new java.text.SimpleDateFormat("HH:mm:ss z");
+
+ var itemisalcohol = false;
+ if(item_id != null && item_id >=1000 && item_id < 2000)
+ itemisalcohol = true;
+
+ if( itemisalcohol
+ && timenow_gmt.getTime() >= midnight_gmt.getTime()
+ && timenow_gmt.getTime() < eleven30_gmt.getTime()) {
+
+ executor.outFields.put("authorised", false);
+ executor.outFields.put("message", "Sale not authorised by policy task " +
+ executor.subject.taskName+ " for time " + timeformatter.format(timenow_gmt.getTime()) +
+ ". Alcohol can not be sold between " + timeformatter.format(midnight_gmt.getTime()) +
+ " and " + timeformatter.format(eleven30_gmt.getTime()));
+ }
+ else{
+ executor.outFields.put("authorised", true);
+ executor.outFields.put("message", "Sale authorised by policy task " +
+ executor.subject.taskName + " for time "+timeformatter.format(timenow_gmt.getTime()));
+ }
+
+ /*
+ This task checks if a sale request is for an item that is an alcoholic drink.
+ If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
+ authorised. Otherwise the sale is authorised.
+ In this implementation we assume that items with item_ID value between 1000 and
+ 2000 are all alcoholic drinks :-)
+ */
+
+ .. container:: paragraph
+
+ The task definition is now complete so click the 'Submit'
+ button to save the task. The task can now be seen on the
+ 'Tasks' tab, and can be updated at any time by
+ right-clicking on the task on the 'Task' tab. Now that we
+ have created our task, we can can create a policy that
+ uses that task.
+
+ .. container:: paragraph
+
+ To create a new Policy click on the 'Policies' tab. In
+ the 'Policies' pane, right click and select 'Create new
+ Policy':
+
+ .. container:: paragraph
+
+ Create a new Policy called ``MyFirstPolicy``. Use the
+ 'Generate UUID' button to create a new unique ID for the
+ policy, and fill in a description for the policy. Use
+ 'FREEFORM' as the 'Policy Flavour'.
+
+ .. container:: paragraph
+
+ Each policy must have at least one state. Since this is
+ 'freeform' policy we can add as many states as we wish.
+ Let’s start with one state. Add a new state called
+ ``BoozeAuthDecide`` to this ``MyFirstPolicy`` policy
+ using the 'Add new State' button after filling in the
+ name of our new state.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Create a new policy|
+
+ .. container:: paragraph
+
+ Each state must uses one input event type. For this new
+ state select the ``SALE_INPUT`` event as the input event.
+
+ .. container:: paragraph
+
+ Each policy must define a 'First State' and a 'Policy
+ Trigger Event'. The 'Policy Trigger Event' is the input
+ event for the policy as a whole. This event is then
+ passed to the first state in the chain of states in the
+ policy, therefore the 'Policy Trigger Event' will be the
+ input event for the first state. Each policy can only
+ have one 'First State'. For our ``MyFirstPolicy`` policy,
+ select ``BoozeAuthDecide`` as the 'First State'. This
+ will automatically select ``SALE_INPUT`` as the 'Policy
+ Trigger Event' for our policy.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Create a state|
+
+ .. container:: paragraph
+
+ In this case we will create a reference the pre-existing
+ ``MorningBoozeCheck`` task that we defined above using
+ the 'Add New Task' button. Select the
+ ``MorningBoozeCheck`` task, and use the name of the task
+ as the 'Local Name' for the task.
+
+ .. container:: paragraph
+
+ in the case where a state references more than one task,
+ a 'Default Task' must be selected for the state and some
+ logic ('Task Selection Logic') must be specified to
+ select the appropriate task at execution time. Since our
+ new state ``BoozeAuthDecide`` only has one task the
+ default task is automatically selected and no 'Task
+ Selection Logic' is required.
+
+ .. container:: admonitionblock note
+
+ .. NOTE::
+
+ .. container:: paragraph
+ In a 'Policy' 'State' a 'State Output Mapping' has 3 roles: 1) Select which 'State'
+ should be executed next, 2) Select the type of the state’s 'Outgoing Event', and
+ 3) Populate the state’s 'Outgoing Event'. This is how states are chained together
+ to form a (`Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__)
+ of states. The final state(s) of a policy are those that do not select any 'next'
+ state. Since a 'State' can only accept a single type of event, the type of the
+ event emitted by a previous 'State' must match the incoming event type of the next
+ 'State'. This is also how the last state(s) in a policy can emit events of
+ different types. The 'State Output Mapping' is also responsible for taking the
+ fields that are output by the task executed in the state and populating the
+ state’s output populating the state’s output event before it is emitted.
+
+ Each 'Task' referenced in 'State' must have a defined 'Output Mapping' to take the output of the task, select an 'Outgoing Event' type for the state, populate the state's outgoing event, and then select the next state to be executed (if any).
+
+ There are 2 basic types of output mappings:
+
+ .. container:: olist arabic
+
+ #. **Direct Output Mappings** have a single value for 'Next State' and a single value for 'State Output Event'. The outgoing event for the state is automatically created, any outgoing event parameters that were present in the incoming event are copied into the outgoing event, then any task output fields that have the same name and type as parameters in the outgoing event are automatically copied into the outgoing event.
+ #. **Logic-Based State Output Mappings / Finalizers** have some logic defined that dynamically selects and creates the 'State Outgoing Event', manages the population of the outgoing event parameters (perhaps changing or adding to the outputs from the task), and then dynamically selects the next state to be executed (if any).
+
+ .. container:: paragraph
+
+ Each task reference must also have an associated 'Output
+ State Mapping' so we need an 'Output State Mapping' for
+ the ``BoozeAuthDecide`` state to use when the
+ ``MorningBoozeCheck`` task is executed. The simplest type
+ of output mapping is a 'Direct Output Mapping'.
+
+ .. container:: paragraph
+
+ Create a new 'Direct Output Mapping' for the state called
+ ``MorningBoozeCheck_Output_Direct`` using the 'Add New
+ Direct State Output Mapping' button. Select ``SALE_AUTH``
+ as the output event and select ``None`` for the next
+ state value. We can then select this output mapping for
+ use when the the ``MorningBoozeCheck`` task is executed.
+ Since there is only state, and only one task for that
+ state, this output mapping ensures that the
+ ``BoozeAuthDecide`` state is the only state executed and
+ the state (and the policy) can only emit events of type
+ ``SALE_AUTH``. (You may remember that the output fields
+ for the ``MorningBoozeCheck`` task have the exact same
+ names and reuse the item schemas that we used for the
+ parameters in ``SALE_AUTH`` event. The
+ ``MorningBoozeCheck_Output_Direct`` direct output mapping
+ can now automatically copy the values from the
+ ``MorningBoozeCheck`` task directly into outgoing
+ ``SALE_AUTH`` events.)
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Add a Task and Output Mapping|
+
+ .. container:: paragraph
+
+ Click the 'Submit' button to complete the definition of
+ our ``MyFirstPolicy`` policy. The policy
+ ``MyFirstPolicy`` can now be seen in the list of policies
+ on the 'Policies' tab, and can be updated at any time by
+ right-clicking on the policy on the 'Policies' tab.
+
+ .. container:: paragraph
+
+ The ``MyFirstPolicyModel``, including our
+ ``MyFirstPolicy`` policy can now be checked for errors.
+ Click on the 'Model' menu and select 'Validate'. The
+ model should validate without any 'Warning' or 'Error'
+ messages. If you see any 'Error' or 'Warning' messages,
+ carefully read the message as a hint to find where you
+ might have made a mistake when defining some aspect of
+ your policy model.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Validate the policy model for error using the 'Model'
+ > 'Validate' menu item|
+
+ .. container:: paragraph
+
+ Congratulations, you have now completed your first APEX
+ policy. The policy model containing our new policy can
+ now be exported from the editor and saved. Click on the
+ 'File' menu and select 'Download' to save the policy
+ model in JSON format. The exported policy model is then
+ available in the directory you selected, for instance
+ ``$APEX_HOME/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json``.
+ The exported policy can now be loaded into the APEX
+ Policy Engine, or can be re-loaded and edited by the APEX
+ Policy Editor.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Download the completed policy model using the 'File'
+ > 'Download' menu item|
+
+Test The Policy
+---------------
+
+ .. container:: sectionbody
+
+ .. container:: sect1
+
+ .. rubric:: Test Policy Step 1
+ :name: test_policy_step_1
+
+ .. container:: paragraph
+
+ To start a new APEX Engine you can use the following
+ configuration. In a full APEX installation you can find
+ this configuration in
+ ``$APEX_HOME/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
+ This configuration expects incoming events to be in
+ ``JSON`` format and to be passed into the APEX Engine
+ from ``stdin``, and result events will be printed in
+ ``JSON`` format to ``stdout``. This configuration loads
+ the policy model stored in the file
+ 'MyFirstPolicyModel_0.0.1.json' as exported from the APEX
+ Editor. Note, you may need to edit this file to provide
+ the full path to wherever you stored the exported policy
+ model file.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "engineServiceParameters" : {
+ "name" : "MyFirstPolicyApexEngine",
+ "version" : "0.0.1",
+ "id" : 101,
+ "instanceCount" : 4,
+ "deploymentPort" : 12345,
+ "policyModelFileName" : "examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json",
+ "engineParameters" : {
+ "executorParameters" : {
+ "MVEL" : {
+ "parameterClassName" : "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
+ },
+ "JAVASCRIPT" : {
+ "parameterClassName" : "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
+ }
+ }
+ }
+ },
+ "eventOutputParameters": {
+ "FirstProducer": {
+ "carrierTechnologyParameters" : {
+ "carrierTechnology" : "FILE",
+ "parameters" : {
+ "standardIO" : true
+ }
+ },
+ "eventProtocolParameters" : {
+ "eventProtocol" : "JSON"
+ }
+ }
+ },
+ "eventInputParameters": {
+ "FirstConsumer": {
+ "carrierTechnologyParameters" : {
+ "carrierTechnology" : "FILE",
+ "parameters" : {
+ "standardIO" : true
+ }
+ },
+ "eventProtocolParameters" : {
+ "eventProtocol" : "JSON"
+ }
+ }
+ }
+ }
+
+ .. container:: paragraph
+
+ To test the policy try paste the following events into
+ the console as the APEX engine executes:
+
+ .. list-table:: Title
+ :widths: 25 40 35
+ :header-rows: 1
+
+ * - Input Event (JSON)
+ - Output Event (JSON)
+ - comment
+ * - .. literalinclude:: events/1/EventIn_NonBoozeItem_101309GMT.json
+ :language: JSON
+ - .. literalinclude:: events/1/EventOut_NonBoozeItem_101309GMT.json
+ :language: JSON
+ - .. container:: paragraph
+
+ Request to buy a non-alcoholic item (item_ID=5123) at 10:13:09 on Tuesday, 10 January 2017.
+ Sale is authorized.
+ * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json
+ :language: JSON
+ - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json
+ :language: JSON
+ - .. container:: paragraph
+
+ Request to buy alcohol item (`item_ID=1249`) at _08:41:06_ on _Monday, 02 January 2017_.
+ Sale is not authorized.
+ * - .. literalinclude:: events/1/EventIn_BoozeItem_201713GMT.json
+ :language: JSON
+ - .. literalinclude:: events/1/EventOut_BoozeItem_201713GMT.json
+ :language: JSON
+ - .. container:: paragraph
+
+ Request to buy alcohol (`item_ID=1943`) at _20:17:13_ on _Tuesday, 20 December 2016_.
+ Sale is authorized.
+
+
+CLI Editor File
+---------------
+
+ .. container:: sectionbody
+
+ .. container:: sect1
+
+ .. rubric:: Policy 1 in CLI Editor
+ :name: policy_1_in_cli_editor
+
+ .. container:: paragraph
+
+ An equivalent version of the ``MyFirstPolicyModel``
+ policy model can again be generated using the APEX CLI
+ editor. A sample APEX CLI script is shown below:
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ #-------------------------------------------------------------------------------
+ # ============LICENSE_START=======================================================
+ # Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ # ================================================================================
+ # Licensed under the Apache License, Version 2.0 (the "License");
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ #
+ # SPDX-License-Identifier: Apache-2.0
+ # ============LICENSE_END=========================================================
+ #-------------------------------------------------------------------------------
+
+ model create name=MyFirstPolicyModel version=0.0.1 uuid=540226fb-55ee-4f0e-a444-983a0494818e description="This is my first Apex Policy Model."
+
+ schema create name=assistant_ID_type version=0.0.1 uuid=36df4c71-9616-4206-8b53-976a5cd4bd87 description="A type for 'assistant_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=authorised_type version=0.0.1 uuid=d48b619e-d00d-4008-b884-02d76ea4350b description="A type for 'authorised' values" flavour=Java schema=java.lang.Boolean
+
+ schema create name=branch_ID_type version=0.0.1 uuid=6468845f-4122-4128-8e49-0f52c26078b5 description="A type for 'branch_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=item_ID_type version=0.0.1 uuid=4f227ff1-aee0-453a-b6b6-9a4b2e0da932 description="A type for 'item_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=message_type version=0.0.1 uuid=ad1431bb-3155-4e73-b5a3-b89bee498749 description="A type for 'message' values" flavour=Java schema=java.lang.String
+
+ schema create name=notes_type version=0.0.1 uuid=eecfde90-896c-4343-8f9c-2603ced94e2d description="A type for 'notes' values" flavour=Java schema=java.lang.String
+
+ schema create name=price_type version=0.0.1 uuid=52c2fc45-fd8c-463c-bd6f-d91b0554aea7 description="A type for 'amount'/'price' values" flavour=Java schema=java.lang.Long
+
+ schema create name=quantity_type version=0.0.1 uuid=ac3d9842-80af-4a98-951c-bd79a431c613 description="A type for 'quantity' values" flavour=Java schema=java.lang.Integer
+
+ schema create name=sale_ID_type version=0.0.1 uuid=cca47d74-7754-4a61-b163-ca31f66b157b description="A type for 'sale_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
+
+ task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
+ This task checks if the sales request is for an item that contains alcohol.
+ If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
+ In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
+ LE
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
+ task logic create name=MorningBoozeCheck version=0.0.1 logicFlavour=MVEL logic=LS
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+ import java.util.Date;
+ import java.util.Calendar;
+ import java.util.TimeZone;
+ import java.text.SimpleDateFormat;
+
+ logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
+
+ outFields.put("amount" , inFields.get("amount"));
+ outFields.put("assistant_ID", inFields.get("assistant_ID"));
+ outFields.put("notes" , inFields.get("notes"));
+ outFields.put("quantity" , inFields.get("quantity"));
+ outFields.put("branch_ID" , inFields.get("branch_ID"));
+ outFields.put("item_ID" , inFields.get("item_ID"));
+ outFields.put("time" , inFields.get("time"));
+ outFields.put("sale_ID" , inFields.get("sale_ID"));
+
+ item_id = inFields.get("item_ID");
+
+ //The events used later to test this task use GMT timezone!
+ gmt = TimeZone.getTimeZone("GMT");
+ timenow = Calendar.getInstance(gmt);
+ df = new SimpleDateFormat("HH:mm:ss z");
+ df.setTimeZone(gmt);
+ timenow.setTimeInMillis(inFields.get("time"));
+
+ midnight = timenow.clone();
+ midnight.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),0,0,0);
+ eleven30 = timenow.clone();
+ eleven30.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),11,30,0);
+
+ itemisalcohol = false;
+ if(item_id != null && item_id >=1000 && item_id < 2000)
+ itemisalcohol = true;
+
+ if( itemisalcohol
+ && timenow.after(midnight) && timenow.before(eleven30)){
+ outFields.put("authorised", false);
+ outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime())+
+ ". Alcohol can not be sold between "+df.format(midnight.getTime())+
+ " and "+df.format(eleven30.getTime()));
+ return true;
+ }
+ else{
+ outFields.put("authorised", true);
+ outFields.put("message", "Sale authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime()));
+ return true;
+ }
+
+ /*
+ This task checks if a sale request is for an item that is an alcoholic drink.
+ If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
+ authorised. Otherwise the sale is authorised.
+ In this implementation we assume that items with item_ID value between 1000 and
+ 2000 are all alcoholic drinks :-)
+ */
+ LE
+
+ event create name=SALE_AUTH version=0.0.1 uuid=c4500941-3f98-4080-a9cc-5b9753ed050b description="An event emitted by the Policy to indicate whether the sale of an item has been authorised" nameSpace=com.hyperm source="APEX" target="POS"
+ event parameter create name=SALE_AUTH version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=authorised schemaName=authorised_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=message schemaName=message_type schemaVersion=0.0.1 optional=true
+ event parameter create name=SALE_AUTH version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ event parameter create name=SALE_AUTH version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
+
+ event create name=SALE_INPUT version=0.0.1 uuid=4f04aa98-e917-4f4a-882a-c75ba5a99374 description="An event raised by the PoS system each time an item is scanned for purchase" nameSpace=com.hyperm source="POS" target="APEX"
+ event parameter create name=SALE_INPUT version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ event parameter create name=SALE_INPUT version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
+
+
+ policy create name=MyFirstPolicy version=0.0.1 uuid=6c5e410f-489a-46ff-964e-982ce6e8b6d0 description="This is my first Apex policy. It checks if a sale should be authorised or not." template=FREEFORM firstState=BoozeAuthDecide
+ policy state create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide triggerName=SALE_INPUT triggerVersion=0.0.1 defaultTaskName=MorningBoozeCheck defaultTaskVersion=0.0.1
+ policy state output create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide outputName=MorningBoozeCheck_Output_Direct eventName=SALE_AUTH eventVersion=0.0.1 nextState=NULL
+ policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheck taskName=MorningBoozeCheck taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
+
+Policy Step 2
+^^^^^^^^^^^^^
+
+ .. container:: sectionbody
+
+ .. container:: sect1
+
+ .. rubric:: Scenario
+ :name: scenario
+
+ .. container:: paragraph
+
+ *HyperM* have just opened a new branch in a
+ different country, but that country has different
+ rules about when alcohol can be sold! In this
+ section we will go through the necessary steps to
+ extend our policy to enforce this for *HyperM*.
+
+ .. container:: ulist
+
+ - In some branches alcohol cannot be sold before
+ 1pm, and not at all on Sundays.
+
+ .. container:: paragraph
+
+ Although there are a number of ways to accomplish
+ this the easiest approach for us is to define
+ another task and then select which task is
+ appropriate at runtime depending on the branch
+ identifier in the incoming event.
+
+Extend Policy Model
+-------------------
+
+ .. container:: sectionbody
+
+ .. container:: sect2
+
+ .. rubric:: Extend the Policy with the new Scenario
+ :name: extend_the_policy_with_the_new_scenario
+
+ .. container:: paragraph
+
+ To create a new Task click on the 'Tasks' tab. In the
+ 'Tasks' pane, right click and select 'Create new Task':
+
+ .. container:: paragraph
+
+ Create a new Task called ``MorningBoozeCheckAlt1``. Use
+ the 'Generate UUID' button to create a new unique ID for
+ the task, and fill in a description for the task. Select
+ the same input and output fields that we used earlier
+ when we defined the ``MorningBoozeCheck`` task earlier.
+
+ .. table:: Table 1. Input fields for
+ ``MorningBoozeCheckAlt1`` task
+
+ +-----------------------------------+-----------------------------------+
+ | Parameter Name | Parameter Type |
+ +===================================+===================================+
+ | time | timestamp_type |
+ +-----------------------------------+-----------------------------------+
+ | sale_ID | sale_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | amount | price_type |
+ +-----------------------------------+-----------------------------------+
+ | item_ID | item_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | quantity | quantity_type |
+ +-----------------------------------+-----------------------------------+
+ | assistant_ID | assistant_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | branch_ID | branch_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | notes | notes_type |
+ +-----------------------------------+-----------------------------------+
+
+ .. table:: Table 2. Output fields for
+ ``MorningBoozeCheckAlt1`` task
+
+ +-----------------------------------+-----------------------------------+
+ | Parameter Name | Parameter Type |
+ +===================================+===================================+
+ | sale_ID | sale_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | time | timestamp_type |
+ +-----------------------------------+-----------------------------------+
+ | authorised | authorised_type |
+ +-----------------------------------+-----------------------------------+
+ | message | message_type |
+ +-----------------------------------+-----------------------------------+
+ | amount | price_type |
+ +-----------------------------------+-----------------------------------+
+ | item_ID | item_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | assistant_ID | assistant_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | quantity | quantity_type |
+ +-----------------------------------+-----------------------------------+
+ | branch_ID | branch_ID_type |
+ +-----------------------------------+-----------------------------------+
+ | notes | notes_type |
+ +-----------------------------------+-----------------------------------+
+
+ .. container:: paragraph
+
+ This task also requires some 'Task Logic' to implement
+ the new behaviour for this task.
+
+ .. container:: paragraph
+
+ For simplicity use the following code for the task logic.
+ It again assumes that all items with ``item_ID`` between
+ 1000 and 2000 contain alcohol. We again use the standard
+ ``Java`` time utilities to check if the current time is
+ between ``00:00:00 CET`` and ``13:00:00 CET`` or if it is
+ ``Sunday``.
+
+ .. container:: paragraph
+
+ For this task we will again author the logic using the
+ ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__
+ scripting language. Sample task logic code (specified in
+ ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__) is
+ given below. For a detailed guide to how to write your
+ own logic in
+ ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
+ ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
+ of the other supported languages please refer to APEX
+ Programmers Guide.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+ import java.util.Date;
+ import java.util.Calendar;
+ import java.util.TimeZone;
+ import java.text.SimpleDateFormat;
+
+ logger.info("Task Execution: '"+subject.id+"'. Input Event: '"+inFields+"'");
+
+ outFields.put("amount" , inFields.get("amount"));
+ outFields.put("assistant_ID", inFields.get("assistant_ID"));
+ outFields.put("notes" , inFields.get("notes"));
+ outFields.put("quantity" , inFields.get("quantity"));
+ outFields.put("branch_ID" , inFields.get("branch_ID"));
+ outFields.put("item_ID" , inFields.get("item_ID"));
+ outFields.put("time" , inFields.get("time"));
+ outFields.put("sale_ID" , inFields.get("sale_ID"));
+
+ item_id = inFields.get("item_ID");
+
+ //The events used later to test this task use CET timezone!
+ cet = TimeZone.getTimeZone("CET");
+ timenow = Calendar.getInstance(cet);
+ df = new SimpleDateFormat("HH:mm:ss z");
+ df.setTimeZone(cet);
+ timenow.setTimeInMillis(inFields.get("time"));
+
+ midnight = timenow.clone();
+ midnight.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),0,0,0);
+ onepm = timenow.clone();
+ onepm.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),13,0,0);
+
+ itemisalcohol = false;
+ if(item_id != null && item_id >=1000 && item_id < 2000)
+ itemisalcohol = true;
+
+ if( itemisalcohol &&
+ ( (timenow.after(midnight) && timenow.before(onepm))
+ ||
+ (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
+ )){
+ outFields.put("authorised", false);
+ outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime())+
+ ". Alcohol can not be sold between "+df.format(midnight.getTime())+
+ " and "+df.format(onepm.getTime()) +" or on Sunday");
+ return true;
+ }
+ else{
+ outFields.put("authorised", true);
+ outFields.put("message", "Sale authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime()));
+ return true;
+ }
+
+ /*
+ This task checks if a sale request is for an item that is an alcoholic drink.
+ If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
+ Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
+ In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
+ */
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Create a new alternative task
+ \`MorningBoozeCheckAlt1\`|
+
+ .. container:: paragraph
+
+ The task definition is now complete so click the 'Submit'
+ button to save the task. Now that we have created our
+ task, we can can add this task to the single pre-existing
+ state (``BoozeAuthDecide``) in our policy.
+
+ .. container:: paragraph
+
+ To edit the ``BoozeAuthDecide`` state in our policy click
+ on the 'Policies' tab. In the 'Policies' pane, right
+ click on our ``MyFirstPolicy`` policy and select 'Edit'.
+ Navigate to the ``BoozeAuthDecide`` state in the 'states'
+ section at the bottom of the policy definition pane.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |Right click to edit a policy|
+
+ .. container:: paragraph
+
+ To add our new task ``MorningBoozeCheckAlt1``, scroll
+ down to the ``BoozeAuthDecide`` state in the 'States'
+ section. In the 'State Tasks' section for
+ ``BoozeAuthDecide`` use the 'Add new task' button. Select
+ our new ``MorningBoozeCheckAlt1`` task, and use the name
+ of the task as the 'Local Name' for the task. The
+ ``MorningBoozeCheckAlt1`` task can reuse the same
+ ``MorningBoozeCheck_Output_Direct`` 'Direct State Output
+ Mapping' that we used for the ``MorningBoozeCheck`` task.
+ (Recall that the role of the 'State Output Mapping' is to
+ select the output event for the state, and select the
+ next state to be executed. These both remain the same as
+ before.)
+
+ .. container:: paragraph
+
+ Since our state has more than one task we must define
+ some logic to determine which task should be used each
+ time the state is executed. This *task selection logic*
+ is defined in the state definition. For our
+ ``BoozeAuthDecide`` state we want the choice of which
+ task to use to be based on the ``branch_ID`` from which
+ the ``SALE_INPUT`` event originated. For simplicity sake
+ let us assume that branches with ``branch_ID`` between
+ ``0`` and ``999`` should use the ``MorningBoozeCheck``
+ task, and the branches with with ``branch_ID`` between
+ ``1000`` and ``1999`` should use the
+ ``MorningBoozeCheckAlt1`` task.
+
+ .. container:: paragraph
+
+ This time, for variety, we will author the task selection
+ logic using the
+ ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__
+ scripting language. Sample task selection logic code
+ (specified in
+ ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__)
+ is given below. Paste the script text into the 'Task
+ Selection Logic' box, and use "JAVASCRIPT" as the 'Task
+ Selection Logic Type / Flavour'. It is necessary to mark
+ one of the tasks as the 'Default Task' so that the task
+ selection logic always has a fallback default option in
+ cases where a particular task cannot be selected. In this
+ case the ``MorningBoozeCheck`` task can be the default
+ task.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+
+ executor.logger.info("Task Selection Execution: '"+executor.subject.id+
+ "'. Input Event: '"+executor.inFields+"'");
+
+ branchid = executor.inFields.get("branch_ID");
+ taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
+ taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
+ taskdef = executor.subject.getDefaultTaskKey();
+
+ if(branchid >=0 && branchid <1000){
+ taskorig.copyTo(executor.selectedTask);
+ }
+ else if (branchid >=1000 && branchid <2000){
+ taskalt.copyTo(executor.selectedTask);
+ }
+ else{
+ taskdef.copyTo(executor.selectedTask);
+ }
+
+ /*
+ This task selection logic selects task "MorningBoozeCheck" for branches with
+ 0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with
+ 1000<=branch_ID<2000. Otherwise the default task is selected.
+ In this case the default task is also "MorningBoozeCheck"
+ */
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |State definition with 2 Tasks and Task Selection
+ Logic|
+
+ .. container:: paragraph
+
+ When complete don’t forget to click the 'Submit' button
+ at the bottom of 'Policies' pane for our
+ ``MyFirstPolicy`` policy after updating the
+ ``BoozeAuthDecide`` state.
+
+ .. container:: paragraph
+
+ Congratulations, you have now completed the second step
+ towards your first APEX policy. The policy model
+ containing our new policy can again be validated and
+ exported from the editor and saved as shown in Step 1.
+
+ .. container:: paragraph
+
+ The exported policy model is then available in the
+ directory you selected, as
+ `MyFirstPolicyModel_0.0.1.json <files/mfp-files/2/MyFirstPolicyModel_0.0.1.json>`__.
+ The exported policy can now be loaded into the APEX
+ Policy Engine, or can be re-loaded and edited by the APEX
+ Policy Editor.
+
+Test The Policy
+---------------
+
+ .. container:: sectionbody
+
+ .. container:: sect2
+
+ .. rubric:: Test Policy Step 2
+ :name: test_policy_step_2
+
+ .. container:: paragraph
+
+ To start a new APEX Engine you can use the following
+ configuration. In a full APEX installation you can find
+ this configuration in
+ ``$APEX_HOME/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
+ Note, this has changed from the configuration file in
+ Step 1 to enable the ``JAVASCRIPT`` executor for our new
+ 'Task Selection Logic'.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "engineServiceParameters" : {
+ "name" : "MyFirstPolicyApexEngine",
+ "version" : "0.0.1",
+ "id" : 102,
+ "instanceCount" : 4,
+ "deploymentPort" : 12345,
+ "policyModelFileName" : "examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.json",
+ "engineParameters" : {
+ "executorParameters" : {
+ "MVEL" : {
+ "parameterClassName" : "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
+ },
+ "JAVASCRIPT" : {
+ "parameterClassName" : "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
+ }
+ }
+ }
+ },
+ "eventOutputParameters": {
+ "FirstProducer": {
+ "carrierTechnologyParameters" : {
+ "carrierTechnology" : "FILE",
+ "parameters" : {
+ "standardIO" : true
+ }
+ },
+ "eventProtocolParameters" : {
+ "eventProtocol" : "JSON"
+ }
+ }
+ },
+ "eventInputParameters": {
+ "FirstConsumer": {
+ "carrierTechnologyParameters" : {
+ "carrierTechnology" : "FILE",
+ "parameters" : {
+ "standardIO" : true
+ }
+ },
+ "eventProtocolParameters" : {
+ "eventProtocol" : "JSON"
+ }
+ }
+ }
+ }
+
+ .. container:: paragraph
+
+ To test the policy try paste the following events into
+ the console as the APEX engine executes. Note, all tests
+ from Step 1 will still work perfectly since none of those
+ events originate from a branch with ``branch_ID`` between
+ ``1000`` and ``2000``. The 'Task Selection Logic' will
+ therefore pick the ``MorningBoozeCheck`` task as
+ expected, and will therefore give the same results.
+
+ .. list-table:: Table 1. Inputs and Outputs when testing *My First Policy*
+ :widths: 25 40 35
+ :header-rows: 1
+
+ * - Input Event (JSON)
+ - Output Event (JSON)
+ - comment
+ * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json
+ :language: JSON
+ - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json
+ :language: JSON
+ - .. container:: paragraph
+
+ Request to buy alcohol item (`item_ID=1249`) at _08:41:06 GMT_ on _Monday, 02 January 2017_.
+ Sale is not authorized. Uses the `MorningBoozeCheck` task.
+
+ * - .. literalinclude:: events/2/EventIn_BoozeItem_101433CET_thurs.json
+ :language: JSON
+ - .. literalinclude:: events/2/EventOut_BoozeItem_101433CET_thurs.json
+ :language: JSON
+ - .. container:: paragraph
+
+ Request to buy alcohol (`item_ID=1047`) at _10:14:33_ on _Thursday, 22 December 2016_.
+ Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task.
+
+ * - .. literalinclude:: events/2/EventIn_BoozeItem_171937CET_sun.json
+ :language: JSON
+ - .. literalinclude:: events/2/EventOut_BoozeItem_171937CET_sun.json
+ :language: JSON
+ - .. container:: paragraph
+
+ Request to buy alcohol (`item_ID=1443`) at _17:19:37_ on _Sunday, 18 December 2016_.
+ Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task.
+
+ * - .. literalinclude:: events/2/EventIn_NonBoozeItem_111309CET_mon.json
+ :language: JSON
+ - .. literalinclude:: events/2/EventOut_NonBoozeItem_111309CET_mon.json
+ :language: JSON
+ - .. container:: paragraph
+
+ Request to buy non-alcoholic item (`item_ID=5321`) at _11:13:09_ on _Monday, 2 January 2017_.
+ Sale is authorized. Uses the `MorningBoozeCheckAlt1` task.
+
+CLI Editor File
+---------------
+
+ .. container:: sectionbody
+
+ .. container:: sect2
+
+ .. rubric:: Policy 2 in CLI Editor
+ :name: policy_2_in_cli_editor
+
+ .. container:: paragraph
+
+ An equivalent version of the ``MyFirstPolicyModel``
+ policy model can again be generated using the APEX CLI
+ editor. A sample APEX CLI script is shown below:
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ #-------------------------------------------------------------------------------
+ # ============LICENSE_START=======================================================
+ # Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ # ================================================================================
+ # Licensed under the Apache License, Version 2.0 (the "License");
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ #
+ # SPDX-License-Identifier: Apache-2.0
+ # ============LICENSE_END=========================================================
+ #-------------------------------------------------------------------------------
+
+ model create name=MyFirstPolicyModel version=0.0.1 uuid=540226fb-55ee-4f0e-a444-983a0494818e description="This is my first Apex Policy Model."
+
+ schema create name=assistant_ID_type version=0.0.1 uuid=36df4c71-9616-4206-8b53-976a5cd4bd87 description="A type for 'assistant_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=authorised_type version=0.0.1 uuid=d48b619e-d00d-4008-b884-02d76ea4350b description="A type for 'authorised' values" flavour=Java schema=java.lang.Boolean
+
+ schema create name=branch_ID_type version=0.0.1 uuid=6468845f-4122-4128-8e49-0f52c26078b5 description="A type for 'branch_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=item_ID_type version=0.0.1 uuid=4f227ff1-aee0-453a-b6b6-9a4b2e0da932 description="A type for 'item_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=message_type version=0.0.1 uuid=ad1431bb-3155-4e73-b5a3-b89bee498749 description="A type for 'message' values" flavour=Java schema=java.lang.String
+
+ schema create name=notes_type version=0.0.1 uuid=eecfde90-896c-4343-8f9c-2603ced94e2d description="A type for 'notes' values" flavour=Java schema=java.lang.String
+
+ schema create name=price_type version=0.0.1 uuid=52c2fc45-fd8c-463c-bd6f-d91b0554aea7 description="A type for 'amount'/'price' values" flavour=Java schema=java.lang.Long
+
+ schema create name=quantity_type version=0.0.1 uuid=ac3d9842-80af-4a98-951c-bd79a431c613 description="A type for 'quantity' values" flavour=Java schema=java.lang.Integer
+
+ schema create name=sale_ID_type version=0.0.1 uuid=cca47d74-7754-4a61-b163-ca31f66b157b description="A type for 'sale_ID' values" flavour=Java schema=java.lang.Long
+
+ schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
+
+ task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
+ This task checks if the sales request is for an item that contains alcohol.
+ If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
+ In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
+ LE
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
+ task logic create name=MorningBoozeCheck version=0.0.1 logicFlavour=MVEL logic=LS
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+ import java.util.Date;
+ import java.util.Calendar;
+ import java.util.TimeZone;
+ import java.text.SimpleDateFormat;
+
+ logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
+
+ outFields.put("amount" , inFields.get("amount"));
+ outFields.put("assistant_ID", inFields.get("assistant_ID"));
+ outFields.put("notes" , inFields.get("notes"));
+ outFields.put("quantity" , inFields.get("quantity"));
+ outFields.put("branch_ID" , inFields.get("branch_ID"));
+ outFields.put("item_ID" , inFields.get("item_ID"));
+ outFields.put("time" , inFields.get("time"));
+ outFields.put("sale_ID" , inFields.get("sale_ID"));
+
+ item_id = inFields.get("item_ID");
+
+ //The events used later to test this task use GMT timezone!
+ gmt = TimeZone.getTimeZone("GMT");
+ timenow = Calendar.getInstance(gmt);
+ df = new SimpleDateFormat("HH:mm:ss z");
+ df.setTimeZone(gmt);
+ timenow.setTimeInMillis(inFields.get("time"));
+
+ midnight = timenow.clone();
+ midnight.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),0,0,0);
+ eleven30 = timenow.clone();
+ eleven30.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),11,30,0);
+
+ itemisalcohol = false;
+ if(item_id != null && item_id >=1000 && item_id < 2000)
+ itemisalcohol = true;
+
+ if( itemisalcohol
+ && timenow.after(midnight) && timenow.before(eleven30)){
+ outFields.put("authorised", false);
+ outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime())+
+ ". Alcohol can not be sold between "+df.format(midnight.getTime())+
+ " and "+df.format(eleven30.getTime()));
+ return true;
+ }
+ else{
+ outFields.put("authorised", true);
+ outFields.put("message", "Sale authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime()));
+ return true;
+ }
+
+ /*
+ This task checks if a sale request is for an item that is an alcoholic drink.
+ If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
+ authorised. Otherwise the sale is authorised.
+ In this implementation we assume that items with item_ID value between 1000 and
+ 2000 are all alcoholic drinks :-)
+ */
+ LE
+
+ task create name=MorningBoozeCheckAlt1 version=0.0.1 uuid=bc6d90c9-c902-4686-afd3-925b30e39990 description=LS
+ This task checks if a sale request is for an item that is an alcoholic drink.
+ If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
+ Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
+ In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks
+ LE
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
+ task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
+ task logic create name=MorningBoozeCheckAlt1 version=0.0.1 logicFlavour=MVEL logic=LS
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+ import java.util.Date;
+ import java.util.Calendar;
+ import java.util.TimeZone;
+ import java.text.SimpleDateFormat;
+
+ logger.info("Task Execution: '"+subject.id+"'. Input Event: '"+inFields+"'");
+
+ outFields.put("amount" , inFields.get("amount"));
+ outFields.put("assistant_ID", inFields.get("assistant_ID"));
+ outFields.put("notes" , inFields.get("notes"));
+ outFields.put("quantity" , inFields.get("quantity"));
+ outFields.put("branch_ID" , inFields.get("branch_ID"));
+ outFields.put("item_ID" , inFields.get("item_ID"));
+ outFields.put("time" , inFields.get("time"));
+ outFields.put("sale_ID" , inFields.get("sale_ID"));
+
+ item_id = inFields.get("item_ID");
+
+ //The events used later to test this task use CET timezone!
+ cet = TimeZone.getTimeZone("CET");
+ timenow = Calendar.getInstance(cet);
+ df = new SimpleDateFormat("HH:mm:ss z");
+ df.setTimeZone(cet);
+ timenow.setTimeInMillis(inFields.get("time"));
+
+ midnight = timenow.clone();
+ midnight.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),0,0,0);
+ onepm = timenow.clone();
+ onepm.set(
+ timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
+ timenow.get(Calendar.DATE),13,0,0);
+
+ itemisalcohol = false;
+ if(item_id != null && item_id >=1000 && item_id < 2000)
+ itemisalcohol = true;
+
+ if( itemisalcohol &&
+ ( (timenow.after(midnight) && timenow.before(onepm))
+ ||
+ (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
+ )){
+ outFields.put("authorised", false);
+ outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime())+
+ ". Alcohol can not be sold between "+df.format(midnight.getTime())+
+ " and "+df.format(onepm.getTime()) +" or on Sunday");
+ return true;
+ }
+ else{
+ outFields.put("authorised", true);
+ outFields.put("message", "Sale authorised by policy task "+subject.taskName+
+ " for time "+df.format(timenow.getTime()));
+ return true;
+ }
+
+ /*
+ This task checks if a sale request is for an item that is an alcoholic drink.
+ If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
+ Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
+ In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
+ */
+ LE
+
+ event create name=SALE_AUTH version=0.0.1 uuid=c4500941-3f98-4080-a9cc-5b9753ed050b description="An event emitted by the Policy to indicate whether the sale of an item has been authorised" nameSpace=com.hyperm source="APEX" target="POS"
+ event parameter create name=SALE_AUTH version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=authorised schemaName=authorised_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=message schemaName=message_type schemaVersion=0.0.1 optional=true
+ event parameter create name=SALE_AUTH version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ event parameter create name=SALE_AUTH version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_AUTH version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
+
+ event create name=SALE_INPUT version=0.0.1 uuid=4f04aa98-e917-4f4a-882a-c75ba5a99374 description="An event raised by the PoS system each time an item is scanned for purchase" nameSpace=com.hyperm source="POS" target="APEX"
+ event parameter create name=SALE_INPUT version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
+ event parameter create name=SALE_INPUT version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
+ event parameter create name=SALE_INPUT version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
+
+
+ policy create name=MyFirstPolicy version=0.0.1 uuid=6c5e410f-489a-46ff-964e-982ce6e8b6d0 description="This is my first Apex policy. It checks if a sale should be authorised or not." template=FREEFORM firstState=BoozeAuthDecide
+ policy state create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide triggerName=SALE_INPUT triggerVersion=0.0.1 defaultTaskName=MorningBoozeCheck defaultTaskVersion=0.0.1
+ policy state output create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide outputName=MorningBoozeCheck_Output_Direct eventName=SALE_AUTH eventVersion=0.0.1 nextState=NULL
+ policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheckAlt1 taskName=MorningBoozeCheckAlt1 taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
+ policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheck taskName=MorningBoozeCheck taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
+ policy state selecttasklogic create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide logicFlavour=JAVASCRIPT logic=LS
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+
+ executor.logger.info("Task Selection Execution: '"+executor.subject.id+"'. Input Event: '"+executor.inFields+"'");
+
+ branchid = executor.inFields.get("branch_ID");
+ taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
+ taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
+ taskdef = executor.subject.getDefaultTaskKey();
+
+ if(branchid >=0 && branchid <1000){
+ taskorig.copyTo(executor.selectedTask);
+ }
+ else if (branchid >=1000 && branchid <2000){
+ taskalt.copyTo(executor.selectedTask);
+ }
+ else{
+ taskdef.copyTo(executor.selectedTask);
+ }
+
+ /*
+ This task selection logic selects task "MorningBoozeCheck" for branches with 0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with 1000<=branch_ID<2000. Otherwise the default task is selected. In this case the default task is also "MorningBoozeCheck"
+ */
+ LE
+
+
+ .. container::
+ :name: footer-text
+
+ 2.3.0-SNAPSHOT
+ Last updated 2020-04-03 16:04:24 IST
+
+.. |File > New to create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel1.png
+.. |Create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel2.png
+.. |ONAP| image:: ../../../images/logos.png
+ :class: builtBy
+ :target: http://www.onap.org/
+.. |Right click to create a new event| image:: images/mfp/MyFirstPolicy_P1_newEvent1.png
+.. |Fill in the necessary information for the 'SALE_INPUT' event and click 'Submit'| image:: images/mfp/MyFirstPolicy_P1_newEvent2.png
+.. |Right click to create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema1.png
+.. |Create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema2.png
+.. |Add new event parameters to an event| image:: images/mfp/MyFirstPolicy_P1_newEvent3.png
+.. |Right click to create a new task| image:: images/mfp/MyFirstPolicy_P1_newTask1.png
+.. |Add input and out fields for the task| image:: images/mfp/MyFirstPolicy_P1_newTask2.png
+.. |Add task logic the task| image:: images/mfp/MyFirstPolicy_P1_newTask3.png
+.. |Create a new policy| image:: images/mfp/MyFirstPolicy_P1_newPolicy1.png
+.. |Create a state| image:: images/mfp/MyFirstPolicy_P1_newState1.png
+.. |Add a Task and Output Mapping| image:: images/mfp/MyFirstPolicy_P1_newState2.png
+.. |Validate the policy model for error using the 'Model' > 'Validate' menu item| image:: images/mfp/MyFirstPolicy_P1_validatePolicyModel.png
+.. |Download the completed policy model using the 'File' > 'Download' menu item| image:: images/mfp/MyFirstPolicy_P1_exportPolicyModel1.png
+.. |Create a new alternative task \`MorningBoozeCheckAlt1\`| image:: images/mfp/MyFirstPolicy_P2_newTask1.png
+.. |Right click to edit a policy| image:: images/mfp/MyFirstPolicy_P2_editPolicy1.png
+.. |State definition with 2 Tasks and Task Selection Logic| image:: images/mfp/MyFirstPolicy_P2_editState1.png
+
+
diff --git a/docs/apex/APEX-PCVS-Example.rst b/docs/apex/APEX-PCVS-Example.rst
new file mode 100644
index 00000000..fc420303
--- /dev/null
+++ b/docs/apex/APEX-PCVS-Example.rst
@@ -0,0 +1,2954 @@
+.. This work is licensed under a Creative Commons Attribution 4.0 International License.
+.. http://creativecommons.org/licenses/by/4.0
+
+.. _apex-PCVSExample:
+
+Policy-controlled Video Streaming (pcvs) with APEX
+**************************************************
+
+.. contents::
+ :depth: 3
+
+Introduction
+^^^^^^^^^^^^
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ This module contains several demos for
+ Policy-controlled Video Streaming (PCVS). Each demo
+ defines a policy using AVRO and Javascript (or other
+ scripting languages for the policy logic). To run the
+ demo, a vanilla Ubuntu server with some extra software
+ packages is required:
+
+ .. container:: ulist
+
+ - Mininet as network simulator
+
+ - Floodlight as SDN controller
+
+ - Kafka as messaging system
+
+ - Zookeeper for Kafka configuration
+
+ - APEX for policy control
+
+Install Ubuntu Server and SW
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+ .. container:: sect1
+
+ .. rubric:: Install Demo
+ :name: install_demo
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ Requirements:
+
+ .. container:: ulist
+
+ - Ubuntu server: 1.4 GB
+
+ - Ubuntu with Xubuntu Desktop, git, Firefox: 2.3 GB
+
+ - Ubuntu with all, system updated: 3 GB
+
+ - With ZK, Kafka, VLC, Mininet, Floodlight, Python:
+ 4.4 GB
+
+ - APEX Build (M2 and built): M2 ~ 2 GB, APEX ~3.5 GB
+
+ - APEX install (not build locally): ~ 300 MB
+
+ .. container:: paragraph
+
+ On a Ubuntu OS (install a stable or LTS server first)
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ # pre for Ubuntu, tools and X
+ sudo apt-get -y install --no-install-recommends software-properties-common
+ sudo apt-get -y install --no-install-recommends build-essential
+ sudo apt-get -y install --no-install-recommends git
+ sudo aptitude -y install --no-install-recommends xubuntu-desktop
+ sudo apt-get -y install --no-install-recommends firefox
+
+
+ # install Java
+ sudo add-apt-repository ppa:webupd8team/java
+ sudo apt-get update
+ sudo apt-get -y install --no-install-recommends oracle-java8-installer
+ java -version
+
+
+ # reboot system, run system update, then continue
+
+ # if VBox additions are needed, install and reboot
+ sudo (cd /usr/local/share; wget https://www.virtualbox.org/download/testcase/VBoxGuestAdditions_5.2.7-120528.iso)
+ sudo mount /usr/local/share/VBoxGuestAdditions_5.2.7-120528.iso /media/cdrom
+ sudo (cd /media/cdrom;VBoxLinuxAdditions.run)
+
+
+ # update apt-get DB
+ sudo apt-get update
+
+ # if APEX is build from source, install maven and rpm
+ sudo apt-get install maven rpm
+
+ # install ZooKeeper
+ sudo apt-get install zookeeperd
+
+ # install Kafka
+ (cd /tmp;wget http://ftp.heanet.ie/mirrors/www.apache.org/dist/kafka/1.0.0/kafka_2.12-1.0.0.tgz --show-progress)
+ sudo mkdir /opt/Kafka
+ sudo tar -xvf /tmp/kafka_2.12-1.0.0.tgz -C /opt/Kafka/
+
+ # install mininet
+ cd /usr/local/src
+ sudo git clone https://github.com/mininet/mininet.git
+ (cd mininet;util/install.sh -a)
+
+ # install floodlight, requires ant
+ sudo apt-get install ant
+ cd /usr/local/src
+ sudo wget --no-check-certificate https://github.com/floodlight/floodlight/archive/master.zip
+ sudo unzip master.zip
+ cd floodlight-master
+ sudo ant
+ sudo mkdir /var/lib/floodlight
+ sudo chmod 777 /var/lib/floodlight
+
+ # install python pip
+ sudo apt-get install python-pip
+
+ # install kafka-python (need newer version from github)
+ cd /usr/local/src
+ sudo git clone https://github.com/dpkp/kafka-python
+ sudo pip install ./kafka-python
+
+ # install vlc
+ sudo apt-get install vlc
+
+ .. container:: paragraph
+
+ Install APEX either from source or from a distribution
+ package. See the APEX documentation for details. We
+ assume that APEX is installed in
+ ``/opt/ericsson/apex/apex``
+
+ .. container:: paragraph
+
+ Copy the LinkMonitor file to Kafka-Python
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ sudo cp /opt/ericsson/apex/apex/examples/scripts/pcvs/vpnsla/LinkMonitor.py /usr/local/src/kafka-python
+
+ .. container:: paragraph
+
+ Change the Logback configuration in APEX to logic
+ logging
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ (cd /opt/ericsson/apex/apex/etc; sudo cp logback-logic.xml logback.xml)
+
+ .. container:: sect1
+
+ .. rubric:: Get the Demo Video
+ :name: get_the_demo_video
+
+ .. container:: sectionbody
+
+ .. container:: ulist
+
+ - For all download options of the movie please visit
+ http://bbb3d.renderfarming.net/download.html
+
+ - For lower-res downloads and mirrors see
+ https://peach.blender.org/download
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ sudo mkdir /usr/local/src/videos
+
+ .. container:: paragraph
+
+ Standard 720p (recommended)
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ (cd /usr/local/src/videos; sudo curl -o big_buck_bunny_480p_surround.avi http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_surround-fix.avi)
+
+ .. container:: paragraph
+
+ Full HD video
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ (cd videos; sudo curl -o bbb_sunflower_1080p_60fps_normal.mp4 http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_60fps_normal.mp4)
+
+
+
+VPN SLA Demo
+^^^^^^^^^^^^^
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ This demo uses a network with several central office
+ and core switches, over which two VPNs are run. A
+ customer ``A`` has two location ``A1`` and ``A2`` and
+ a VPN between them. A customer ``B`` has two location
+ ``B1`` and ``B2`` and a VPN between them.
+
+ .. container:: imageblock
+
+ .. container:: content
+
+ |VPN SLA Architecture|
+
+ .. container:: paragraph
+
+ The architecture above shows the scenario. The
+ components are realized in this demo as follows:
+
+ .. container:: ulist
+
+ - *CEP / Analytics* - a simple Python script taking
+ events from Kafka and sending them to APEX
+
+ - *APEX / Policy* - the APEX engine running the VPA
+ SLA policy
+
+ - *Controller* - A vanilla Floodlight controller
+ taking events from the Link Monitor and configuring
+ Mininet
+
+ - *Network* - A network created using Mininet
+
+ .. container:: paragraph
+
+ The demo requires to start some software (detailed
+ below). To show actual video streams, we use ``VLC``.
+ If you do not want to show video streams, but only the
+ policy, skip the ``VLC`` section.
+
+ .. container:: paragraph
+
+ All shown scripts are available in a full APEX
+ installation in
+ ``$APEX_HOME/examples/scripts/pcvs/vpnsla``.
+
+ .. container:: sect2
+
+ .. rubric:: Start all Software
+ :name: start_all_software
+
+ .. container:: paragraph
+
+ Create environment variables in a file, say
+ ``env.sh``. In each new Xterm
+
+ .. container:: ulist
+
+ - Source these environment settings, e.g.
+ ``. ./env.sh``
+
+ - Run the commands below as root (``sudo`` per
+ command or ``sudo -i`` for interactive mode as
+ shown below)
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ #!/usr/bin/env bash
+
+ export src_dir=/usr/local/src
+ export APEX_HOME=/opt/ericsson/apex/apex
+ export APEX_USER=apexuser
+
+ .. container:: paragraph
+
+ In a new Xterm, start Floodlight
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ sudo -i
+ . ./env.sh
+ cd $src_dir/floodlight-master && java -jar target/floodlight.jar
+
+ .. container:: paragraph
+
+ In a new Xterm start Mininet
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ sudo -i
+ . ./env.sh
+ mn -c && python $APEX_HOME/examples/scripts/pcvs/vpnsla/MininetTopology.py
+
+ .. container:: paragraph
+
+ In a new Xterm, start Kafka
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ sudo -i
+ . ./env.sh
+ /opt/Kafka/kafka_2.12-1.0.0/bin/kafka-server-start.sh /opt/Kafka/kafka_2.12-1.0.0/config/server.properties
+
+ .. container:: paragraph
+
+ In a new Xerm start APEX with the Kafka
+ configuration for this demo
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ cd $APEX_HOME
+ ./bin/apexApps.sh engine -c examples/config/pcvs/vpnsla/kafka2kafka.json
+
+ .. container:: paragraph
+
+ In a new Xterm start the Link Monitor. The Link
+ Monitor has a 30 second sleep to slow down the
+ demonstration. So the first action of it comes 30
+ seconds after start. Every new action in 30 second
+ intervals.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ ::
+
+ sudo -i
+ . ./env.sh
+ cd $src_dir
+ xterm -hold -e 'python3 $src_dir/kafka-python/LinkMonitor.py' &
+
+ .. container:: paragraph
+
+ Now all software should be started and the demo is
+ running. The Link Monitor will send link up events,
+ picked up by APEX which triggers the policy. Since
+ there is no problem, the policy will do nothing.
+
+ .. container:: sect2
+
+ .. rubric:: Create 2 Video Streams with VLC
+ :name: create_2_video_streams_with_vlc
+
+ .. container:: paragraph
+
+ In the Mininet console, type ``xterm A1 A2`` and
+ ``xterm B1 B2`` to open terminals on these nodes.
+
+ .. container:: paragraph
+
+ ``A2`` and ``B2`` are the receiving nodes. In these
+ terminals, run ``vlc-wrapper``. In each opened VLC
+ window do
+
+ .. container:: ulist
+
+ - Click Media → Open Network Stream
+
+ - Give the URL as ``rtp://@:5004``
+
+ .. container:: paragraph
+
+ ``A1`` and ``B1`` are the sending nodes (sending
+ the video stream) In these terminals, run
+ ``vlc-wrapper``. In each opened VLC window do
+
+ .. container:: ulist
+
+ - Click Media → Stream
+
+ - Add the video (from ``/usr/local/src/videos``)
+
+ - Click ``Stream``
+
+ - Click ``Next``
+
+ - Change the destination
+ ``RTP / MPEG Transport Stream`` and click
+ ``Add``
+
+ - Change the address and type to ``10.0.0.2`` in
+ ``A1`` and to ``10.0.0.4`` in ``B1``
+
+ - Turn off ``Active Transcoding`` (this is
+ important to minimize CPU load)
+
+ - Click ``Next``
+
+ - Click ``Stream``
+
+ .. container:: paragraph
+
+ The video should be streaming across the network
+ from ``A1`` to ``A2`` and from ``B1`` to ``B2``. If
+ the video streams a slow or interrupted the CPU
+ load is too high. In these cases either try a
+ better machine or use a different (lower quality)
+ video stream.
+
+ .. container:: sect2
+
+ .. rubric:: Take out L09 and let the Policy do it’s
+ Magic
+ :name: take_out_l09_and_let_the_policy_do_it_s_magic
+
+ .. container:: paragraph
+
+ Now it is time to take out the link ``L09``. This
+ will be picked up by the Link Monitor, which sends
+ a new event (L09 DOWN) to the policy. The policy
+ then will calculate which customer should be
+ impeded (throttled). This will continue, until SLAs
+ are violated, then a priority calculation will kick
+ in (Customer ``A`` is prioritized in the setup).
+
+ .. container:: paragraph
+
+ To initiate this, simply type ``link s5 s6 down``
+ in the Mininet console followed by ``exit``.
+
+ .. container:: paragraph
+
+ If you have the video streams running, you will see
+ one or the other struggeling, depending on the
+ policy decision.
+
+ .. container:: sect2
+
+ .. rubric:: Reset the Demo
+ :name: reset_the_demo
+
+ .. container:: paragraph
+
+ If you want to reset the demo, simple stop (in this
+ order) the following process
+
+ .. container:: ulist
+
+ - Link Monitor
+
+ - APEX
+
+ - Mininet
+
+ - Floodlight
+
+ .. container:: paragraph
+
+ Then restart them in this order
+
+ .. container:: ulist
+
+ - Floodlight
+
+ - Mininet
+
+ - APEX
+
+ - Link Monitor
+
+ .. container:: sect2
+
+ .. rubric:: Monitor the Demo
+ :name: monitor_the_demo
+
+ .. container:: paragraph
+
+ Floodlight and APEX provide REST interfaces for
+ monitoring.
+
+ .. container:: ulist
+
+ - Floodlight: see `Floodlight
+ Docs <https://floodlight.atlassian.net/wiki/spaces/floodlightcontroller/pages/40403023/Web+GUI>`__
+ for details on how to access the monitoring. In
+ a standard installation as we use here, pointing
+ browser to the URL
+ ``http://localhost:8080/ui/pages/index.html``
+ should work on the same host
+
+ - APEX please see the APEX documentation for
+ `Monitoring
+ Client <https://ericsson.github.io/apex-docs/user-manual/engine-apps/um-engapps-eng-monitoring.html>`__
+ or `Full
+ Client <https://ericsson.github.io/apex-docs/user-manual/engine-apps/um-engapps-full-client.html>`__
+ for details on how to monitor APEX.
+
+
+VPN SLA Policy
+^^^^^^^^^^^^^^
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The VPN SLA policy is designed as a MEDA policy. The
+ first state (M = Match) takes the trigger event (a
+ link up or down) and checks if this is a change to the
+ known topology. The second state (E = Establish) takes
+ all available information (trigger event, local
+ context) and defines what situation we have. The third
+ state (D = Decide) takes the situation and selects
+ which algorithm is best to process it. This state can
+ select between ``none`` (nothing to do), ``solved`` (a
+ problem is solved now), ``sla`` (compare the current
+ customer SLA situation and select one to impede), and
+ ``priority`` (impede non-priority customers). The
+ fourth and final state (A = Act) selects the right
+ action for the taken decision and creates the response
+ event sent to the orchestrator.
+
+ .. container:: paragraph
+
+ We have added three more policies to set the local
+ context: one for adding nodes, one for adding edges
+ (links), and one for adding customers. These policies
+ do not realize any action, they are only here for
+ updating the local context. This mechanism is the
+ fasted way to update local context, and it is
+ independent of any context plugin.
+
+ .. container:: paragraph
+
+ The policy uses data defined in Avro, so we have a
+ number of Avro schema definitions.
+
+Context Schemas
+---------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The context schemas are for the local context. We
+ model edges and nodes for the topology, customers, and
+ problems with all information on detected problems.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "type" : "record",
+ "name" : "TopologyEdges",
+ "fields" : [
+ {"name": "name", "type": "string", "doc": "Name of the Edge, typically a link name"},
+ {"name": "start", "type": "string", "doc": "Edge endpoint: start - a node name"},
+ {"name": "end", "type": "string", "doc": "Edge endpoint: end - a node name"},
+ {"name": "active", "type": "boolean", "doc": "Flag for active/inactive edges, inactive means a link is down"}
+ ]
+ }
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "type" : "record",
+ "name" : "TopologyNodes",
+ "fields" : [
+ {"name" : "name", "type" : "string", "doc": "The name of the node"},
+ {"name" : "mnname", "type" : "string", "doc": "The name of the node in Mininet"}
+ ]
+ }
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "type" : "record",
+ "name" : "Customer",
+ "fields" : [
+ {"name" : "customerName", "type" : "string"},
+ {"name" : "dtSLA" , "type" : "int"},
+ {"name" : "dtYTD" , "type" : "int"},
+ {"name" : "priority" , "type" : "boolean"},
+ {"name" : "satisfaction", "type" : "int"},
+ {
+ "name": "links",
+ "doc": "Links used by this customer",
+ "type": {"type" : "array", "items" : "string"}
+ }
+ ]
+ }
+
+
+Trigger Schemas
+---------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The trigger event provides a status as ``UP`` or
+ ``DOWN``. To avoid tests for these strings in the
+ logic, we defined an Avro schema for an enumeration.
+ This does not impact the trigger system (it can still
+ send the strings), but makes the task logic simpler.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "type": "enum",
+ "name": "Status",
+ "symbols" : [
+ "UP",
+ "DOWN"
+ ]
+ }
+
+Context Logic Nodes
+--------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The node context logic simply takes the trigger event
+ (for context) and creates a new node in the local
+ context topology.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var ifNodeName = executor.inFields["nodeName"];
+ var ifMininetName = executor.inFields["mininetName"];
+
+ var albumTopoNodes = executor.getContextAlbum("albumTopoNodes");
+
+ logger.trace("-- got infields, testing existing node");
+
+ var ctxtNode = albumTopoNodes.get(ifNodeName);
+ if (ctxtNode != null) {
+ albumTopoNodes.remove(ifNodeName);
+ logger.trace("-- removed node: <" + ifNodeName + ">");
+ }
+
+ logger.trace("-- creating node: <" + ifNodeName + ">");
+ ctxtNode = "{name:" + ifNodeName + ", mnname:" + ifMininetName + "}";
+ albumTopoNodes.put(ifNodeName, ctxtNode);
+
+ if (logger.isTraceEnabled()) {
+ logger.trace(" >> *** Nodes ***");
+ if (albumTopoNodes != null) {
+ for (var i = 0; i < albumTopoNodes.values().size(); i++) {
+ logger.trace(" >> >> " + albumTopoNodes.values().get(i).get("name") + " : "
+ + albumTopoNodes.values().get(i).get("mnname"));
+ }
+ } else {
+ logger.trace(" >> >> node album is null");
+ }
+ }
+
+ executor.outFields["report"] = "node ctxt :: added node " + ifNodeName;
+
+ logger.info("vpnsla: ctxt added node " + ifNodeName);
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".");
+
+Context Logic Edges
+--------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The edge context logic simply takes the trigger event
+ (for context) and creates a new edge in the local
+ context topology.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var ifEdgeName = executor.inFields["edgeName"];
+ var ifEdgeStatus = executor.inFields["status"];
+
+ var albumTopoEdges = executor.getContextAlbum("albumTopoEdges");
+
+ logger.trace("-- got infields, testing existing edge");
+
+ var ctxtEdge = albumTopoEdges.get(ifEdgeName);
+ if (ctxtEdge != null) {
+ albumTopoEdges.remove(ifEdgeName);
+ logger.trace("-- removed edge: <" + ifEdgeName + ">");
+ }
+
+ logger.trace("-- creating edge: <" + ifEdgeName + ">");
+ ctxtEdge = "{name:" + ifEdgeName + ", start:" + executor.inFields["start"] + ", end:" + executor.inFields["end"]
+ + ", active:" + ifEdgeStatus + "}";
+ albumTopoEdges.put(ifEdgeName, ctxtEdge);
+
+ if (logger.isTraceEnabled()) {
+ logger.trace(" >> *** Edges ***");
+ if (albumTopoEdges != null) {
+ for (var i = 0; i < albumTopoEdges.values().size(); i++) {
+ logger.trace(" >> >> " + albumTopoEdges.values().get(i).get("name") + " \t "
+ + albumTopoEdges.values().get(i).get("start") + " --> " + albumTopoEdges.values().get(i).get("end")
+ + " \t " + albumTopoEdges.values().get(i).get("active"));
+ }
+ } else {
+ logger.trace(" >> >> edge album is null");
+ }
+ }
+
+ executor.outFields["report"] = "edge ctxt :: added edge " + ifEdgeName;
+
+ logger.info("vpnsla: ctxt added edge " + ifEdgeName);
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".");
+
+Context Logic Customer
+----------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The customer context logic simply takes the trigger
+ event (for context) and creates a new customer in the
+ local context topology.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var ifCustomerName = executor.inFields["customerName"];
+ var ifLinks = executor.inFields["links"];
+
+ logger.trace("-- got infields, testing existing customer");
+ var ctxtCustomer = executor.getContextAlbum("albumCustomerMap").get(ifCustomerName);
+ if (ctxtCustomer != null) {
+ executor.getContextAlbum("albumCustomerMap").remove(ifCustomerName);
+ logger.trace("-- removed customer: <" + ifCustomerName + ">");
+ }
+
+ logger.trace("-- creating customer: <" + ifCustomerName + ">");
+ var links = new Array();
+ for (var i = 0; i < ifLinks.split(" ").length; i++) {
+ var link = executor.getContextAlbum("albumTopoEdges").get(ifLinks.split(" ")[i]);
+ if (link != null) {
+ logger.trace("-- link: <" + ifLinks.split(" ")[i] + ">");
+ links.push(ifLinks.split(" ")[i]);
+ } else {
+ logger.trace("-- unknown link: <" + ifLinks.split(" ")[i] + "> for customer <" + ifCustomerName + ">");
+ }
+ }
+ logger.trace("-- links: <" + links + ">");
+ ctxtCustomer = "{customerName:" + ifCustomerName + ", dtSLA:" + executor.inFields["dtSLA"] + ", dtYTD:"
+ + executor.inFields["dtYTD"] + ", priority:" + executor.inFields["priority"] + ", satisfaction:"
+ + executor.inFields["satisfaction"] + ", links:[" + links + "]}";
+
+ executor.getContextAlbum("albumCustomerMap").put(ifCustomerName, ctxtCustomer);
+
+ if (logger.isTraceEnabled()) {
+ logger.trace(" >> *** Customers ***");
+ if (executor.getContextAlbum("albumCustomerMap") != null) {
+ for (var i = 0; i < executor.getContextAlbum("albumCustomerMap").values().size(); i++) {
+ logger.trace(" >> >> " + executor.getContextAlbum("albumCustomerMap").values().get(i).get("customerName")
+ + " : " + "dtSLA=" + executor.getContextAlbum("albumCustomerMap").values().get(i).get("dtSLA")
+ + " : " + "dtYTD=" + executor.getContextAlbum("albumCustomerMap").values().get(i).get("dtYTD")
+ + " : " + "links=" + executor.getContextAlbum("albumCustomerMap").values().get(i).get("links")
+ + " : " + "priority="
+ + executor.getContextAlbum("albumCustomerMap").values().get(i).get("priority") + " : "
+ + "satisfaction="
+ + executor.getContextAlbum("albumCustomerMap").values().get(i).get("satisfaction"));
+ }
+ } else {
+ logger.trace(" >> >> customer album is null");
+ }
+ }
+
+ executor.outFields["report"] = "customer ctxt :: added customer: " + ifCustomerName;
+
+ logger.info("vpnsla: ctxt added customer " + ifCustomerName);
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".");
+
+Logic: Match
+------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ This is the logic for the match state. It is kept very
+ simple. Beside taking the trigger event, it also
+ creates a timestamp. This timestamp is later used for
+ SLA and downtime calculations as well as for some
+ performance information of the policy.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+
+ var now = new Date().getTime();
+ executor.outFields["matchStart"] = now;
+
+ importClass(org.slf4j.LoggerFactory);
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
+
+ var ifEdgeName = executor.inFields["edgeName"];
+ var ifLinkStatus = executor.inFields["status"];
+
+ var albumTopoEdges = executor.getContextAlbum("albumTopoEdges");
+
+ logger.trace("-- got infields, checking albumTopoEdges changes");
+
+ var active = false;
+ switch (ifLinkStatus.toString()) {
+ case "UP":
+ active = true;
+ break;
+ case "DOWN":
+ active = false;
+ break;
+ default:
+ active = false;
+ logger.error("-- trigger sent unknown link status <" + ifLinkStatus + "> for link <" + ifEdgeName + ">");
+ rootLogger.error(executor.subject.id + " " + "-- trigger sent unknown link status <" + ifLinkStatus
+ + "> for link <" + ifEdgeName + ">");
+ }
+
+ var link = albumTopoEdges.get(ifEdgeName);
+ if (link == null) {
+ logger.trace("-- link <" + ifEdgeName + "> not in albumTopoEdges");
+ } else {
+ logger.trace("-- found link <" + link + "> in albumTopoEdges");
+ logger.trace("-- active <" + active + "> : link.active <" + link.get("active") + ">");
+ if (active != link.get("active")) {
+ link.put("active", active);
+ logger.trace("-- link <" + ifEdgeName + "> status changed to <active:" + link.get("active") + ">");
+ executor.outFields["hasChanged"] = true;
+ } else {
+ logger.trace("-- link <" + ifEdgeName + "> status not changed <active:" + link.get("active") + ">");
+ executor.outFields["hasChanged"] = false;
+ }
+ }
+
+ executor.outFields["edgeName"] = ifEdgeName;
+ executor.outFields["status"] = ifLinkStatus;
+
+ logger.info("vpnsla: detected " + ifEdgeName + " as " + ifLinkStatus);
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".m");
+
+
+Logic: Policy Establish State
+-----------------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ This is the logic for the establish state. It is the
+ most complicated logic, since establishing a situation
+ for a decision is the most important part of any
+ policy. First, the policy describes what we find (the
+ switch block), in terms of 8 normal situations and 1
+ extreme error case.
+
+ .. container:: paragraph
+
+ If required, it creates local context information for
+ the problem (if it is new) or updates it (if the
+ problem still exists). It also calculates customer SLA
+ downtime and checks for any SLA violations. Finally,
+ it creates a situation object.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+ importClass(org.slf4j.LoggerFactory);
+
+ importClass(java.util.ArrayList);
+
+ importClass(org.apache.avro.generic.GenericData.Array);
+ importClass(org.apache.avro.generic.GenericRecord);
+ importClass(org.apache.avro.Schema);
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
+
+ var ifEdgeName = executor.inFields["edgeName"];
+ var ifEdgeStatus = executor.inFields["status"].toString();
+ var ifhasChanged = executor.inFields["hasChanged"];
+ var ifMatchStart = executor.inFields["matchStart"];
+
+ var albumCustomerMap = executor.getContextAlbum("albumCustomerMap");
+ var albumProblemMap = executor.getContextAlbum("albumProblemMap");
+
+ var linkProblem = albumProblemMap.get(ifEdgeName);
+
+ // create outfiled for situation
+ var situation = executor.subject.getOutFieldSchemaHelper("situation").createNewInstance();
+ situation.put("violatedSLAs", new ArrayList());
+
+ // create a string as states+hasChanged+linkProblem and switch over it
+ var switchTest = ifEdgeStatus + ":" + ifhasChanged + ":" + (linkProblem == null ? "no" : "yes");
+ switch (switchTest) {
+ case "UP:false:no":
+ logger.trace("-- edge <" + ifEdgeName + "> UP:false:no => everything ok");
+ logger.info("vpnsla: everything ok");
+ situation.put("problemID", "NONE");
+ break;
+ case "UP:false:yes":
+ logger.trace("-- edge <" + ifEdgeName + "> UP:false:yes ==> did we miss earlier up?, removing problem");
+ albumProblemMap.remove(ifEdgeName);
+ linkProblem = null;
+ situation.put("problemID", "NONE");
+ break;
+ case "UP:true:no":
+ logger.trace("-- edge <" + ifEdgeName + "> UP:true:no ==> did we miss the earlier down?, creating new problem");
+ situation.put("problemID", ifEdgeName);
+ break;
+ case "UP:true:yes":
+ logger.trace("-- edge <" + ifEdgeName + "> UP:true:yes ==> detected solution, link up again");
+ logger.info("vpnsla: problem solved");
+ linkProblem.put("endTime", ifMatchStart);
+ linkProblem.put("status", "SOLVED");
+ situation.put("problemID", "NONE");
+ break;
+ case "DOWN:false:no":
+ logger.trace("-- edge <" + ifEdgeName + "> DOWN:false:no ==> did we miss an earlier down?, creating new problem");
+ situation.put("problemID", ifEdgeName);
+ break;
+ case "DOWN:false:yes":
+ logger.trace("-- edge <" + ifEdgeName + "> DOWN:false:yes ==> problem STILL exists");
+ logger.info("vpnsla: problem still exists");
+ linkProblem.put("status", "STILL");
+ situation.put("problemID", ifEdgeName);
+ break;
+ case "DOWN:true:no":
+ logger.trace("-- edge <" + ifEdgeName + "> DOWN:true:no ==> found NEW problem");
+ logger.info("vpnsla: this is a new problem");
+ situation.put("problemID", ifEdgeName);
+ break;
+ case "DOWN:true:yes":
+ logger.trace("-- edge <" + ifEdgeName
+ + "> DOWN:true:yes ==> did we miss to remove an earlier problem?, remove and create new problem");
+ linkProblem = null;
+ situation.put("problemID", ifEdgeName);
+ break;
+
+ default:
+ logger.error("-- input wrong for edge" + ifEdgeName + ": edge status <" + ifEdgeStatus
+ + "> unknown or null on hasChanged <" + ifhasChanged + ">");
+ rootLogger.error("-- input wrong for edge" + ifEdgeName + ": edge status <" + ifEdgeStatus
+ + "> unknown or null on hasChanged <" + ifhasChanged + ">");
+ }
+
+ // create new problem if situation requires it
+ if (situation.get("problemID").equals(ifEdgeName) && linkProblem == null) {
+ logger.trace("-- edge <" + ifEdgeName + "> creating new problem");
+ linkProblem = albumProblemMap.getSchemaHelper().createNewInstance();
+ linkProblem.put("edge", ifEdgeName);
+ linkProblem.put("startTime", ifMatchStart);
+ linkProblem.put("lastUpdate", ifMatchStart);
+ linkProblem.put("endTime", 0);
+ linkProblem.put("status", "NEW");
+ linkProblem.put("edgeUsedBy", new ArrayList());
+ linkProblem.put("impededLast", new ArrayList());
+
+ for (var i = 0; i < albumCustomerMap.values().size(); i++) {
+ var customer = albumCustomerMap.values().get(i);
+ var customerLinks = albumCustomerMap.values().get(i).get("links");
+ for (var k = 0; k < customerLinks.size(); k++) {
+ if (customerLinks.get(k) == ifEdgeName) {
+ linkProblem.get("edgeUsedBy").add(customer.get("customerName"));
+ }
+ }
+ }
+ albumProblemMap.put(ifEdgeName, linkProblem);
+ logger.trace("-- edge <" + ifEdgeName + "> problem created as <" + linkProblem + ">");
+ }
+
+ // set dtYTD if situation requires it
+ if (linkProblem != null && (linkProblem.get("status") == "STILL" || linkProblem.get("status") == "SOLVED")) {
+ var linkDownTimeinSecs = (ifMatchStart - linkProblem.get("lastUpdate")) / 1000;
+ logger.trace("-- edge <" + ifEdgeName + "> down time: " + linkDownTimeinSecs + " s");
+ for (var k = 0; k < linkProblem.get("impededLast").size(); k++) {
+ for (var i = 0; i < albumCustomerMap.values().size(); i++) {
+ var customer = albumCustomerMap.values().get(i);
+ if (customer.get("customerName").equals(linkProblem.get("impededLast").get(k))) {
+ logger.info("-- vpnsla: customer " + customer.get("customerName") + " YDT downtime increased from "
+ + customer.get("dtYTD") + " to " + (customer.get("dtYTD") + linkDownTimeinSecs));
+ customer.put("dtYTD", (customer.get("dtYTD") + linkDownTimeinSecs))
+ }
+ }
+ }
+ // set lastUpdate to this policy execution for next execution calculation
+ linkProblem.put("lastUpdate", ifMatchStart);
+ }
+
+ // check SLA violations if situation requires it
+ if (linkProblem != null && linkProblem.get("status") != "SOLVED") {
+ logger.info(">e> customer\tDT SLA\tDT YTD\tviolation");
+ for (var i = 0; i < albumCustomerMap.values().size(); i++) {
+ var customer = albumCustomerMap.values().get(i);
+ if (customer.get("dtYTD") > customer.get("dtSLA")) {
+ situation.get("violatedSLAs").add(customer.get("customerName"));
+ logger.info(">e> " + customer.get("customerName") + "\t\t" + customer.get("dtSLA") + "s\t"
+ + customer.get("dtYTD") + "s\t" + "!!");
+ } else {
+ logger.info(">e> " + customer.get("customerName") + "\t\t" + customer.get("dtSLA") + "s\t"
+ + customer.get("dtYTD") + "s");
+ }
+ }
+ }
+
+ executor.outFields["situation"] = situation;
+
+ logger.trace("-- out fields <" + executor.outFields + ">");
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".e");
+
+Logic: Policy Decide State
+--------------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The decide state can select between different
+ algorithms depending on the situation. So it needs a
+ Task Selection Logic (TSL). This TSL select a task in
+ the current policy execution (i.e. potentially a
+ different one per execution).
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+ importClass(org.slf4j.LoggerFactory);
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id + " - TSL");
+
+ var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
+
+ var ifSituation = executor.inFields["situation"];
+
+ var albumProblemMap = executor.getContextAlbum("albumProblemMap");
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ if (ifSituation.get("problemID") == "NONE") {
+ logger.trace("-- situation has no problem, selecting <VpnSlaPolicyDecideNoneTask>");
+ executor.subject.getTaskKey("VpnSlaPolicyDecideNoneTask").copyTo(executor.selectedTask);
+ var returnValue = new returnValueType(true);
+ } else if (albumProblemMap.get(ifSituation.get("problemID")).get("status") == "SOLVED") {
+ logger.trace("-- situation is solved, selecting <VpnSlaPolicyDecideSolvedTask>");
+ executor.subject.getTaskKey("VpnSlaPolicyDecideSolvedTask").copyTo(executor.selectedTask);
+ var returnValue = new returnValueType(true);
+ } else if (ifSituation.get("violatedSLAs") != null && ifSituation.get("violatedSLAs").size() > 0) {
+ logger.trace("-- situation is problem with violations, selecting <VpnSlaPolicyDecidePriorityTask>");
+ executor.subject.getTaskKey("VpnSlaPolicyDecidePriorityTask").copyTo(executor.selectedTask);
+ var returnValue = new returnValueType(true);
+ } else if (ifSituation.get("violatedSLAs") != null && ifSituation.get("violatedSLAs").size() == 0) {
+ logger.trace("-- situation is problem without violations, selecting <VpnSlaPolicyDecideSlaTask>");
+ executor.subject.getTaskKey("VpnSlaPolicyDecideSlaTask").copyTo(executor.selectedTask);
+ var returnValue = new returnValueType(true);
+ } else {
+ logger.error("-- detected unknown decision for situation <" + ifSituation.get("problemID") + ">");
+ rootLogger.error(executor.subject.id + " " + "-- detected unknown decision for situation <"
+ + ifSituation.get("problemID") + ">");
+ var returnValue = new returnValueType(false);
+ }
+
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".d-tsl");
+
+ .. container:: paragraph
+
+ The actual task logic are then ``none``, ``solved``,
+ ``sla``, and ``priority``.
+
+Logic: Decide None
+-------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+ importClass(org.slf4j.LoggerFactory);
+
+ importClass(java.util.ArrayList);
+
+ importClass(org.apache.avro.generic.GenericData.Array);
+ importClass(org.apache.avro.generic.GenericRecord);
+ importClass(org.apache.avro.Schema);
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
+
+ var ifSituation = executor.inFields["situation"];
+
+ // create outfiled for decision
+ var decision = executor.subject.getOutFieldSchemaHelper("decision").createNewInstance();
+ decision.put("description", "None, everything is ok");
+ decision.put("decision", "NONE");
+ decision.put("customers", new ArrayList());
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ if (ifSituation.get("problemID") == "NONE") {
+ logger.trace("-- no problem, everything ok");
+ var returnValue = new returnValueType(true);
+ } else {
+ logger.trace("-- wrong problemID <" + problemID + "> for NONE task, we should not be here");
+ rootLogger.error(executor.subject.id + " " + "-- wrong problemID <" + problemID
+ + "> for NONE task, we should not be here");
+ var returnValue = new returnValueType(false);
+ }
+
+ executor.outFields["decision"] = decision;
+
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".d-non");
+
+Logic: Decide Solved
+---------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+ importClass(org.slf4j.LoggerFactory);
+
+ importClass(java.util.ArrayList);
+
+ importClass(org.apache.avro.generic.GenericData.Array);
+ importClass(org.apache.avro.generic.GenericRecord);
+ importClass(org.apache.avro.Schema);
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
+
+ var ifSituation = executor.inFields["situation"];
+
+ var albumProblemMap = executor.getContextAlbum("albumProblemMap");
+
+ // create outfiled for decision
+ var decision = executor.subject.getOutFieldSchemaHelper("decision").createNewInstance();
+ decision.put("description", "None, everything is ok");
+ decision.put("decision", "REBUILD");
+ decision.put("customers", new ArrayList());
+ decision.put("problemID", ifSituation.get("problemID"));
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ if (albumProblemMap.get(ifSituation.get("problemID")).get("status") == "SOLVED") {
+ logger.trace("-- problem solved");
+ var returnValue = new returnValueType(true);
+ } else {
+ logger.trace("-- wrong problemID <" + problemID + "> for SOLVED task, we should not be here");
+ rootLogger.error(executor.subject.id + " " + "-- wrong problemID <" + problemID
+ + "> for SOLVED task, we should not be here");
+ var returnValue = new returnValueType(false);
+ }
+
+ executor.outFields["decision"] = decision;
+
+ logger.info("vpnsla: sla solved, problem solved");
+
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".d-non");
+
+Logic: Decide SLA
+------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+ importClass(org.slf4j.LoggerFactory);
+
+ importClass(java.util.ArrayList);
+
+ importClass(org.apache.avro.generic.GenericData.Array);
+ importClass(org.apache.avro.generic.GenericRecord);
+ importClass(org.apache.avro.Schema);
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
+
+ var ifSituation = executor.inFields["situation"];
+
+ var albumCustomerMap = executor.getContextAlbum("albumCustomerMap");
+ var albumProblemMap = executor.getContextAlbum("albumProblemMap");
+
+ // create outfiled for decision
+ var decision = executor.subject.getOutFieldSchemaHelper("decision").createNewInstance();
+ decision.put("description", "Impede given customers selected based on maximum SLA delta");
+ decision.put("decision", "IMPEDE");
+ decision.put("problemID", ifSituation.get("problemID"));
+ decision.put("customers", new ArrayList());
+
+ var problem = albumProblemMap.get(ifSituation.get("problemID"));
+ var returnValueType = Java.type("java.lang.Boolean");
+ if (problem != null && ifSituation.get("violatedSLAs").size() == 0) {
+ logger.trace("-- impede by maximum SLA");
+ var customer = "";
+ var customerSla = 0;
+ for (var i = 0; i < problem.get("edgeUsedBy").size(); i++) {
+ customerCtxt = albumCustomerMap.get(problem.get("edgeUsedBy").get(i).toString());
+ if (customerSla == 0) {
+ customerSla = customerCtxt.get("dtSLA") - customerCtxt.get("dtYTD");
+ }
+ if ((customerCtxt.get("dtSLA") - customerCtxt.get("dtYTD")) >= customerSla) {
+ customer = customerCtxt.get("customerName");
+ customerSla = (customerCtxt.get("dtSLA") - customerCtxt.get("dtYTD"));
+ }
+ }
+ decision.get("customers").add(customer);
+ var returnValue = new returnValueType(true);
+ } else {
+ logger.trace("-- wrong problemID <" + ifSituation.get("problemID") + "> for SLA task, we should not be here");
+ rootLogger.error(executor.subject.id + " " + "-- wrong problemID <" + ifSituation.get("problemID")
+ + "> for SLA task, we should not be here");
+ var returnValue = new returnValueType(false);
+ }
+
+ // set impededLast to decision[customers]
+ problem.get("impededLast").clear();
+ problem.get("impededLast").addAll(decision.get("customers"));
+
+ executor.outFields["decision"] = decision;
+ logger.trace("-- decision: " + decision);
+
+ logger.info("vpnsla: sla balance, impeding customers " + decision.get("customers"));
+
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".d-sla");
+
+Logic: Decide Priority
+----------------------
+
+ .. container:: sect2
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+ importClass(org.slf4j.LoggerFactory);
+
+ importClass(java.util.ArrayList);
+
+ importClass(org.apache.avro.generic.GenericData.Array);
+ importClass(org.apache.avro.generic.GenericRecord);
+ importClass(org.apache.avro.Schema);
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
+
+ var ifSituation = executor.inFields["situation"];
+
+ var albumCustomerMap = executor.getContextAlbum("albumCustomerMap");
+ var albumProblemMap = executor.getContextAlbum("albumProblemMap");
+
+ // create outfiled for decision
+ var decision = executor.subject.getOutFieldSchemaHelper("decision").createNewInstance();
+ decision.put("description", "None, everything is ok");
+ decision.put("decision", "IMPEDE");
+ decision.put("problemID", ifSituation.get("problemID"));
+ decision.put("customers", new ArrayList());
+
+ var problem = albumProblemMap.get(ifSituation.get("problemID"));
+ var returnValueType = Java.type("java.lang.Boolean");
+ if (problem != null && ifSituation.get("violatedSLAs").size() > 0) {
+ logger.trace("-- impede by priority");
+ for (var i = 0; i < problem.get("edgeUsedBy").size(); i++) {
+ customerCtxt = albumCustomerMap.get(problem.get("edgeUsedBy").get(i).toString());
+ if (customerCtxt.get("priority") == false) {
+ decision.get("customers").add(customerCtxt.get("customerName"));
+ }
+ }
+ var returnValue = new returnValueType(true);
+ } else {
+ logger.trace("-- wrong problemID <" + ifSituation.get("problemID") + "> for PRIORITY task, we should not be here");
+ rootLogger.error(executor.subject.id + " " + "-- wrong problemID <" + ifSituation.get("problemID")
+ + "> for PRIORITY task, we should not be here");
+ var returnValue = new returnValueType(false);
+ }
+
+ // set impededLast to decision[customers]
+ problem.get("impededLast").clear();
+ problem.get("impededLast").addAll(decision.get("customers"));
+
+ executor.outFields["decision"] = decision;
+ logger.trace("-- decision: " + decision);
+
+ logger.info("vpnsla: priority, impeding customers " + decision.get("customers"));
+
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".d-pri");
+
+Logic: Policy Act State
+------------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ This is the logic for the act state. It is simply
+ selecting an action, and creating the repsonse event
+ for the orchestrator (the output of the policy).
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ /*
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+ load("nashorn:mozilla_compat.js");
+
+ var logger = executor.logger;
+ logger.trace("start: " + executor.subject.id);
+ logger.trace("-- infields: " + executor.inFields);
+
+ var ifDecision = executor.inFields["decision"];
+ var ifMatchStart = executor.inFields["matchStart"];
+
+ var albumCustomerMap = executor.getContextAlbum("albumCustomerMap");
+ var albumProblemMap = executor.getContextAlbum("albumProblemMap");
+
+ switch (ifDecision.get("decision").toString()) {
+ case "NONE":
+ executor.outFields["edgeName"] = "";
+ executor.outFields["action"] = "";
+ break;
+ case "IMPEDE":
+ for (var i = 0; i < ifDecision.get("customers").size(); i++) {
+ customer = albumCustomerMap.get(ifDecision.get("customers").get(i).toString());
+ executor.outFields["edgeName"] = customer.get("links").get(0);
+ executor.outFields["action"] = "firewall";
+ }
+ break;
+ case "REBUILD":
+ // finally solved, remove problem
+ albumProblemMap.remove(ifDecision.get("problemID"));
+ executor.outFields["edgeName"] = "L10"; // this is ###static###
+ executor.outFields["action"] = "rebuild"; // this is ###static###
+ break;
+ default:
+
+ }
+
+ var returnValueType = Java.type("java.lang.Boolean");
+ var returnValue = new returnValueType(true);
+
+ if (executor.outFields["action"] != "") {
+ logger.info("vpnsla: action is to " + executor.outFields["action"] + " " + executor.outFields["edgeName"]);
+ } else {
+ logger.info("vpnsla: no action required");
+ }
+
+ logger.trace("-- outfields: " + executor.outFields);
+ logger.trace("finished: " + executor.subject.id);
+ logger.debug(".a");
+
+ var now = new Date().getTime();
+ logger.info("VPN SLA finished in " + (now - ifMatchStart) + " ms");
+
+CLI Spec
+--------
+
+ .. container:: sect1
+
+ .. rubric:: Complete Policy Definition
+ :name: complete_policy_definition
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The complete policy definition is realized using the
+ APEX CLI Editor. The script below shows the actual
+ policy specification. All logic and schemas are
+ included (as macro file).
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ #-------------------------------------------------------------------------------
+ # ============LICENSE_START=======================================================
+ # Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ # ================================================================================
+ # Licensed under the Apache License, Version 2.0 (the "License");
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ #
+ # SPDX-License-Identifier: Apache-2.0
+ # ============LICENSE_END=========================================================
+ #-------------------------------------------------------------------------------
+
+ # ============LICENSE_START=======================================================
+ # Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ # ================================================================================
+ # Licensed under the Apache License, Version 2.0 (the "License");
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ #
+ # SPDX-License-Identifier: Apache-2.0
+ # ============LICENSE_END=========================================================
+
+ model create name=PCVS-VpnSla version=1.0.0 description="Policies-Controlled Video Streaming, VPN SLA Policy Model"
+
+
+
+ schema create name=reportDecl version=1.0.0 description="Report of activities of a policy/task" flavour=Java schema=java.lang.String
+ event create name=ReportOut version=1.0.0 description="Report of a policy (issued by a task)" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="APEX" target="CtxtManagement"
+ event parameter create name=ReportOut version=1.0.0 parName=report schemaName=reportDecl schemaVersion=1.0.0
+
+ schema create name=timestampDecl version=1.0.0 description="Timestamp" flavour=Java schema=java.lang.Long
+
+
+
+ schema create name=ctxtEdgeNameDecl version=1.0.0 description="Topology Edges: edge (link) name" flavour=Java schema=java.lang.String
+ schema create name=ctxtEdgeStartDecl version=1.0.0 description="Topology Edges: edge endpoint (start)" flavour=Java schema=java.lang.String
+ schema create name=ctxtEdgeEndDecl version=1.0.0 description="Topology Edges: edge endpoint (end)" flavour=Java schema=java.lang.String
+ schema create name=ctxtEdgeStatusDecl version=1.0.0 description="Topology Edges: edge status as up (true) or down (false)" flavour=Java schema=java.lang.Boolean
+
+ schema create name=ctxtTopologyEdgesDecl version=1.0.0 description="Topology Edges Context Map" flavour=Avro schema=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/avro/topology-edges.avsc"
+ LE
+ album create name=albumTopoEdges scope=global writable=true schemaName=ctxtTopologyEdgesDecl
+
+
+ task create name=EdgeContextTask version=1.0.0 description="This task adds event context to edge context"
+ task inputfield create name=EdgeContextTask version=1.0.0 fieldName=edgeName schemaName=ctxtEdgeNameDecl schemaVersion=1.0.0
+ task inputfield create name=EdgeContextTask version=1.0.0 fieldName=start schemaName=ctxtEdgeStartDecl schemaVersion=1.0.0
+ task inputfield create name=EdgeContextTask version=1.0.0 fieldName=end schemaName=ctxtEdgeEndDecl schemaVersion=1.0.0
+ task inputfield create name=EdgeContextTask version=1.0.0 fieldName=status schemaName=ctxtEdgeStatusDecl schemaVersion=1.0.0
+ task outputfield create name=EdgeContextTask version=1.0.0 fieldName=report schemaName=reportDecl schemaVersion=1.0.0
+ task contextref create name=EdgeContextTask albumName=albumTopoEdges
+ task logic create name=EdgeContextTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/ctxt-edges.js"
+ LE
+
+ event create name=EdgeContextEventIn version=1.0.0 description="Event to add an Edge to engine Context" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="CtxtManagement" target="APEX"
+ event parameter create name=EdgeContextEventIn version=1.0.0 parName=edgeName schemaName=ctxtEdgeNameDecl schemaVersion=1.0.0
+ event parameter create name=EdgeContextEventIn version=1.0.0 parName=start schemaName=ctxtEdgeStartDecl schemaVersion=1.0.0
+ event parameter create name=EdgeContextEventIn version=1.0.0 parName=end schemaName=ctxtEdgeEndDecl schemaVersion=1.0.0
+ event parameter create name=EdgeContextEventIn version=1.0.0 parName=status schemaName=ctxtEdgeStatusDecl schemaVersion=1.0.0
+
+ policy create name=EdgeContextPolicy version=1.0.0 description="Policy that adds an edge to context" template=FREEFORM firstState=EdgeContextState
+ policy state create name=EdgeContextPolicy version=1.0.0 stateName=EdgeContextState triggerName=EdgeContextEventIn triggerVersion=1.0.0 defaultTaskName=EdgeContextTask defaultTaskVersion=1.0.0
+ policy state output create name=EdgeContextPolicy version=1.0.0 stateName=EdgeContextState outputName=EdgeContextState_Output_Direct eventName=ReportOut eventVersion=1.0.0 nextState=NULL
+ policy state taskref create name=EdgeContextPolicy version=1.0.0 stateName=EdgeContextState taskLocalName=doContext taskName=EdgeContextTask taskVersion=1.0.0 outputType=DIRECT outputName=EdgeContextState_Output_Direct
+
+
+
+ schema create name=ctxtNodeNameDecl version=1.0.0 description="Topology Nodes: node name" flavour=Java schema=java.lang.String
+ schema create name=ctxtNodeMininetNameDecl version=1.0.0 description="Topology Nodes: node name in Mininet" flavour=Java schema=java.lang.String
+
+ schema create name=ctxtTopologyNodesDecl version=1.0.0 description="Topology Nodes Context Map" flavour=Avro schema=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/avro/topology-nodes.avsc"
+ LE
+ album create name=albumTopoNodes scope=global writable=true schemaName=ctxtTopologyNodesDecl
+
+ task create name=NodeContextTask version=1.0.0 description="This task adds event context to node context"
+ task inputfield create name=NodeContextTask version=1.0.0 fieldName=nodeName schemaName=ctxtNodeNameDecl schemaVersion=1.0.0
+ task inputfield create name=NodeContextTask version=1.0.0 fieldName=mininetName schemaName=ctxtNodeMininetNameDecl schemaVersion=1.0.0
+ task outputfield create name=NodeContextTask version=1.0.0 fieldName=report schemaName=reportDecl schemaVersion=1.0.0
+ task contextref create name=NodeContextTask albumName=albumTopoNodes
+ task logic create name=NodeContextTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/ctxt-nodes.js"
+ LE
+
+ event create name=NodeContextEventIn version=1.0.0 description="Event to add Node to engine Context" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="CtxtManagement" target="APEX"
+ event parameter create name=NodeContextEventIn version=1.0.0 parName=nodeName schemaName=ctxtNodeNameDecl schemaVersion=1.0.0
+ event parameter create name=NodeContextEventIn version=1.0.0 parName=mininetName schemaName=ctxtNodeMininetNameDecl schemaVersion=1.0.0
+
+ policy create name=NodeContextPolicy version=1.0.0 description="Policy that adds an node to context" template=FREEFORM firstState=NodeContextState
+ policy state create name=NodeContextPolicy version=1.0.0 stateName=NodeContextState triggerName=NodeContextEventIn triggerVersion=1.0.0 defaultTaskName=NodeContextTask defaultTaskVersion=1.0.0
+ policy state output create name=NodeContextPolicy version=1.0.0 stateName=NodeContextState outputName=NodeContextState_Output_Direct eventName=ReportOut eventVersion=1.0.0 nextState=NULL
+ policy state taskref create name=NodeContextPolicy version=1.0.0 stateName=NodeContextState taskLocalName=doContext taskName=NodeContextTask taskVersion=1.0.0 outputType=DIRECT outputName=NodeContextState_Output_Direct
+
+
+
+
+ schema create name=ctxtCustomerNameDecl version=1.0.0 description="Customer Context: customer name" flavour=Java schema=java.lang.String
+ schema create name=ctxtCustomerPriorityDecl version=1.0.0 description="Customer Context: priority flag" flavour=Java schema=java.lang.Boolean
+ schema create name=ctxtCustomerSatisfactionDecl version=1.0.0 description="Customer Context: satisfaction in percent" flavour=Java schema=java.lang.Integer
+ schema create name=ctxtCustomerDowntimeSLADecl version=1.0.0 description="Customer Context: contracted downtime as per SLA" flavour=Java schema=java.lang.Integer
+ schema create name=ctxtCustomerDowntimeYTDDecl version=1.0.0 description="Customer Context: year-to-date downtime experienced" flavour=Java schema=java.lang.Integer
+ schema create name=ctxtCustomerLinksDecl version=1.0.0 description="Customer Context: links a customer uses (for events/task)" flavour=Java schema=java.lang.String
+
+ schema create name=ctxtCustomerMapDecl version=1.0.0 description="Map of customers with all known information" flavour=Avro schema=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/avro/customers.avsc"
+ LE
+ album create name=albumCustomerMap scope=global writable=true schemaName=ctxtCustomerMapDecl
+
+ task create name=CustomerContextTask version=1.0.0 description="This task adds event context to customer context"
+ task inputfield create name=CustomerContextTask version=1.0.0 fieldName=customerName schemaName=ctxtCustomerNameDecl schemaVersion=1.0.0
+ task inputfield create name=CustomerContextTask version=1.0.0 fieldName=priority schemaName=ctxtCustomerPriorityDecl schemaVersion=1.0.0
+ task inputfield create name=CustomerContextTask version=1.0.0 fieldName=satisfaction schemaName=ctxtCustomerSatisfactionDecl schemaVersion=1.0.0
+ task inputfield create name=CustomerContextTask version=1.0.0 fieldName=dtSLA schemaName=ctxtCustomerDowntimeSLADecl schemaVersion=1.0.0
+ task inputfield create name=CustomerContextTask version=1.0.0 fieldName=dtYTD schemaName=ctxtCustomerDowntimeYTDDecl schemaVersion=1.0.0
+ task inputfield create name=CustomerContextTask version=1.0.0 fieldName=links schemaName=ctxtCustomerLinksDecl schemaVersion=1.0.0
+ task outputfield create name=CustomerContextTask version=1.0.0 fieldName=report schemaName=reportDecl schemaVersion=1.0.0
+ task contextref create name=CustomerContextTask albumName=albumCustomerMap
+ task contextref create name=CustomerContextTask albumName=albumTopoEdges
+ task logic create name=CustomerContextTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/ctxt-customer.js"
+ LE
+
+ event create name=CustomerContextEventIn version=1.0.0 description="Event to add Customers to engine Context" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="CtxtManagement" target="APEX"
+ event parameter create name=CustomerContextEventIn version=1.0.0 parName=customerName schemaName=ctxtCustomerNameDecl schemaVersion=1.0.0
+ event parameter create name=CustomerContextEventIn version=1.0.0 parName=priority schemaName=ctxtCustomerPriorityDecl schemaVersion=1.0.0
+ event parameter create name=CustomerContextEventIn version=1.0.0 parName=satisfaction schemaName=ctxtCustomerSatisfactionDecl schemaVersion=1.0.0
+ event parameter create name=CustomerContextEventIn version=1.0.0 parName=dtSLA schemaName=ctxtCustomerDowntimeSLADecl schemaVersion=1.0.0
+ event parameter create name=CustomerContextEventIn version=1.0.0 parName=dtYTD schemaName=ctxtCustomerDowntimeYTDDecl schemaVersion=1.0.0
+ event parameter create name=CustomerContextEventIn version=1.0.0 parName=links schemaName=ctxtCustomerLinksDecl schemaVersion=1.0.0
+
+ policy create name=CustomerContextPolicy version=1.0.0 description="Policy that adds Customer information to engine context" template=FREEFORM firstState=CustomerContextState
+ policy state create name=CustomerContextPolicy version=1.0.0 stateName=CustomerContextState triggerName=CustomerContextEventIn triggerVersion=1.0.0 defaultTaskName=CustomerContextTask defaultTaskVersion=1.0.0
+ policy state output create name=CustomerContextPolicy version=1.0.0 stateName=CustomerContextState outputName=CustomerContextState_Output_Direct eventName=ReportOut eventVersion=1.0.0 nextState=NULL
+ policy state taskref create name=CustomerContextPolicy version=1.0.0 stateName=CustomerContextState taskLocalName=doContext taskName=CustomerContextTask taskVersion=1.0.0 outputType=DIRECT outputName=CustomerContextState_Output_Direct
+
+
+
+
+ schema create name=edgeNameDecl version=1.0.0 description="Edge name" flavour=Java schema=java.lang.String
+ schema create name=edgeStatusDecl version=1.0.0 description="Statuf of the edge (UP, DOWN)" flavour=Avro schema=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/avro/link-status.avsc"
+ LE
+ schema create name=edgeChangedDecl version=1.0.0 description="Status Change (true:change, false:no change)" flavour=Java schema=java.lang.Boolean
+
+ task create name=VpnSlaPolicyMatchTask version=1.0.0 description="Pre-process an edge event"
+ task inputfield create name=VpnSlaPolicyMatchTask version=1.0.0 fieldName=edgeName schemaName=edgeNameDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyMatchTask version=1.0.0 fieldName=status schemaName=edgeStatusDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyMatchTask version=1.0.0 fieldName=edgeName schemaName=edgeNameDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyMatchTask version=1.0.0 fieldName=status schemaName=edgeStatusDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyMatchTask version=1.0.0 fieldName=hasChanged schemaName=edgeChangedDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyMatchTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task contextref create name=VpnSlaPolicyMatchTask albumName=albumTopoEdges
+ task logic create name=VpnSlaPolicyMatchTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/task-match.js"
+ LE
+
+
+
+
+ schema create name=problemMapDecl version=1.0.0 description="Map of problems with all known Information" flavour=Avro schema=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/avro/problems.avsc"
+ LE
+ album create name=albumProblemMap scope=global writable=true schemaName=problemMapDecl
+
+ schema create name=establishSituationDecl version=1.0.0 description="Establish: the situation that was established" flavour=Avro schema=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/avro/situation.avsc"
+ LE
+
+ task create name=VpnSlaPolicyEstablishTask version=1.0.0 description="Task taking a match event and establishing a situation"
+ task inputfield create name=VpnSlaPolicyEstablishTask version=1.0.0 fieldName=edgeName schemaName=edgeNameDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyEstablishTask version=1.0.0 fieldName=status schemaName=edgeStatusDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyEstablishTask version=1.0.0 fieldName=hasChanged schemaName=edgeChangedDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyEstablishTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyEstablishTask version=1.0.0 fieldName=situation schemaName=establishSituationDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyEstablishTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task contextref create name=VpnSlaPolicyEstablishTask albumName=albumProblemMap
+ task contextref create name=VpnSlaPolicyEstablishTask albumName=albumCustomerMap
+ task logic create name=VpnSlaPolicyEstablishTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/task-establish.js"
+ LE
+
+
+
+
+ schema create name=decideDecisionDecl version=1.0.0 description="Decide: the taken decision" flavour=Avro schema=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/avro/decision.avsc"
+ LE
+
+ task create name=VpnSlaPolicyDecideNoneTask version=1.0.0 description="Decide task for a 'none' problem"
+ task inputfield create name=VpnSlaPolicyDecideNoneTask version=1.0.0 fieldName=situation schemaName=establishSituationDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyDecideNoneTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecideNoneTask version=1.0.0 fieldName=decision schemaName=decideDecisionDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecideNoneTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task logic create name=VpnSlaPolicyDecideNoneTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/task-decide-none.js"
+ LE
+
+
+ task create name=VpnSlaPolicyDecideSlaTask version=1.0.0 description="Decide task solving the problem by balancing SLAs"
+ task inputfield create name=VpnSlaPolicyDecideSlaTask version=1.0.0 fieldName=situation schemaName=establishSituationDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyDecideSlaTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecideSlaTask version=1.0.0 fieldName=decision schemaName=decideDecisionDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecideSlaTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task contextref create name=VpnSlaPolicyDecideSlaTask albumName=albumCustomerMap
+ task contextref create name=VpnSlaPolicyDecideSlaTask albumName=albumProblemMap
+ task logic create name=VpnSlaPolicyDecideSlaTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/task-decide-sla.js"
+ LE
+
+
+ task create name=VpnSlaPolicyDecidePriorityTask version=1.0.0 description="Decide task solving the problem by using customer priorities"
+ task inputfield create name=VpnSlaPolicyDecidePriorityTask version=1.0.0 fieldName=situation schemaName=establishSituationDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyDecidePriorityTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecidePriorityTask version=1.0.0 fieldName=decision schemaName=decideDecisionDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecidePriorityTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task contextref create name=VpnSlaPolicyDecidePriorityTask albumName=albumCustomerMap
+ task contextref create name=VpnSlaPolicyDecidePriorityTask albumName=albumProblemMap
+ task logic create name=VpnSlaPolicyDecidePriorityTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/task-decide-priority.js"
+ LE
+
+
+ task create name=VpnSlaPolicyDecideSolvedTask version=1.0.0 description="Decide task solving the problem by using customer priorities"
+ task inputfield create name=VpnSlaPolicyDecideSolvedTask version=1.0.0 fieldName=situation schemaName=establishSituationDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyDecideSolvedTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecideSolvedTask version=1.0.0 fieldName=decision schemaName=decideDecisionDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyDecideSolvedTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task contextref create name=VpnSlaPolicyDecideSolvedTask albumName=albumProblemMap
+ task logic create name=VpnSlaPolicyDecideSolvedTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/task-decide-solved.js"
+ LE
+
+
+
+
+ schema create name=actionDecl version=1.0.0 description="An action for the actioning system" flavour=Java schema=java.lang.String
+
+ task create name=VpnSlaPolicyActTask version=1.0.0 description="Task issueing an action for taken decision"
+ task inputfield create name=VpnSlaPolicyActTask version=1.0.0 fieldName=decision schemaName=decideDecisionDecl schemaVersion=1.0.0
+ task inputfield create name=VpnSlaPolicyActTask version=1.0.0 fieldName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyActTask version=1.0.0 fieldName=edgeName schemaName=edgeNameDecl schemaVersion=1.0.0
+ task outputfield create name=VpnSlaPolicyActTask version=1.0.0 fieldName=action schemaName=actionDecl schemaVersion=1.0.0
+ task contextref create name=VpnSlaPolicyActTask albumName=albumCustomerMap
+ task contextref create name=VpnSlaPolicyActTask albumName=albumProblemMap
+ task logic create name=VpnSlaPolicyActTask logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/task-act.js"
+ LE
+
+
+
+
+
+
+
+ event create name=VpnSlaTrigger version=1.0.0 description="Event triggering the VPN SLA policy" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="TriggerSys" target="VpnSlaMatch"
+ event parameter create name=VpnSlaTrigger version=1.0.0 parName=edgeName schemaName=edgeNameDecl schemaVersion=1.0.0
+ event parameter create name=VpnSlaTrigger version=1.0.0 parName=status schemaName=edgeStatusDecl schemaVersion=1.0.0
+
+ event create name=VpnSlaMatchOut version=1.0.0 description="Event with matched trigger for the VPN SLA policy" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="VpnSlaMatch" target="VpnSlaEstablish"
+ event parameter create name=VpnSlaMatchOut version=1.0.0 parName=edgeName schemaName=edgeNameDecl schemaVersion=1.0.0
+ event parameter create name=VpnSlaMatchOut version=1.0.0 parName=status schemaName=edgeStatusDecl schemaVersion=1.0.0
+ event parameter create name=VpnSlaMatchOut version=1.0.0 parName=hasChanged schemaName=edgeChangedDecl schemaVersion=1.0.0
+ event parameter create name=VpnSlaMatchOut version=1.0.0 parName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+
+ event create name=VpnSlaEstablishOut version=1.0.0 description="Event with situation for the SLA policy" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="SlaEstablish" target="SlaDecide"
+ event parameter create name=VpnSlaEstablishOut version=1.0.0 parName=situation schemaName=establishSituationDecl schemaVersion=1.0.0
+ event parameter create name=VpnSlaEstablishOut version=1.0.0 parName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+
+ event create name=VpnSlaDecideOut version=1.0.0 description="Event with a decision for the SLA policy" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="SlaDecide" target="SlaAct"
+ event parameter create name=VpnSlaDecideOut version=1.0.0 parName=decision schemaName=decideDecisionDecl schemaVersion=1.0.0
+ event parameter create name=VpnSlaDecideOut version=1.0.0 parName=matchStart schemaName=timestampDecl schemaVersion=1.0.0
+
+ event create name=VpnSlaActOut version=1.0.0 description="Event action" nameSpace=org.onap.policy.apex.examples.pcvs.vpnsla source="SlaAct" target="ActioningSystem"
+ event parameter create name=VpnSlaActOut version=1.0.0 parName=edgeName schemaName=edgeNameDecl schemaVersion=1.0.0
+ event parameter create name=VpnSlaActOut version=1.0.0 parName=action schemaName=actionDecl schemaVersion=1.0.0
+
+
+ policy create name=VpnSlaPolicy version=1.0.0 description="Policy deciding customer treatment based on SLAs as MEDA policy" template=FREEFORM firstState=VpnSlaPolicyMatchState
+
+ policy state create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyActState triggerName=VpnSlaDecideOut triggerVersion=1.0.0 defaultTaskName=VpnSlaPolicyActTask defaultTaskVersion=1.0.0
+ policy state output create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyActState outputName=SlaPolicyAct_Output_Direct eventName=VpnSlaActOut eventVersion=1.0.0 nextState=NULL
+ policy state taskref create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyActState taskLocalName=act taskName=VpnSlaPolicyActTask taskVersion=1.0.0 outputType=DIRECT outputName=SlaPolicyAct_Output_Direct
+
+ policy state create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyDecideState triggerName=VpnSlaEstablishOut triggerVersion=1.0.0 defaultTaskName=VpnSlaPolicyDecideSlaTask defaultTaskVersion=1.0.0
+ policy state contextref create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyDecideState albumName=albumProblemMap
+ policy state selecttasklogic create name=VpnSlaPolicy stateName=VpnSlaPolicyDecideState logicFlavour=JAVASCRIPT logic=LS
+ #MACROFILE:"src/main/resources/org/onap/policy/apex/examples/pcvs/vpnsla/logic/tsl-decide.js"
+ LE
+ policy state output create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyDecideState outputName=VpnSlaPolicyDecide_Output_Direct eventName=VpnSlaDecideOut eventVersion=1.0.0 nextState=VpnSlaPolicyActState
+ policy state taskref create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyDecideState taskLocalName=decideNone taskName=VpnSlaPolicyDecideNoneTask taskVersion=1.0.0 outputType=DIRECT outputName=VpnSlaPolicyDecide_Output_Direct
+ policy state taskref create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyDecideState taskLocalName=decideNone taskName=VpnSlaPolicyDecideSolvedTask taskVersion=1.0.0 outputType=DIRECT outputName=VpnSlaPolicyDecide_Output_Direct
+ policy state taskref create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyDecideState taskLocalName=decideSla taskName=VpnSlaPolicyDecideSlaTask taskVersion=1.0.0 outputType=DIRECT outputName=VpnSlaPolicyDecide_Output_Direct
+ policy state taskref create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyDecideState taskLocalName=decidePriority taskName=VpnSlaPolicyDecidePriorityTask taskVersion=1.0.0 outputType=DIRECT outputName=VpnSlaPolicyDecide_Output_Direct
+
+ policy state create name=VpnSlaPolicy version=1.0.0 stateName=VpmSlaPolicyEstablishState triggerName=VpnSlaMatchOut triggerVersion=1.0.0 defaultTaskName=VpnSlaPolicyEstablishTask defaultTaskVersion=1.0.0
+ policy state output create name=VpnSlaPolicy version=1.0.0 stateName=VpmSlaPolicyEstablishState outputName=VpnSlaPolicyEstablish_Output_Direct eventName=VpnSlaEstablishOut eventVersion=1.0.0 nextState=VpnSlaPolicyDecideState
+ policy state taskref create name=VpnSlaPolicy version=1.0.0 stateName=VpmSlaPolicyEstablishState taskLocalName=establish taskName=VpnSlaPolicyEstablishTask taskVersion=1.0.0 outputType=DIRECT outputName=VpnSlaPolicyEstablish_Output_Direct
+
+ policy state create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyMatchState triggerName=VpnSlaTrigger triggerVersion=1.0.0 defaultTaskName=VpnSlaPolicyMatchTask defaultTaskVersion=1.0.0
+ policy state output create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyMatchState outputName=VpnSlaPolicyMatch_Output_Direct eventName=VpnSlaMatchOut eventVersion=1.0.0 nextState=VpmSlaPolicyEstablishState
+ policy state taskref create name=VpnSlaPolicy version=1.0.0 stateName=VpnSlaPolicyMatchState taskLocalName=match taskName=VpnSlaPolicyMatchTask taskVersion=1.0.0 outputType=DIRECT outputName=VpnSlaPolicyMatch_Output_Direct
+
+
+
+ validate
+ quit
+
+Context Events Nodes
+--------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The following events create all nodes of the topology.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "A1",
+ "mininetName": "nn"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "A2",
+ "mininetName": "nn"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "B1",
+ "mininetName": "nn"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "B2",
+ "mininetName": "nn"
+ }
+
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "A1CO",
+ "mininetName": "s1"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "A2CO",
+ "mininetName": "s2"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "B1CO",
+ "mininetName": "s3"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "B2CO",
+ "mininetName": "s4"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "BBL",
+ "mininetName": "s5"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "NodeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_NodeContext",
+ "nodeName": "BBR",
+ "mininetName": "s6"
+ }
+
+Context Events Edges
+--------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The following events create all edges of the topology.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L01",
+ "start": "A1",
+ "end": "A1CO",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L02",
+ "start": "B1",
+ "end": "B1CO",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L03",
+ "start": "A2",
+ "end": "A2CO",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L04",
+ "start": "B2",
+ "end": "B2CO",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L05",
+ "start": "A1CO",
+ "end": "BBL",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L06",
+ "start": "B1CO",
+ "end": "BBL",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L07",
+ "start": "A2CO",
+ "end": "BBR",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L08",
+ "start": "B2CO",
+ "end": "BBR",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L09",
+ "start": "BBL",
+ "end": "BBR",
+ "status": true
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "EdgeContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_EdgeContext",
+ "edgeName": "L10",
+ "start": "BBR",
+ "end": "BBL",
+ "status": true
+ }
+
+Context Events Customers
+------------------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The following events create all customers of the
+ topology.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "CustomerContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_CustomerContext",
+ "customerName": "A",
+ "links": "L01 L05 L09 L10",
+ "dtSLA": 180,
+ "dtYTD": 10,
+ "priority": false,
+ "satisfaction": 80
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "CustomerContextEventIn",
+ "version": "1.0.0",
+ "source": "CtxtManagement",
+ "target" : "VpnSlaPolicy_CustomerContext",
+ "customerName": "B",
+ "links": "L02 L07 L09 L10",
+ "dtSLA": 180,
+ "dtYTD": 120,
+ "priority": true,
+ "satisfaction": 99
+ }
+
+Trigger Examples
+----------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The following events are examples for trigger events
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "VpnSlaTrigger",
+ "version": "1.0.0",
+ "source": "ExampleEvents",
+ "target" : "VpnSlaPolicy",
+ "edgeName": "L09",
+ "status": "UP"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "VpnSlaTrigger",
+ "version": "1.0.0",
+ "source": "ExampleEvents",
+ "target" : "VpnSlaPolicy",
+ "edgeName": "L09",
+ "status": "UP"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "VpnSlaTrigger",
+ "version": "1.0.0",
+ "source": "ExampleEvents",
+ "target" : "VpnSlaPolicy",
+ "edgeName": "L09",
+ "status": "DOWN"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "VpnSlaTrigger",
+ "version": "1.0.0",
+ "source": "ExampleEvents",
+ "target" : "VpnSlaPolicy",
+ "edgeName": "L09",
+ "status": "DOWN"
+ }
+
+ {
+ "nameSpace": "org.onap.policy.apex.examples.pcvs.vpnsla",
+ "name": "VpnSlaTrigger",
+ "version": "1.0.0",
+ "source": "ExampleEvents",
+ "target" : "VpnSlaPolicy",
+ "edgeName": "L09",
+ "status": "UP"
+ }
+
+Link Monitor
+------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The Link Monitor is a Python script. At startup, it
+ sends the context events to APEX to initialize the
+ topology and the customers. Then it takes events from
+ Kafka and sends them to APEX.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ # ============LICENSE_START=======================================================
+ # Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ # ================================================================================
+ # Licensed under the Apache License, Version 2.0 (the "License");
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ #
+ # SPDX-License-Identifier: Apache-2.0
+ # ============LICENSE_END=========================================================
+
+ import http.client
+ import json
+ import time
+ from kafka import KafkaConsumer, KafkaProducer
+
+ class StaticFlowPusher(object):
+
+ def __init__(self, server):
+ self.server = server
+
+ def get(self, data):
+ ret = self.rest_call({}, 'GET')
+ return json.loads(ret[2])
+
+ def set(self, data):
+ ret = self.rest_call(data, 'POST')
+ return ret[0] == 200
+
+ def remove(self, objtype, data):
+ ret = self.rest_call(data, 'DELETE')
+ return ret[0] == 200
+
+ def getControllerSummary(self, data):
+ ret = self.rest_call_controller_summary({}, 'GET')
+ return json.loads(ret[2])
+
+ def getLinks(self, data):
+ ret = self.rest_call_links({}, 'GET')
+ return json.loads(ret[2].decode())
+
+ def rest_call(self, data, action):
+ path = '/wm/staticflowpusher/json'
+ headers = {
+ 'Content-type': 'application/json',
+ 'Accept': 'application/json',
+ }
+ body = json.dumps(data)
+ conn = http.client.HTTPConnection(self.server, 8080)
+ conn.request(action, path, body, headers)
+ response = conn.getresponse()
+ ret = (response.status, response.reason, response.read())
+ print(ret)
+ conn.close()
+ return ret
+
+ def rest_call_controller_summary(self, data, action):
+ path = '/wm/core/controller/summary/json'
+ headers = {
+ 'Content-type': 'application/json',
+ 'Accept': 'application/json',
+ }
+ body = json.dumps(data)
+ conn = http.client.HTTPConnection(self.server, 8080)
+ conn.request(action, path, body, headers)
+ response = conn.getresponse()
+ ret = (response.status, response.reason, response.read())
+ print(ret)
+ conn.close()
+ return ret
+
+ def rest_call_links(self, data, action):
+ path = '/wm/topology/links/json'
+ headers = {
+ 'Content-type': 'application/json',
+ 'Accept': 'application/json',
+ }
+ body = json.dumps(data)
+ conn = http.client.HTTPConnection(self.server, 8080)
+ conn.request(action, path, body, headers)
+ response = conn.getresponse()
+ ret = (response.status, response.reason, response.read())
+ conn.close()
+ return ret
+
+ pusher = StaticFlowPusher('127.0.1.1')
+
+
+ def parseLinks(links):
+ #print("\n\n\n",links)
+ result = []
+ for link in links:
+ list = []
+ #print("\n\n\n",link)
+ #print("\nsrc-switch : s", link['src-switch'][len(link['src-switch'])-1])
+ #print("\ndst-switch : s", link['dst-switch'][len(link['dst-switch'])-1])
+ list.append("s")
+ list.append(link['src-switch'][len(link['src-switch'])-1])
+ list.append("-s")
+ list.append(link['dst-switch'][len(link['dst-switch'])-1])
+ result.append(''.join(list))
+ #print(result, "\n")
+ return result
+
+
+
+ counter =0
+ healthyList = []
+ testableList = []
+ healthyLinks = ""
+ testableLinks = ""
+ producer = KafkaProducer(bootstrap_servers='localhost:9092')
+ while(True):
+ time.sleep(30)
+ switchLinks = pusher.getLinks({})
+ if counter == 0:
+ healthyList = parseLinks(switchLinks)
+ #Build All Links
+ print("READING LINKS FROM MININET\n")
+ for l in healthyList:
+ link = ""
+ #print(l, "\n")
+ #Links between switches [s6-s7 is ignored so it matches VPN SCENARIO]
+ if(l == "s1-s5"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L05', 'start': 'A1CO','end': 'BBL'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(l == "s5-s6"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L09', 'start': 'BBL','end': 'BBR'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(l == "s2-s6"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L07', 'start': 'A2CO','end': 'BBR'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(l == "s5-s7"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L10', 'start': 'BBR','end': 'BBL'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(l == "s3-s5"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L06', 'start': 'B1CO','end': 'BBL'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(l == "s4-s6"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L08', 'start': 'B2CO','end': 'BBR'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ #Links between switches and hosts [NoT SENT IN FROM FLOODLIGHT]
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L01', 'start': 'A1','end': 'A1CO'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L02', 'start': 'B1','end': 'B1CO'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L03', 'start': 'A2','end': 'A2CO'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'EdgeContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_EdgeContext','status': true,'edgeName': 'L04', 'start': 'B2','end': 'B2CO'}")
+ print("LINKS HAVE BEEN SENT TO APEX\n")
+
+ #Build Customers
+ print("BUILDING CUSTOMERS\n")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'CustomerContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_CustomerContext','dtYTD': 10,'dtSLA': 180,'links': 'L01 L05 L09 L10','customerName': 'A', 'priority': true,'satisfaction': 80}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'CustomerContextEventIn','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy_CustomerContext','dtYTD': 120,'dtSLA': 180,'links': 'L02 L07 L09 L10','customerName': 'B', 'priority': false,'satisfaction': 99}")
+ print("CUSTOMERS HAVE BEEN SENT TO APEX\n")
+ healthyLinks = switchLinks
+ myfile = open('LinkInfo.json', 'a')
+ myfile.write(str(healthyLinks))
+ myfile.write('\n')
+ myfile.close()
+ print("We start off with", len(healthyLinks), "healthy Links!\n")
+ else:
+ testableList = parseLinks(switchLinks)
+ issueLink = "";
+ for h in healthyList:
+ issueLink = h
+ for t in testableList:
+ if t == h:
+ issueLink = ""
+ if issueLink != "":
+ print("There is an issue with the links! ", issueLink, " \n")
+ if(issueLink == "s1-s5"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'DOWN','edgeName': 'L05'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(issueLink == "s5-s6"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'DOWN','edgeName': 'L09'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(issueLink == "s2-s6"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'DOWN','edgeName': 'L07'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(issueLink == "s5-s7"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'DOWN','edgeName': 'L10'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(issueLink == "s3-s5"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'DOWN','edgeName': 'L06'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ if(issueLink == "s4-s6"):
+ link = "{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'DOWN','edgeName': 'L08'}"
+ producer.send("apex-in-0", bytes(link, encoding="ascii"))
+ break
+ if issueLink == "":
+ print("All Links are working\n")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L01'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L02'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L03'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L04'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L05'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L06'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L07'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L08'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L09'}")
+ producer.send("apex-in-0", b"{'nameSpace': 'org.onap.policy.apex.examples.pcvs.vpnsla','name': 'VpnSlaTrigger','version': '1.0.0','source': 'LinkMonitor.py','target': 'VpnSlaPolicy','status': 'UP','edgeName': 'L10'}")
+
+ testableLinks = switchLinks
+ myfile = open('LinkInfo.json', 'a')
+ myfile.write(str(testableLinks))
+ myfile.write('\n')
+ myfile.close()
+ counter += 1
+
+Mininet Topology
+----------------
+
+ .. container:: sect1
+
+ .. container:: sectionbody
+
+ .. container:: paragraph
+
+ The topology is realized using Mininet. The following
+ script is use to estalish the topology and to realize
+ network configurations.
+
+ .. container:: listingblock
+
+ .. container:: content
+
+ .. code:: CodeRay
+
+ # ============LICENSE_START=======================================================
+ # Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ # ================================================================================
+ # Licensed under the Apache License, Version 2.0 (the "License");
+ # you may not use this file except in compliance with the License.
+ # You may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ # See the License for the specific language governing permissions and
+ # limitations under the License.
+ #
+ # SPDX-License-Identifier: Apache-2.0
+ # ============LICENSE_END=========================================================
+
+ #Add Mininet to PATH
+ import sys
+ sys.path.insert(0, "/~/mininet")
+
+ #Kafka
+ import httplib
+ import json
+ import time
+ from kafka import KafkaConsumer, KafkaProducer
+
+ #Mininet
+ from mininet.clean import *
+ from mininet.cli import *
+ from mininet.link import *
+ from mininet.log import *
+ from mininet.net import *
+ from mininet.node import *
+ from mininet.nodelib import *
+ from mininet.topo import *
+ from mininet.topolib import *
+
+ class StaticFlowPusher(object):
+ def __init__(self, server):
+ self.server = server
+
+ def enableFirewall(self, data):
+ path = "/wm/firewall/module/enable/json"
+ headers = {'Content-Type': 'application/json','Accept': 'application/json',}
+ body = json.dumps(data)
+ conn = httplib.HTTPConnection(self.server, 8080)
+ conn.request("PUT", path, "")
+ response = conn.getresponse()
+ ret = (response.status, response.reason, response.read())
+ conn.close()
+ return ret
+
+ def addRule(self, data):
+ path = '/wm/firewall/rules/json'
+ headers = {'Content-Type': 'application/json','Accept': 'application/json',}
+ body = json.dumps(data)
+ conn = httplib.HTTPConnection(self.server, 8080)
+ conn.request('POST', path, body, headers)
+ response = conn.getresponse()
+ ret = (response.status, response.reason, response.read())
+ conn.close()
+ return ret
+
+ def deleteRule(self, data):
+ path = '/wm/firewall/rules/json'
+ headers = {'Content-Type': 'application/json','Accept': 'application/json',}
+ body = json.dumps(data)
+ conn = httplib.HTTPConnection(self.server, 8080)
+ conn.request('DELETE', path, body, headers)
+ response = conn.getresponse()
+ ret = (response.status, response.reason, response.read())
+ conn.close()
+ return ret
+
+ #Build Pusher(REST/IN)
+ pusher = StaticFlowPusher('127.0.0.1')
+
+ net = Mininet(link=TCLink)
+
+ #Create Customers
+ customerA1 = net.addHost( 'A1' )
+ customerA2 = net.addHost( 'A2' )
+ customerB1 = net.addHost( 'B1' )
+ customerB2 = net.addHost( 'B2' )
+
+ #Create Switches
+ switchA1CO = net.addSwitch( 's1' )
+ switchA2CO = net.addSwitch( 's2' )
+ switchB1CO = net.addSwitch( 's3' )
+ switchB2CO = net.addSwitch( 's4' )
+ switchBBL = net.addSwitch( 's5' )
+ switchBBR = net.addSwitch( 's6' )
+ # we need an extra switch here because Mininet does not allow two links between two switches
+ switchEx = net.addSwitch( 's7' )
+
+ #Create Links
+ net.addLink( customerA1, switchA1CO )
+ net.addLink( customerA2, switchA2CO )
+ net.addLink( customerB1, switchB1CO )
+ net.addLink( customerB2, switchB2CO )
+ net.addLink( switchA1CO, switchBBL )
+ net.addLink( switchB1CO, switchBBL )
+ net.addLink( switchA2CO, switchBBR )
+ net.addLink( switchB2CO, switchBBR )
+ net.addLink( switchBBL, switchBBR)
+ net.addLink( switchBBR, switchEx, bw=1.2 )
+ net.addLink( switchEx, switchBBL )
+
+ #Create Controller
+ floodlightController = net.addController(name='c0' , controller=RemoteController , ip='127.0.0.1', port=6653)
+
+ net.start()
+
+ if pusher.enableFirewall({})[0] == 200:
+ print("Firewall enabled!")
+
+ #print(pusher.addRule({"switchid": "00:00:00:00:00:00:00:01"})[2])
+ s1id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:01"})[2])['rule-id']
+ s2id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:02"})[2])['rule-id']
+ s3id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:03"})[2])['rule-id']
+ s4id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:04"})[2])['rule-id']
+ s5id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:05"})[2])['rule-id']
+ s6id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:06"})[2])['rule-id']
+ s7id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:07"})[2])['rule-id']
+
+
+ result = 100
+ while result!=0:
+ result = net.pingAll(None)
+ print("Network Simulation Complete")
+
+ #Assume control and when finished "exit"
+ cli = CLI( net )
+
+ consumer = KafkaConsumer(bootstrap_servers='localhost:9092',auto_offset_reset='latest')
+ consumer.subscribe(['apex-out'])
+ print("Starting Message Loop")
+ for message in consumer:
+ myOutput = json.loads(message.value.decode())
+ action = ""
+ try:
+ print("Checking Message")
+ #print("SWITCHES= ",net.switches)
+ #print("LINKS= ",net.links)
+ #print("VALUES= ",net.values)
+ if myOutput['edgeName'] != '':
+ print("Message Received: ",myOutput['edgeName'])
+ pusher.deleteRule({"ruleid": s1id})
+ pusher.deleteRule({"ruleid": s2id})
+ pusher.deleteRule({"ruleid": s3id})
+ pusher.deleteRule({"ruleid": s4id})
+ pusher.deleteRule({"ruleid": s5id})
+ pusher.deleteRule({"ruleid": s6id})
+ pusher.deleteRule({"ruleid": s7id})
+ s1id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:01"})[2])['rule-id']
+ s2id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:02"})[2])['rule-id']
+ s3id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:03"})[2])['rule-id']
+ s4id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:04"})[2])['rule-id']
+ s5id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:05"})[2])['rule-id']
+ s6id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:06"})[2])['rule-id']
+ s7id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:07"})[2])['rule-id']
+ if myOutput['edgeName'] == "L01":
+ action = "link s1 s5 down"
+ #net.configLinkStatus('s1', 's5', "down")
+ pusher.deleteRule({"ruleid": s1id})
+ s1id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:01", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L02":
+ action = "link s3 s5 down"
+ #net.configLinkStatus('s3', 's5', "down")
+ pusher.deleteRule({"ruleid": s3id})
+ s3id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:03", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L03":
+ action = "link s2 s6 down"
+ #net.configLinkStatus('s2', 's6', "down")
+ pusher.deleteRule({"ruleid": s1id})
+ s1id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:01", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L04":
+ action = "link s4 s6 down"
+ #net.configLinkStatus('s4', 's6', "down")
+ pusher.deleteRule({"ruleid": s3id})
+ s3id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:03", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L05":
+ action = "link s1 s5 down"
+ #net.configLinkStatus('s1', 's5', "down")
+ pusher.deleteRule({"ruleid": s1id})
+ s1id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:01", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L06":
+ action = "link s3 s5 down"
+ #net.configLinkStatus('s3', 's5', "down")
+ pusher.deleteRule({"ruleid": s3id})
+ s3id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:03", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L07":
+ action = "link s2 s6 down"
+ #net.configLinkStatus('s2', 's6', "down")
+ pusher.deleteRule({"ruleid": s2id})
+ s2id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:02", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L08":
+ action = "link s4 s6 down"
+ #net.configLinkStatus('s4', 's6', "down")
+ pusher.deleteRule({"ruleid": s4id})
+ s4id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:04", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L09":
+ action = "link s5 s6 down"
+ #net.configLinkStatus('s5', 's6', "down")
+ pusher.deleteRule({"ruleid": s7id})
+ s7id = json.loads(pusher.addRule({"switchid": "00:00:00:00:00:00:00:07", "action": "DENY"})[2])['rule-id']
+ if myOutput['edgeName'] == "L10":
+ print("L10")
+ #print(action)
+ #print("3")
+ except KeyError:
+ print(myOutput)
+ print("HA")
+ net.stop()
+
+ .. container::
+ :name: footer-text
+
+ 2.3.0-SNAPSHOT
+ Last updated 2020-04-03 16:04:24 IST
+
+
+.. |ONAP| image:: ../../../images/logos.png
+ :class: builtBy
+ :target: http://www.onap.org/
+
+.. |VPN SLA Architecture| image:: images/pcvs/vpnsla-arch.png
+
+
diff --git a/docs/apex/APEX-Policy-Examples.rst b/docs/apex/APEX-Policy-Examples.rst
new file mode 100644
index 00000000..579f9160
--- /dev/null
+++ b/docs/apex/APEX-Policy-Examples.rst
@@ -0,0 +1,83 @@
+.. This work is licensed under a Creative Commons Attribution 4.0 International License.
+.. http://creativecommons.org/licenses/by/4.0
+
+Policy Examples
+***************
+
+.. contents::
+ :depth: 3
+
+Sample APEX Policy in TOSCA format
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+ .. container:: paragraph
+
+ An example APEX policy in TOSCA format for the vCPE
+ use case can be found here:
+
+ .. container:: ulist
+
+ - `APEX TOSCA Policy
+ vCPE <https://github.com/onap/policy-models/blob/master/models-examples/src/main/resources/policies/vCPE.apex.policy.operational.input.tosca.json>`__
+
+My First Policy
+^^^^^^^^^^^^^^^
+
+ .. container:: paragraph
+
+ A good starting point is the ``My First Policy`` example. It
+ describes a sales problem, to which policy can be applied.
+ The example details the policy background, shows how to use
+ the REST Editor to create a policy, and provides details for
+ running the policies. The documentation can be found:
+
+ .. container:: ulist
+
+ - :ref:`My-First-Policy on the APEX site <apex-myFirstExample>`
+
+VPN SLA
+^^^^^^^
+
+ .. container:: paragraph
+
+ The domain Policy-controlled Video Streaming (PCVS) contains
+ a policy for controlling video streams with different
+ strategies. It also provides details for installing an
+ actual testbed with off-the-shelve software (Mininet,
+ Floodlight, Kafka, Zookeeper). The policy model here
+ demonstrates virtually all APEX features: local context and
+ policies controlling it, task selection logic and multiple
+ tasks in a single state, AVRO schemas for context, AVOR
+ schemas for events (trigger and local), and a CLI editor
+ specification of the policy. The documentation can be found:
+
+ .. container:: ulist
+
+ - :ref:`VPN SLA Policy on the APEX site <apex-PCVSExample>`
+
+Decision Maker
+^^^^^^^^^^^^^^
+
+ .. container:: paragraph
+
+ The domain Decision Maker shows a very simple policy for
+ decisions. Interesting here is that the it creates a Docker
+ image to run the policy and that it uses the APEX REST
+ applications to update the policy on the-fly. It also has
+ local context to remember past decisions, and shows how to
+ use that to no make the same decision twice in a row. The
+ documentation can be found:
+
+ .. container:: ulist
+
+ - `Decision Maker on APEX
+ site <https://ericsson.github.io/apex-docs/modules/examples/examples-decisionmaker/index.html>`__
+
+.. container::
+ :name: footer
+
+ .. container::
+ :name: footer-text
+
+ 2.3.0-SNAPSHOT
+ Last updated 2020-04-03 16:04:24 GMT \ No newline at end of file
diff --git a/docs/apex/APEX-Policy-Guide.rst b/docs/apex/APEX-Policy-Guide.rst
index c7e8ad5c..cb2388e0 100644
--- a/docs/apex/APEX-Policy-Guide.rst
+++ b/docs/apex/APEX-Policy-Guide.rst
@@ -2093,82 +2093,6 @@ Using Java in Scripting Logic
importClass(java.util.ArrayList);
var myList = new ArrayList();
-Policy Examples
-^^^^^^^^^^^^^^^
-
-Sample APEX Policy in TOSCA format
-----------------------------------
-
- .. container:: paragraph
-
- An example APEX policy in TOSCA format for the vCPE
- use case can be found here:
-
- .. container:: ulist
-
- - `APEX TOSCA Policy
- vCPE <https://github.com/onap/policy-models/blob/master/models-examples/src/main/resources/policies/vCPE.apex.policy.operational.input.tosca.json>`__
-
-My First Policy
----------------
-
- .. container:: paragraph
-
- A good starting point is the ``My First Policy`` example. It
- describes a sales problem, to which policy can be applied.
- The example details the policy background, shows how to use
- the REST Editor to create a policy, and provides details for
- running the policies. The documentation can be found:
-
- .. container:: ulist
-
- - `My-First-Policy on the APEX
- site <https://ericsson.github.io/apex-docs/modules/examples/examples-myfirstpolicy/MyFirstPolicyHowto.html>`__
-
- - `Stand-alone
- HTML <https://ericsson.github.io/apex-docs/docs-apex/html/HowTo-MyFirstPolicy.html>`__
-
- - `Stand-alone
- PDF <https://ericsson.github.io/apex-docs/docs-apex/pdf/HowTo-MyFirstPolicy.pdf>`__
-
-VPN SLA
--------
-
- .. container:: paragraph
-
- The domain Policy-controlled Video Streaming (PCVS) contains
- a policy for controlling video streams with different
- strategies. It also provides details for installing an
- actual testbed with off-the-shelve software (Mininet,
- Floodlight, Kafka, Zookeeper). The policy model here
- demonstrates virtually all APEX features: local context and
- policies controlling it, task selection logic and multiple
- tasks in a single state, AVRO schemas for context, AVOR
- schemas for events (trigger and local), and a CLI editor
- specification of the policy. The documentation can be found:
-
- .. container:: ulist
-
- - `VPN SLA Policy on the APEX
- site <https://ericsson.github.io/apex-docs/modules/examples/examples-pcvs/vpnsla/policy.html>`__
-
-Decision Maker
---------------
-
- .. container:: paragraph
-
- The domain Decision Maker shows a very simple policy for
- decisions. Interesting here is that the it creates a Docker
- image to run the policy and that it uses the APEX REST
- applications to update the policy on the-fly. It also has
- local context to remember past decisions, and shows how to
- use that to no make the same decision twice in a row. The
- documentation can be found:
-
- .. container:: ulist
-
- - `Decision Maker on APEX
- site <https://ericsson.github.io/apex-docs/modules/examples/examples-decisionmaker/index.html>`__
.. container::
:name: footer
diff --git a/docs/apex/events/1/EventIn_BoozeItem_084106GMT.json b/docs/apex/events/1/EventIn_BoozeItem_084106GMT.json
new file mode 100644
index 00000000..4c5af6c2
--- /dev/null
+++ b/docs/apex/events/1/EventIn_BoozeItem_084106GMT.json
@@ -0,0 +1,12 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483346466000,
+ "sale_ID": 99999992,
+ "amount": 1249,
+ "item_ID": 1012,
+ "quantity": 1,
+ "assistant_ID": 12,
+ "branch_ID": 2
+} \ No newline at end of file
diff --git a/docs/apex/events/1/EventIn_BoozeItem_201713GMT.json b/docs/apex/events/1/EventIn_BoozeItem_201713GMT.json
new file mode 100644
index 00000000..cc18e7dd
--- /dev/null
+++ b/docs/apex/events/1/EventIn_BoozeItem_201713GMT.json
@@ -0,0 +1,12 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1482265033000,
+ "sale_ID": 99999993,
+ "amount": 4799,
+ "item_ID": 1943,
+ "quantity": 2,
+ "assistant_ID": 9,
+ "branch_ID": 3
+} \ No newline at end of file
diff --git a/docs/apex/events/1/EventIn_NonBoozeItem_101309GMT.json b/docs/apex/events/1/EventIn_NonBoozeItem_101309GMT.json
new file mode 100644
index 00000000..1cdc4992
--- /dev/null
+++ b/docs/apex/events/1/EventIn_NonBoozeItem_101309GMT.json
@@ -0,0 +1,13 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483351989000,
+ "sale_ID": 99999991,
+ "amount": 299,
+ "item_ID": 5123,
+ "quantity": 1,
+ "assistant_ID": 23,
+ "branch_ID": 1,
+ "notes": "Special Offer!!"
+} \ No newline at end of file
diff --git a/docs/apex/events/1/EventOut_BoozeItem_084106GMT.json b/docs/apex/events/1/EventOut_BoozeItem_084106GMT.json
new file mode 100644
index 00000000..3625f908
--- /dev/null
+++ b/docs/apex/events/1/EventOut_BoozeItem_084106GMT.json
@@ -0,0 +1,17 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "source": "",
+ "target": "",
+ "amount": 1249,
+ "assistant_ID": 12,
+ "authorised": false,
+ "branch_ID": 2,
+ "item_ID": 1012,
+ "message": "Sale not authorised by policy task MorningBoozeCheck for time 08:41:06 GMT. Alcohol can not be sold between 00:00:00 GMT and 11:30:00 GMT",
+ "notes": null,
+ "quantity": 1,
+ "sale_ID": 99999992,
+ "time": 1483346466000
+} \ No newline at end of file
diff --git a/docs/apex/events/1/EventOut_BoozeItem_201713GMT.json b/docs/apex/events/1/EventOut_BoozeItem_201713GMT.json
new file mode 100644
index 00000000..2b760d5f
--- /dev/null
+++ b/docs/apex/events/1/EventOut_BoozeItem_201713GMT.json
@@ -0,0 +1,17 @@
+{
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "nameSpace": "com.hyperm",
+ "source": "",
+ "target": "",
+ "amount": 4799,
+ "assistant_ID": 9,
+ "authorised": true,
+ "branch_ID": 3,
+ "item_ID": 1943,
+ "message": "Sale authorised by policy task MorningBoozeCheck for time 20:17:13 GMT",
+ "notes": null,
+ "quantity": 2,
+ "sale_ID": 99999993,
+ "time": 1482265033000
+} \ No newline at end of file
diff --git a/docs/apex/events/1/EventOut_NonBoozeItem_101309GMT.json b/docs/apex/events/1/EventOut_NonBoozeItem_101309GMT.json
new file mode 100644
index 00000000..b90c6fa0
--- /dev/null
+++ b/docs/apex/events/1/EventOut_NonBoozeItem_101309GMT.json
@@ -0,0 +1,17 @@
+{
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "nameSpace": "com.hyperm",
+ "source": "",
+ "target": "",
+ "amount": 299,
+ "assistant_ID": 23,
+ "authorised": true,
+ "branch_ID": 1,
+ "item_ID": 5123,
+ "message": "Sale authorised by policy task MorningBoozeCheck for time 10:13:09 GMT",
+ "notes": "Special Offer!!",
+ "quantity": 1,
+ "sale_ID": 99999991,
+ "time": 1483351989000
+} \ No newline at end of file
diff --git a/docs/apex/events/1/EventsIn.json.txt b/docs/apex/events/1/EventsIn.json.txt
new file mode 100644
index 00000000..a9570f98
--- /dev/null
+++ b/docs/apex/events/1/EventsIn.json.txt
@@ -0,0 +1,37 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483346466000,
+ "sale_ID": 99999992,
+ "amount": 1249,
+ "item_ID": 1012,
+ "quantity": 1,
+ "assistant_ID": 12,
+ "branch_ID": 2
+}
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1482265033000,
+ "sale_ID": 99999993,
+ "amount": 4799,
+ "item_ID": 1943,
+ "quantity": 2,
+ "assistant_ID": 9,
+ "branch_ID": 3
+}
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483351989000,
+ "sale_ID": 99999991,
+ "amount": 299,
+ "item_ID": 5123,
+ "quantity": 1,
+ "assistant_ID": 23,
+ "branch_ID": 1,
+ "notes": "Special Offer!!"
+} \ No newline at end of file
diff --git a/docs/apex/events/1/EventsOut.json.txt b/docs/apex/events/1/EventsOut.json.txt
new file mode 100644
index 00000000..46fd887f
--- /dev/null
+++ b/docs/apex/events/1/EventsOut.json.txt
@@ -0,0 +1,51 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "source": "",
+ "target": "",
+ "amount": 1249,
+ "assistant_ID": 12,
+ "authorised": false,
+ "branch_ID": 2,
+ "item_ID": 1012,
+ "message": "Sale not authorised by policy task MorningBoozeCheck for time 08:41:06 GMT. Alcohol can not be sold between 00:00:00 GMT and 11:30:00 GMT",
+ "notes": null,
+ "quantity": 1,
+ "sale_ID": 99999992,
+ "time": 1483346466000
+}
+{
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "nameSpace": "com.hyperm",
+ "source": "",
+ "target": "",
+ "amount": 4799,
+ "assistant_ID": 9,
+ "authorised": true,
+ "branch_ID": 3,
+ "item_ID": 1943,
+ "message": "Sale authorised by policy task MorningBoozeCheck for time 20:17:13 GMT",
+ "notes": null,
+ "quantity": 2,
+ "sale_ID": 99999993,
+ "time": 1482265033000
+}
+{
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "nameSpace": "com.hyperm",
+ "source": "",
+ "target": "",
+ "amount": 299,
+ "assistant_ID": 23,
+ "authorised": true,
+ "branch_ID": 1,
+ "item_ID": 5123,
+ "message": "Sale authorised by policy task MorningBoozeCheck for time 10:13:09 GMT",
+ "notes": "Special Offer!!",
+ "quantity": 1,
+ "sale_ID": 99999991,
+ "time": 1483351989000
+} \ No newline at end of file
diff --git a/docs/apex/events/2/EventIn_BoozeItem_101433CET_thurs.json b/docs/apex/events/2/EventIn_BoozeItem_101433CET_thurs.json
new file mode 100644
index 00000000..952b4b18
--- /dev/null
+++ b/docs/apex/events/2/EventIn_BoozeItem_101433CET_thurs.json
@@ -0,0 +1,12 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1482398073000,
+ "sale_ID": 99999981,
+ "amount": 299,
+ "item_ID": 1047,
+ "quantity": 1,
+ "assistant_ID": 1212,
+ "branch_ID": 1002
+}
diff --git a/docs/apex/events/2/EventIn_BoozeItem_171937CET_sun.json b/docs/apex/events/2/EventIn_BoozeItem_171937CET_sun.json
new file mode 100644
index 00000000..7c8fb2bf
--- /dev/null
+++ b/docs/apex/events/2/EventIn_BoozeItem_171937CET_sun.json
@@ -0,0 +1,13 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1482077977000,
+ "sale_ID": 99999982,
+ "amount": 2199,
+ "item_ID": 1443,
+ "quantity": 12,
+ "assistant_ID": 94,
+ "branch_ID": 1003,
+ "notes": "Buy 3, get 1 free!!"
+}
diff --git a/docs/apex/events/2/EventIn_NonBoozeItem_111309CET_mon.json b/docs/apex/events/2/EventIn_NonBoozeItem_111309CET_mon.json
new file mode 100644
index 00000000..f8aa8760
--- /dev/null
+++ b/docs/apex/events/2/EventIn_NonBoozeItem_111309CET_mon.json
@@ -0,0 +1,13 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483351989000,
+ "sale_ID": 99999983,
+ "amount": 699,
+ "item_ID": 5321,
+ "quantity": 1,
+ "assistant_ID": 2323,
+ "branch_ID": 1001,
+ "notes": ""
+}
diff --git a/docs/apex/events/2/EventOut_BoozeItem_101433CET_thurs.json b/docs/apex/events/2/EventOut_BoozeItem_101433CET_thurs.json
new file mode 100644
index 00000000..d7c3a378
--- /dev/null
+++ b/docs/apex/events/2/EventOut_BoozeItem_101433CET_thurs.json
@@ -0,0 +1,17 @@
+{
+ "nameSpace" : "com.hyperm",
+ "name" : "SALE_AUTH",
+ "version" : "0.0.1",
+ "source" : "",
+ "target" : "",
+ "sale_ID" : 99999981,
+ "amount" : 299,
+ "assistant_ID" : 1212,
+ "notes" : null,
+ "quantity" : 1,
+ "branch_ID" : 1002,
+ "item_ID" : 1047,
+ "authorised" : false,
+ "time" : 1482398073000,
+ "message" : "Sale not authorised by policy task MorningBoozeCheckAlt1 for time 10:14:33 CET. Alcohol can not be sold between 00:00:00 CET and 13:00:00 CET or on Sunday"
+}
diff --git a/docs/apex/events/2/EventOut_BoozeItem_171937CET_sun.json b/docs/apex/events/2/EventOut_BoozeItem_171937CET_sun.json
new file mode 100644
index 00000000..cb838b83
--- /dev/null
+++ b/docs/apex/events/2/EventOut_BoozeItem_171937CET_sun.json
@@ -0,0 +1,17 @@
+{
+ "nameSpace" : "com.hyperm",
+ "name" : "SALE_AUTH",
+ "version" : "0.0.1",
+ "source" : "",
+ "target" : "",
+ "sale_ID" : 99999982,
+ "amount" : 2199,
+ "assistant_ID" : 94,
+ "notes" : "Buy 3, get 1 free!!",
+ "quantity" : 12,
+ "branch_ID" : 1003,
+ "item_ID" : 1443,
+ "authorised" : false,
+ "time" : 1482077977000,
+ "message" : "Sale not authorised by policy task MorningBoozeCheckAlt1 for time 17:19:37 CET. Alcohol can not be sold between 00:00:00 CET and 13:00:00 CET or on Sunday"
+}
diff --git a/docs/apex/events/2/EventOut_NonBoozeItem_111309CET_mon.json b/docs/apex/events/2/EventOut_NonBoozeItem_111309CET_mon.json
new file mode 100644
index 00000000..4b031e45
--- /dev/null
+++ b/docs/apex/events/2/EventOut_NonBoozeItem_111309CET_mon.json
@@ -0,0 +1,17 @@
+{
+ "nameSpace" : "com.hyperm",
+ "name" : "SALE_AUTH",
+ "version" : "0.0.1",
+ "source" : "",
+ "target" : "",
+ "sale_ID" : 99999983,
+ "amount" : 699,
+ "assistant_ID" : 2323,
+ "notes" : "",
+ "quantity" : 1,
+ "branch_ID" : 1001,
+ "item_ID" : 5321,
+ "authorised" : true,
+ "time" : 1483351989000,
+ "message" : "Sale authorised by policy task MorningBoozeCheckAlt1 for time 11:13:09 CET"
+}
diff --git a/docs/apex/events/2/EventsIn.json.txt b/docs/apex/events/2/EventsIn.json.txt
new file mode 100644
index 00000000..a38fcdbc
--- /dev/null
+++ b/docs/apex/events/2/EventsIn.json.txt
@@ -0,0 +1,75 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483346466000,
+ "sale_ID": 99999992,
+ "amount": 1249,
+ "item_ID": 1012,
+ "quantity": 1,
+ "assistant_ID": 12,
+ "branch_ID": 2
+}
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1482265033000,
+ "sale_ID": 99999993,
+ "amount": 4799,
+ "item_ID": 1943,
+ "quantity": 2,
+ "assistant_ID": 9,
+ "branch_ID": 3
+}
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483351989000,
+ "sale_ID": 99999991,
+ "amount": 299,
+ "item_ID": 5123,
+ "quantity": 1,
+ "assistant_ID": 23,
+ "branch_ID": 1,
+ "notes": "Special Offer!!"
+}
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1482398073000,
+ "sale_ID": 99999981,
+ "amount": 299,
+ "item_ID": 1047,
+ "quantity": 1,
+ "assistant_ID": 1212,
+ "branch_ID": 1002
+}
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1482077977000,
+ "sale_ID": 99999982,
+ "amount": 2199,
+ "item_ID": 1443,
+ "quantity": 12,
+ "assistant_ID": 94,
+ "branch_ID": 1003,
+ "notes": "Buy 3, get 1 free!!"
+}
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_INPUT",
+ "version": "0.0.1",
+ "time": 1483351989000,
+ "sale_ID": 99999983,
+ "amount": 699,
+ "item_ID": 5321,
+ "quantity": 1,
+ "assistant_ID": 2323,
+ "branch_ID": 1001,
+ "notes": ""
+}
diff --git a/docs/apex/events/2/EventsOut.json.txt b/docs/apex/events/2/EventsOut.json.txt
new file mode 100644
index 00000000..16cff198
--- /dev/null
+++ b/docs/apex/events/2/EventsOut.json.txt
@@ -0,0 +1,102 @@
+{
+ "nameSpace": "com.hyperm",
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "source": "",
+ "target": "",
+ "amount": 1249,
+ "assistant_ID": 12,
+ "authorised": false,
+ "branch_ID": 2,
+ "item_ID": 1012,
+ "message": "Sale not authorised by policy task MorningBoozeCheck for time 08:41:06 GMT. Alcohol can not be sold between 00:00:00 GMT and 11:30:00 GMT",
+ "notes": null,
+ "quantity": 1,
+ "sale_ID": 99999992,
+ "time": 1483346466000
+}
+{
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "nameSpace": "com.hyperm",
+ "source": "",
+ "target": "",
+ "amount": 4799,
+ "assistant_ID": 9,
+ "authorised": true,
+ "branch_ID": 3,
+ "item_ID": 1943,
+ "message": "Sale authorised by policy task MorningBoozeCheck for time 20:17:13 GMT",
+ "notes": null,
+ "quantity": 2,
+ "sale_ID": 99999993,
+ "time": 1482265033000
+}
+{
+ "name": "SALE_AUTH",
+ "version": "0.0.1",
+ "nameSpace": "com.hyperm",
+ "source": "",
+ "target": "",
+ "amount": 299,
+ "assistant_ID": 23,
+ "authorised": true,
+ "branch_ID": 1,
+ "item_ID": 5123,
+ "message": "Sale authorised by policy task MorningBoozeCheck for time 10:13:09 GMT",
+ "notes": "Special Offer!!",
+ "quantity": 1,
+ "sale_ID": 99999991,
+ "time": 1483351989000
+}
+{
+ "nameSpace" : "com.hyperm",
+ "name" : "SALE_AUTH",
+ "version" : "0.0.1",
+ "source" : "",
+ "target" : "",
+ "sale_ID" : 99999981,
+ "amount" : 299,
+ "assistant_ID" : 1212,
+ "notes" : null,
+ "quantity" : 1,
+ "branch_ID" : 1002,
+ "item_ID" : 1047,
+ "authorised" : false,
+ "time" : 1482398073000,
+ "message" : "Sale not authorised by policy task MorningBoozeCheckAlt1 for time 10:14:33 CET. Alcohol can not be sold between 00:00:00 CET and 13:00:00 CET or on Sunday"
+}
+{
+ "nameSpace" : "com.hyperm",
+ "name" : "SALE_AUTH",
+ "version" : "0.0.1",
+ "source" : "",
+ "target" : "",
+ "sale_ID" : 99999982,
+ "amount" : 2199,
+ "assistant_ID" : 94,
+ "notes" : "Buy 3, get 1 free!!",
+ "quantity" : 12,
+ "branch_ID" : 1003,
+ "item_ID" : 1443,
+ "authorised" : false,
+ "time" : 1482077977000,
+ "message" : "Sale not authorised by policy task MorningBoozeCheckAlt1 for time 17:19:37 CET. Alcohol can not be sold between 00:00:00 CET and 13:00:00 CET or on Sunday"
+}
+{
+ "nameSpace" : "com.hyperm",
+ "name" : "SALE_AUTH",
+ "version" : "0.0.1",
+ "source" : "",
+ "target" : "",
+ "sale_ID" : 99999983,
+ "amount" : 699,
+ "assistant_ID" : 2323,
+ "notes" : "",
+ "quantity" : 1,
+ "branch_ID" : 1001,
+ "item_ID" : 5321,
+ "authorised" : true,
+ "time" : 1483351989000,
+ "message" : "Sale authorised by policy task MorningBoozeCheckAlt1 for time 11:13:09 CET"
+}
diff --git a/docs/apex/images/pcvs/vpnsla-arch.png b/docs/apex/images/pcvs/vpnsla-arch.png
new file mode 100644
index 00000000..0aa39137
--- /dev/null
+++ b/docs/apex/images/pcvs/vpnsla-arch.png
Binary files differ