Initial DT workflow
Sample PPPoE-based workflow.
Track the subscriber PPPoE protocols state, authentication and IP address assignement are done via PPPoE protocols (PAP, CHAP, IPCP...).
Work with BNG app running on ONOS that generates events in the bng.pppoe Kafka topic.
Change-Id: Iae57395dcc90d027932c790c1c36d7b3e3f3e19b
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..b8f06bb
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,2 @@
+.tox
+venv-service
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0d57996
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+.idea
+.tox
+.coverage
+coverage.xml
+nose2-results.xml
+venv-service
+*.pyc
diff --git a/.gitreview b/.gitreview
new file mode 100644
index 0000000..e8758f0
--- /dev/null
+++ b/.gitreview
@@ -0,0 +1,5 @@
+[gerrit]
+host=gerrit.opencord.org
+port=29418
+project=dt-workflow-driver.git
+defaultremote=origin
diff --git a/Dockerfile.synchronizer b/Dockerfile.synchronizer
new file mode 100755
index 0000000..d50b2e1
--- /dev/null
+++ b/Dockerfile.synchronizer
@@ -0,0 +1,61 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+# docker build -t xosproject/dt-workflow-driver-synchronizer:candidate -f Dockerfile.synchronizer .
+
+# xosproject/dt-workflow-driver-synchronizer
+
+FROM xosproject/alpine-grpc-base:0.9.0
+
+# Install pip packages
+COPY requirements.txt /tmp/requirements.txt
+RUN pip install -r /tmp/requirements.txt \
+ && pip freeze > /var/xos/pip_freeze_dt_workflow_driver_service_`date -u +%Y%m%dT%H%M%S`
+
+# Copy files
+COPY xos/synchronizer /opt/xos/synchronizers/dt-workflow-driver
+COPY VERSION /opt/xos/synchronizers/dt-workflow-driver/
+
+WORKDIR "/opt/xos/synchronizers/dt-workflow-driver"
+
+# Label image
+ARG org_label_schema_schema_version=1.0
+ARG org_label_schema_name=dt-workflow-driver-synchronizer
+ARG org_label_schema_version=unknown
+ARG org_label_schema_vcs_url=unknown
+ARG org_label_schema_vcs_ref=unknown
+ARG org_label_schema_build_date=unknown
+ARG org_opencord_vcs_commit_date=unknown
+ARG org_opencord_component_chameleon_version=unknown
+ARG org_opencord_component_chameleon_vcs_url=unknown
+ARG org_opencord_component_chameleon_vcs_ref=unknown
+ARG org_opencord_component_xos_version=unknown
+ARG org_opencord_component_xos_vcs_url=unknown
+ARG org_opencord_component_xos_vcs_ref=unknown
+
+LABEL org.label-schema.schema-version=$org_label_schema_schema_version \
+ org.label-schema.name=$org_label_schema_name \
+ org.label-schema.version=$org_label_schema_version \
+ org.label-schema.vcs-url=$org_label_schema_vcs_url \
+ org.label-schema.vcs-ref=$org_label_schema_vcs_ref \
+ org.label-schema.build-date=$org_label_schema_build_date \
+ org.opencord.vcs-commit-date=$org_opencord_vcs_commit_date \
+ org.opencord.component.chameleon.version=$org_opencord_component_chameleon_version \
+ org.opencord.component.chameleon.vcs-url=$org_opencord_component_chameleon_vcs_url \
+ org.opencord.component.chameleon.vcs-ref=$org_opencord_component_chameleon_vcs_ref \
+ org.opencord.component.xos.version=$org_opencord_component_xos_version \
+ org.opencord.component.xos.vcs-url=$org_opencord_component_xos_vcs_url \
+ org.opencord.component.xos.vcs-ref=$org_opencord_component_xos_vcs_ref
+
+CMD ["/usr/bin/python", "/opt/xos/synchronizers/dt-workflow-driver/dt-workflow-driver-synchronizer.py"]
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100755
index 0000000..785250d
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2020 Open Networking Foundation
+
+ 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.
diff --git a/Makefile b/Makefile
new file mode 100755
index 0000000..4d2881f
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,84 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+# Configure shell
+SHELL = bash -e -o pipefail
+
+# Variables
+VERSION ?= $(shell cat ./VERSION)
+SERVICE_NAME ?= $(notdir $(abspath .))
+SYNCHRONIZER_NAME ?= dt-workflow-driver-synchronizer
+
+## Docker related
+DOCKER_REGISTRY ?=
+DOCKER_REPOSITORY ?=
+DOCKER_BUILD_ARGS ?=
+DOCKER_TAG ?= ${VERSION}
+DOCKER_IMAGENAME := ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}${SYNCHRONIZER_NAME}:${DOCKER_TAG}
+
+## Docker labels. Only set ref and commit date if committed
+DOCKER_LABEL_VCS_URL ?= $(shell git remote get-url $(shell git remote))
+DOCKER_LABEL_VCS_REF ?= $(shell git diff-index --quiet HEAD -- && git rev-parse HEAD || echo "unknown")
+DOCKER_LABEL_COMMIT_DATE ?= $(shell git diff-index --quiet HEAD -- && git show -s --format=%cd --date=iso-strict HEAD || echo "unknown" )
+DOCKER_LABEL_BUILD_DATE ?= $(shell date -u "+%Y-%m-%dT%H:%M:%SZ")
+
+## Migration related - paths are relative to the xos subdirectory within this repo
+XOS_DIR ?= "../../../xos"
+SERVICES_DIR ?= "../.."
+
+all: test
+
+docker-build:
+ docker build $(DOCKER_BUILD_ARGS) \
+ -t ${DOCKER_IMAGENAME} \
+ --build-arg org_label_schema_version="${VERSION}" \
+ --build-arg org_label_schema_vcs_url="${DOCKER_LABEL_VCS_URL}" \
+ --build-arg org_label_schema_vcs_ref="${DOCKER_LABEL_VCS_REF}" \
+ --build-arg org_label_schema_build_date="${DOCKER_LABEL_BUILD_DATE}" \
+ --build-arg org_opencord_vcs_commit_date="${DOCKER_LABEL_COMMIT_DATE}" \
+ -f Dockerfile.synchronizer .
+
+docker-push:
+ docker push ${DOCKER_IMAGENAME}
+
+test: test-unit test-migration test-xproto
+
+test-unit:
+ tox
+
+venv-service:
+ virtualenv $@;\
+ source ./$@/bin/activate ; set -u ;\
+ pip install -r requirements.txt xosmigrate~=3.2.6
+
+create-migration: venv-service
+ source ./venv-service/bin/activate; set -u;\
+ cd xos; xos-migrate --xos-dir ${XOS_DIR} --services-dir ${SERVICES_DIR} -s ${SERVICE_NAME}
+
+test-migration: venv-service
+ source ./venv-service/bin/activate; set -u;\
+ cd xos; xos-migrate --xos-dir ${XOS_DIR} --services-dir ${SERVICES_DIR} -s ${SERVICE_NAME} --check
+
+test-xproto: venv-service
+ source ./venv-service/bin/activate; set -u;\
+ xosgenx --lint --strict xos/synchronizer/models/dt-workflow-driver.xproto
+
+clean:
+ find . -name '*.pyc' | xargs rm -f
+ rm -rf \
+ .tox \
+ venv-service \
+ xos/.coverage \
+ xos/coverage.xml \
+ xos/nose2-results.xml
diff --git a/VERSION b/VERSION
new file mode 100755
index 0000000..05639a5
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+1.0.0-dev
diff --git a/docs/README.md b/docs/README.md
new file mode 100755
index 0000000..eb87acc
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,115 @@
+# DT Workflow Driver Service
+
+This service implements the ONU and Subscriber management logic for a sample PPPoE-based workflow.
+It's also a good start if you need to implement different logic to suit your use case.
+
+> NOTE: This service depends on models contained in the R-CORD and OLT Services, so make sure that the `rcord-synchronizer` and `volt-synchronzier` are running
+
+## Models
+
+This service is composed of the following models:
+
+- `DtWorkflowDriverServiceInstance`. This model holds various state associated with the state machine for validating a subscriber's ONU.
+ - `serial_number`. Serial number of ONU.
+ - NOTE: we might consider creating ONU always in APPROVED
+ - `authentication_state`. [`AWAITING` | `STARTED` | `REQUESTED` | `APPROVED` | `DENIED`]. Current authentication state.
+ - `of_dpid`. OLT Openflow ID.
+ - `uni_port_id`. ONU UNI Port ID.
+ - `admin_onu_state`. [`AWAITING` | `ENABLED` | `DISABLED`]. ONU administrative state.
+ - `status_message`. Status text of current state machine state.
+ - `pppoe_state`. [`AWAITING` | `INITIATED` | `CONNECTED` | `DISCONNECTED`]. Status of the subscriber PPPoE session.
+ - `pppoe_session_id`. Subscriber PPPoE session ID.
+ - `ipcp_state`. [`AWAITING` | `CONF_ACK` | `CONF_REQUEST`]. Status of the IPCP protocol for IP address assignment.
+ - `ip_address`. Subscriber ip address.
+ - `mac_address`. Subscriber mac address.
+ - `oper_onu_status`. [`AWAITING` | `ENABLED` | `DISABLED`]. ONU operational state.
+- `DtWorkflowDriverWhiteListEntry`. This model holds a whitelist authorizing an ONU with a specific serial number to be connected to a specific PON Port on a specific OLT.
+ - `owner`. Relation to the DtWorkflowDriverService that owns this whitelist entry.
+ - `serial_number`. Serial number of ONU.
+ - `pon_port_id`. PON port identifier.
+ - `device_id`. OLT device identifier.
+
+## Example Tosca - Create a whitelist entry
+
+```yaml
+tosca_definitions_version: tosca_simple_yaml_1_0
+imports:
+ - custom_types/dtworkflowdriverwhitelistentry.yaml
+ - custom_types/dtworkflowdriverservice.yaml
+description: Create an entry in the whitelist
+topology_template:
+ node_templates:
+
+ service#dtworkflow:
+ type: tosca.nodes.DtWorkflowDriverService
+ properties:
+ name: dt-workflow-driver
+ must-exist: true
+
+ whitelist:
+ type: tosca.nodes.DtWorkflowDriverWhiteListEntry
+ properties:
+ serial_number: BRCM22222222
+ pon_port_id: 536870912
+ device_id: of:000000000a5a0072
+ requirements:
+ - owner:
+ node: service#dtworkflow
+ relationship: tosca.relationships.BelongsToOne
+```
+
+## Integration with other Services
+
+This service integrates closely with the `R-CORD` and `vOLT` services, directly manipulating models (`RCORDSubscriber`, `ONUDevice`) in those services.
+
+## Synchronizer Workflows
+
+This synchronizer implements only event_steps and model_policies. It's job is to listen for events and execute a state machine associated with those events. Service Instances are created automatically when ONU events are received. As the state machine changes various states for authentication, etc., those changes will be propagated to the appropriate objects in the `R-CORD` and `vOLT` services.
+
+The state machine is described below.
+
+### Service Instances State Machine
+
+TODO: add the info with `bng.pppoe` events
+
+### Model Policy: DtWorkflowDriverServiceInstancePolicy
+
+This model policy is responsible for reacting to state changes that are caused by various event steps, implementing the state machine described above.
+
+### Event Step: ONUEventStep
+
+Listens on `onu.events` and updates the `onu_state` of `DtWorkflowDriverServiceInstance`. Also resets `authentication_state` when an ONU is disabled. Automatically creates `DtWorkflowDriverServiceInstance` as necessary.
+
+## Events format
+
+This events are generated by various applications running on top of ONOS and published on a Kafka bus.
+Here is the structure of the events and their topics.
+
+### onu.events
+
+```json
+{
+ "timestamp": "2018-09-11T01:00:49.506Z",
+ "status": "activated", // or disabled
+ "serialNumber": "ALPHe3d1cfde", // ONU serial number
+ "portNumber": "16", // uni port
+ "deviceId": "of:000000000a5a0072" // OLT OpenFlow Id
+}
+```
+
+### bng.pppoe
+This type of event regards all the possible events that the BNG ONOS app can generate for the PPPoE protocol.
+The different type of events are identified via `messageType` field.
+
+```json
+{
+ "timestamp": "2019-10-07T00:41:47.483Z",
+ "eventType" : "IPCP_CONF_ACK",
+ "deviceId" : "of:000000000a5a0072",
+ "portNumber" : "16",
+ "serialNumber": "ALPHe3d1cfde", // ONU serial number
+ "sessionId": "32", // PPPoE Session ID
+ "ipAddress": "10.255.255.100",
+ "macAddress": "00:11:22:33:44:55"
+}
+```
diff --git a/requirements.txt b/requirements.txt
new file mode 100755
index 0000000..d1f251f
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,3 @@
+xossynchronizer~=3.2.6
+xosapi~=3.2.6
+xoskafka~=3.2.6
diff --git a/samples/oss-service.yaml b/samples/oss-service.yaml
new file mode 100755
index 0000000..2ef8122
--- /dev/null
+++ b/samples/oss-service.yaml
@@ -0,0 +1,27 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+# curl -H "xos-username: admin@opencord.org" -H "xos-password: letmein" -X POST --data-binary @oss-service.yaml http://192.168.99.100:30007/run
+
+tosca_definitions_version: tosca_simple_yaml_1_0
+imports:
+ - custom_types/dtworkflowdriverservice.yaml
+description: Create an instance of the OSS Service and connect it to the vOLT Service
+topology_template:
+ node_templates:
+ service#oss:
+ type: tosca.nodes.DtWorkflowDriverService
+ properties:
+ name: dt-workflow-driver
+ kind: oss
diff --git a/samples/whitelist.yaml b/samples/whitelist.yaml
new file mode 100755
index 0000000..f4ff477
--- /dev/null
+++ b/samples/whitelist.yaml
@@ -0,0 +1,40 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+# curl -H "xos-username: admin@opencord.org" -H "xos-password: letmein" -X POST --data-binary @oss-service.yaml http://192.168.99.100:30007/run
+
+tosca_definitions_version: tosca_simple_yaml_1_0
+imports:
+ - custom_types/dtworkflowdriverwhitelistentry.yaml
+ - custom_types/dtworkflowdriverservice.yaml
+description: Create an entry in the whitelist
+topology_template:
+ node_templates:
+
+ service#dtworkflow:
+ type: tosca.nodes.DtWorkflowDriverService
+ properties:
+ name: dt-workflow-driver
+ must-exist: true
+
+ whitelist:
+ type: tosca.nodes.DtWorkflowDriverWhiteListEntry
+ properties:
+ serial_number: BRCM22222222
+ pon_port_id: 536870912
+ device_id: of:000000000a5a0072
+ requirements:
+ - owner:
+ node: service#dtworkflow
+ relationship: tosca.relationships.BelongsToOne
diff --git a/tox.ini b/tox.ini
new file mode 100755
index 0000000..c7011ac
--- /dev/null
+++ b/tox.ini
@@ -0,0 +1,46 @@
+; Copyright 2020-present Open Networking Foundation
+;
+; 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.
+
+[tox]
+envlist = py27
+; future; envlist = py27,py35,py36,py37
+skip_missing_interpreters = true
+skipsdist = True
+
+[testenv]
+deps =
+ -r requirements.txt
+ requests_mock
+ nose2
+; flake8
+
+changedir = xos
+commands =
+ nose2 -c ../tox.ini --verbose --junit-xml
+; future: flake8
+
+[flake8]
+max-line-length = 119
+
+[unittest]
+plugins = nose2.plugins.junitxml
+
+[junit-xml]
+path = nose2-results.xml
+
+[coverage]
+always-on = True
+coverage-report =
+ term
+ xml
diff --git a/xos/synchronizer/__init__.py b/xos/synchronizer/__init__.py
new file mode 100755
index 0000000..8612cfd
--- /dev/null
+++ b/xos/synchronizer/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
diff --git a/xos/synchronizer/config.yaml b/xos/synchronizer/config.yaml
new file mode 100755
index 0000000..0fa2210
--- /dev/null
+++ b/xos/synchronizer/config.yaml
@@ -0,0 +1,42 @@
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+
+name: dt-workflow-driver
+core_version: ">=2.2.1"
+required_models:
+ - DtWorkflowDriverService
+ - DtWorkflowDriverServiceInstance
+ - RCORDSubscriber
+ - ONUDevice
+model_policies_dir: "/opt/xos/synchronizers/dt-workflow-driver/model_policies"
+models_dir: "/opt/xos/synchronizers/dt-workflow-driver/models"
+event_steps_dir: "/opt/xos/synchronizers/dt-workflow-driver/event_steps"
+logging:
+ version: 1
+ handlers:
+ console:
+ class: logging.StreamHandler
+ file:
+ class: logging.handlers.RotatingFileHandler
+ filename: /var/log/xos.log
+ maxBytes: 10485760
+ backupCount: 5
+ loggers:
+ 'multistructlog':
+ handlers:
+ - console
+ - file
+ level: DEBUG
diff --git a/xos/synchronizer/dt-workflow-driver-synchronizer.py b/xos/synchronizer/dt-workflow-driver-synchronizer.py
new file mode 100755
index 0000000..a1d9173
--- /dev/null
+++ b/xos/synchronizer/dt-workflow-driver-synchronizer.py
@@ -0,0 +1,32 @@
+#!/usr/bin/env python
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+# This imports and runs ../../xos-observer.py
+
+import os
+from xossynchronizer import Synchronizer
+from xosconfig import Config
+
+
+base_config_file = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + '/config.yaml')
+mounted_config_file = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + '/mounted_config.yaml')
+
+if os.path.isfile(mounted_config_file):
+ Config.init(base_config_file, 'synchronizer-config-schema.yaml', mounted_config_file)
+else:
+ Config.init(base_config_file, 'synchronizer-config-schema.yaml')
+
+Synchronizer().run()
diff --git a/xos/synchronizer/event_steps/__init__.py b/xos/synchronizer/event_steps/__init__.py
new file mode 100755
index 0000000..8612cfd
--- /dev/null
+++ b/xos/synchronizer/event_steps/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
diff --git a/xos/synchronizer/event_steps/onu_event.py b/xos/synchronizer/event_steps/onu_event.py
new file mode 100755
index 0000000..9f342df
--- /dev/null
+++ b/xos/synchronizer/event_steps/onu_event.py
@@ -0,0 +1,50 @@
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+
+import json
+from xossynchronizer.event_steps.eventstep import EventStep
+from helpers import DtHelpers
+
+
+class ONUEventStep(EventStep):
+ topics = ["onu.events"]
+ technology = "kafka"
+
+ max_onu_retry = 50
+
+ def __init__(self, *args, **kwargs):
+ super(ONUEventStep, self).__init__(*args, **kwargs)
+
+ def process_event(self, event):
+ value = json.loads(event.value)
+ self.log.info("onu.events: received event", value=value)
+
+ dt_si = DtHelpers.find_or_create_dt_si(self.model_accessor, self.log, value)
+ if value["status"] == "activated":
+ self.log.info("onu.events: activated onu", value=value)
+ dt_si.no_sync = False
+ dt_si.uni_port_id = long(value["portNumber"])
+ dt_si.of_dpid = value["deviceId"]
+ dt_si.oper_onu_status = "ENABLED"
+ dt_si.save_changed_fields(always_update_timestamp=True)
+ elif value["status"] == "disabled":
+ self.log.info("onu.events: disabled onu, resetting the subscriber", value=value)
+ dt_si.oper_onu_status = "DISABLED"
+ dt_si.save_changed_fields(always_update_timestamp=True)
+ return
+ else:
+ self.log.warn("onu.events: Unknown status value: %s" % value["status"], value=value)
+ return
diff --git a/xos/synchronizer/event_steps/pppoe_event.py b/xos/synchronizer/event_steps/pppoe_event.py
new file mode 100755
index 0000000..33c24fe
--- /dev/null
+++ b/xos/synchronizer/event_steps/pppoe_event.py
@@ -0,0 +1,60 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+import json
+from xossynchronizer.event_steps.eventstep import EventStep
+from helpers import DtHelpers
+
+
+class SubscriberPppoeEventStep(EventStep):
+ topics = ["bng.pppoe"]
+ technology = "kafka"
+
+ to_pppoe = {
+ "SESSION_INIT": "INITIATED",
+ "SESSION_CONFIRMATION": "CONNECTED",
+ "SESSION_TERMINATION": "DISCONNECTED"
+ }
+ to_ipcp = {
+ "IPCP_CONF_ACK": "CONF_ACK",
+ "IPCP_CONF_REQ": "CONF_REQUEST"
+ }
+
+ to_auth = {
+ "AUTH_REQ": "STARTED",
+ "AUTH_SUCCESS": "APPROVED",
+ "AUTH_FAILED": "DENIED"
+ }
+
+ def __init__(self, *args, **kwargs):
+ super(SubscriberPppoeEventStep, self).__init__(*args, **kwargs)
+
+ def process_event(self, event):
+ value = json.loads(event.value)
+ self.log.info("bng.pppoe: Got event for subscriber", event_value=value)
+
+ si = DtHelpers.find_or_create_dt_si(self.model_accessor, self.log, value)
+ self.log.debug("bng.pppoe: Updating service instance", si=si)
+ # Map messageType to the different SI states
+ messageType = value["eventType"]
+ if messageType in self.to_pppoe.keys():
+ si.pppoe_state = self.to_pppoe[messageType]
+ if messageType in self.to_ipcp.keys():
+ si.ipcp_state = self.to_ipcp[messageType]
+ if messageType in self.to_auth.keys():
+ si.authentication_state = self.to_auth[messageType]
+ si.ip_address = value["ipAddress"]
+ si.mac_address = value["macAddress"]
+ si.pppoe_session_id = value["sessionId"]
+ si.save_changed_fields(always_update_timestamp=True)
diff --git a/xos/synchronizer/event_steps/test_onu_events.py b/xos/synchronizer/event_steps/test_onu_events.py
new file mode 100755
index 0000000..af44867
--- /dev/null
+++ b/xos/synchronizer/event_steps/test_onu_events.py
@@ -0,0 +1,190 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+import unittest
+from mock import patch, Mock
+import json
+
+import os
+import sys
+
+test_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
+
+
+class TestSyncOLTDevice(unittest.TestCase):
+
+ def setUp(self):
+
+ self.sys_path_save = sys.path
+
+ # Setting up the config module
+ from xosconfig import Config
+ config = os.path.join(test_path, "../test_config.yaml")
+ Config.clear()
+ Config.init(config, "synchronizer-config-schema.yaml")
+ # END Setting up the config module
+
+ from xossynchronizer.mock_modelaccessor_build import mock_modelaccessor_config
+ mock_modelaccessor_config(test_path, [("dt-workflow-driver", "dt-workflow-driver.xproto"),
+ ("olt-service", "volt.xproto"),
+ ("rcord", "rcord.xproto")])
+
+ import xossynchronizer.modelaccessor
+ import mock_modelaccessor
+ reload(mock_modelaccessor) # in case nose2 loaded it in a previous test
+ reload(xossynchronizer.modelaccessor) # in case nose2 loaded it in a previous test
+
+ from xossynchronizer.modelaccessor import model_accessor
+ from onu_event import ONUEventStep
+
+ # import all class names to globals
+ for (k, v) in model_accessor.all_model_classes.items():
+ globals()[k] = v
+
+ self.model_accessor = model_accessor
+ self.log = Mock()
+
+ self.event_step = ONUEventStep(model_accessor=self.model_accessor, log=self.log)
+
+ self.event = Mock()
+ self.event_dict = {
+ 'status': 'activated',
+ 'serialNumber': 'BRCM1234',
+ 'deviceId': 'of:109299321',
+ 'portNumber': '16'
+ }
+ self.event.value = json.dumps(self.event_dict)
+
+ self.pppoe = DtWorkflowDriverService(name="dt-workflow-driver")
+
+ def tearDown(self):
+ sys.path = self.sys_path_save
+
+ def test_create_instance(self):
+
+ with patch.object(DtWorkflowDriverServiceInstance.objects, "get_items") as dt_si_mock, \
+ patch.object(DtWorkflowDriverService.objects, "get_items") as service_mock, \
+ patch.object(DtWorkflowDriverServiceInstance, "save", autospec=True) as mock_save:
+
+ dt_si_mock.return_value = []
+ service_mock.return_value = [self.pppoe]
+
+ self.event_step.process_event(self.event)
+
+ dt_si = mock_save.call_args[0][0]
+
+ self.assertEqual(mock_save.call_count, 1)
+
+ self.assertEqual(dt_si.serial_number, self.event_dict['serialNumber'])
+ self.assertEqual(dt_si.of_dpid, self.event_dict['deviceId'])
+ self.assertEqual(dt_si.uni_port_id, long(self.event_dict['portNumber']))
+ # Receiving an ONU event doesn't change the admin_onu_state until the model policy runs
+ self.assertEqual(dt_si.admin_onu_state, "AWAITING")
+ self.assertEqual(dt_si.oper_onu_status, "ENABLED")
+
+ def test_reuse_instance(self):
+
+ si = DtWorkflowDriverServiceInstance(
+ serial_number=self.event_dict["serialNumber"],
+ of_dpid="foo",
+ uni_port_id="foo"
+ )
+
+ with patch.object(DtWorkflowDriverServiceInstance.objects, "get_items") as dt_si_mock, \
+ patch.object(DtWorkflowDriverServiceInstance, "save", autospec=True) as mock_save:
+
+ dt_si_mock.return_value = [si]
+
+ self.event_step.process_event(self.event)
+
+ dt_si = mock_save.call_args[0][0]
+
+ self.assertEqual(mock_save.call_count, 1)
+
+ self.assertEqual(dt_si.serial_number, self.event_dict['serialNumber'])
+ self.assertEqual(dt_si.of_dpid, self.event_dict['deviceId'])
+ self.assertEqual(dt_si.uni_port_id, long(self.event_dict['portNumber']))
+ # Receiving an ONU event doesn't change the admin_onu_state until the model policy runs
+ self.assertEqual(dt_si.admin_onu_state, "AWAITING")
+ self.assertEqual(dt_si.oper_onu_status, "ENABLED")
+
+ def test_disable_onu(self):
+ self.event_dict = {
+ 'status': 'disabled',
+ 'serialNumber': 'BRCM1234',
+ 'deviceId': 'of:109299321',
+ 'portNumber': '16',
+ }
+
+ si = DtWorkflowDriverServiceInstance(
+ serial_number=self.event_dict["serialNumber"],
+ of_dpid="foo",
+ uni_port_id="foo",
+ admin_onu_state="ENABLED",
+ oper_onu_status="ENABLED",
+ )
+
+ self.event.value = json.dumps(self.event_dict)
+
+ with patch.object(DtWorkflowDriverServiceInstance.objects, "get_items") as dt_si_mock, \
+ patch.object(DtWorkflowDriverServiceInstance, "save_changed_fields", autospec=True) as mock_save:
+ dt_si_mock.return_value = [si]
+
+ self.event_step.process_event(self.event)
+
+ dt_si = mock_save.call_args[0][0]
+
+ self.assertEqual(mock_save.call_count, 1)
+
+ # Receiving an ONU event doesn't change the admin_onu_state until the model policy runs
+ self.assertEqual(dt_si.admin_onu_state, 'ENABLED')
+ self.assertEqual(dt_si.oper_onu_status, 'DISABLED')
+
+ def test_enable_onu(self):
+ self.event_dict = {
+ 'status': 'activated',
+ 'serialNumber': 'BRCM1234',
+ 'deviceId': 'of:109299321',
+ 'portNumber': '16',
+ }
+
+ si = DtWorkflowDriverServiceInstance(
+ serial_number=self.event_dict["serialNumber"],
+ of_dpid="foo",
+ uni_port_id="foo",
+ admin_onu_state="DISABLED",
+ oper_onu_status="DISABLED",
+ )
+
+ self.event.value = json.dumps(self.event_dict)
+
+ with patch.object(DtWorkflowDriverServiceInstance.objects, "get_items") as dt_si_mock, \
+ patch.object(DtWorkflowDriverServiceInstance, "save_changed_fields", autospec=True) as mock_save:
+ dt_si_mock.return_value = [si]
+
+ self.event_step.process_event(self.event)
+
+ dt_si = mock_save.call_args[0][0]
+
+ self.assertEqual(mock_save.call_count, 1)
+
+ # Receiving an ONU event doesn't change the admin_onu_state until the model policy runs
+ self.assertEqual(dt_si.admin_onu_state, 'DISABLED')
+ self.assertEqual(dt_si.oper_onu_status, 'ENABLED')
+
+
+
+if __name__ == '__main__':
+ sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) # for import of helpers.py
+ unittest.main()
diff --git a/xos/synchronizer/event_steps/test_pppoe_event.py b/xos/synchronizer/event_steps/test_pppoe_event.py
new file mode 100755
index 0000000..4932dab
--- /dev/null
+++ b/xos/synchronizer/event_steps/test_pppoe_event.py
@@ -0,0 +1,110 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+import unittest
+from mock import patch, Mock
+import json
+
+import os
+import sys
+
+test_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
+
+
+class TestSubscriberAuthEvent(unittest.TestCase):
+
+ def setUp(self):
+
+ self.sys_path_save = sys.path
+
+ # Setting up the config module
+ from xosconfig import Config
+ config = os.path.join(test_path, "../test_config.yaml")
+ Config.clear()
+ Config.init(config, "synchronizer-config-schema.yaml")
+ from multistructlog import create_logger
+ log = create_logger(Config().get('logging'))
+ # END Setting up the config module
+
+ from xossynchronizer.mock_modelaccessor_build import mock_modelaccessor_config
+ mock_modelaccessor_config(test_path, [("dt-workflow-driver", "dt-workflow-driver.xproto"),
+ ("olt-service", "volt.xproto"),
+ ("rcord", "rcord.xproto")])
+
+ import xossynchronizer.modelaccessor
+ import mock_modelaccessor
+ reload(mock_modelaccessor) # in case nose2 loaded it in a previous test
+ reload(xossynchronizer.modelaccessor) # in case nose2 loaded it in a previous test
+
+ from xossynchronizer.modelaccessor import model_accessor
+ from pppoe_event import SubscriberPppoeEventStep
+
+ # import all class names to globals
+ for (k, v) in model_accessor.all_model_classes.items():
+ globals()[k] = v
+
+ self.model_accessor = model_accessor
+ self.log = log
+
+ self.event_step = SubscriberPppoeEventStep(model_accessor=self.model_accessor, log=self.log)
+
+ self.event = Mock()
+
+ self.volt = Mock()
+ self.volt.name = "vOLT"
+ self.volt.leaf_model = Mock()
+
+ # self.subscriber = RCORDSubscriber()
+ # self.subscriber.onu_device = "BRCM1234"
+ # self.subscriber.save = Mock()
+
+ self.mac_address = "00:AA:00:00:00:01"
+ self.ip_address = "192.168.3.5"
+ self.pppoe_session_id = "12"
+
+ self.si = DtWorkflowDriverServiceInstance()
+ self.si.serial_number = "BRCM1234"
+ self.si.save = Mock()
+
+ def tearDown(self):
+ sys.path = self.sys_path_save
+
+ def test_ipcp_subscriber(self):
+
+ self.event.value = json.dumps({
+ "deviceId": "of:0000000000000001",
+ "portNumber": "1",
+ "macAddress": self.mac_address,
+ "ipAddress": self.ip_address,
+ "sessionId": self.pppoe_session_id,
+ "eventType": "IPCP_CONF_ACK",
+ 'serialNumber': "BRCM1234",
+ })
+
+ with patch.object(DtWorkflowDriverServiceInstance.objects, "get_items") as si_mock:
+
+ si_mock.return_value = [self.si]
+
+ self.event_step.process_event(self.event)
+
+ self.si.save.assert_called()
+ self.assertEqual(self.si.ipcp_state, "CONF_ACK")
+ self.assertEqual(self.si.mac_address, self.mac_address)
+ self.assertEqual(self.si.ip_address, self.ip_address)
+ self.assertEqual(self.si.pppoe_session_id, self.pppoe_session_id)
+
+
+if __name__ == '__main__':
+ sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")) # for import of helpers.py
+ unittest.main()
diff --git a/xos/synchronizer/helpers.py b/xos/synchronizer/helpers.py
new file mode 100755
index 0000000..3cbedb8
--- /dev/null
+++ b/xos/synchronizer/helpers.py
@@ -0,0 +1,82 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+from xossynchronizer.steps.syncstep import DeferredException
+
+class DtHelpers():
+ @staticmethod
+ def validate_onu(model_accessor, log, dt_si):
+ """
+ This method validate an ONU against the whitelist and set the appropriate state.
+ It's expected that the deferred exception is managed in the caller method,
+ for example a model_policy or a sync_step.
+
+ :param dt_si: DtWorkflowDriverServiceInstance
+ :return: [boolean, string]
+ """
+
+ oss_service = dt_si.owner.leaf_model
+
+ # See if there is a matching entry in the whitelist.
+ matching_entries = model_accessor.DtWorkflowDriverWhiteListEntry.objects.filter(
+ owner_id=oss_service.id,
+ )
+ matching_entries = [e for e in matching_entries if e.serial_number.lower() == dt_si.serial_number.lower()]
+
+ if len(matching_entries) == 0:
+ log.warn("ONU not found in whitelist", object=str(dt_si), serial_number=dt_si.serial_number, **dt_si.tologdict())
+ return [False, "ONU not found in whitelist"]
+
+ whitelisted = matching_entries[0]
+ try:
+ onu = model_accessor.ONUDevice.objects.get(serial_number=dt_si.serial_number)
+ pon_port = onu.pon_port
+ except IndexError:
+ raise DeferredException("ONU device %s is not know to XOS yet" % dt_si.serial_number)
+
+ if onu.admin_state == "ADMIN_DISABLED":
+ return [False, "ONU has been manually disabled"]
+
+ if pon_port.port_no != whitelisted.pon_port_id or dt_si.of_dpid != whitelisted.device_id:
+ log.warn("ONU disable as location don't match",
+ object=str(dt_si),
+ serial_number=dt_si.serial_number,
+ pon_port=pon_port.port_no,
+ whitelisted_pon_port=whitelisted.pon_port_id,
+ device_id=dt_si.of_dpid,
+ whitelisted_device_id=whitelisted.device_id,
+ **dt_si.tologdict())
+ return [False, "ONU activated in wrong location"]
+
+ return [True, "ONU has been validated"]
+
+ @staticmethod
+ def find_or_create_dt_si(model_accessor, log, event):
+ try:
+ dt_si = model_accessor.DtWorkflowDriverServiceInstance.objects.get(
+ serial_number=event["serialNumber"]
+ )
+ log.debug("DtHelpers: Found existing DtWorkflowDriverServiceInstance", si=dt_si)
+ except IndexError:
+ # create an DtWorkflowDriverServiceInstance, the validation will be
+ # triggered in the corresponding sync step
+ dt_si = model_accessor.DtWorkflowDriverServiceInstance(
+ serial_number=event["serialNumber"],
+ of_dpid=event["deviceId"],
+ uni_port_id=long(event["portNumber"]),
+ # we assume there is only one DtWorkflowDriverService
+ owner=model_accessor.DtWorkflowDriverService.objects.first()
+ )
+ log.debug("DtHelpers: Created new DtWorkflowDriverServiceInstance", si=dt_si)
+ return dt_si
diff --git a/xos/synchronizer/migrations/0001_initial.py b/xos/synchronizer/migrations/0001_initial.py
new file mode 100644
index 0000000..a3c4808
--- /dev/null
+++ b/xos/synchronizer/migrations/0001_initial.py
@@ -0,0 +1,106 @@
+# Copyright 2017-present Open Networking Foundation
+#
+# 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.
+
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.27 on 2020-01-14 19:25
+from __future__ import unicode_literals
+
+import core.models.xosbase_header
+from django.db import migrations, models
+import django.db.models.deletion
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ('core', '0012_backupoperation_decl_uuid'),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='DtWorkflowDriverService',
+ fields=[
+ ('service_decl_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.Service_decl')),
+ ],
+ options={
+ 'verbose_name': 'DtWorkflowDriver Service',
+ },
+ bases=('core.service',),
+ ),
+ migrations.CreateModel(
+ name='DtWorkflowDriverServiceInstance',
+ fields=[
+ ('serviceinstance_decl_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='core.ServiceInstance_decl')),
+ ('serial_number', models.CharField(help_text=b'Serial number of ONU', max_length=256, unique=True)),
+ ('authentication_state', models.CharField(choices=[(b'AWAITING', b'Awaiting'), (b'STARTED', b'Started'), (b'APPROVED', b'Approved'), (b'DENIED', b'Denied')], default=b'AWAITING', help_text=b'Subscriber authentication state', max_length=50)),
+ ('of_dpid', models.CharField(help_text=b'OLT Openflow ID', max_length=256)),
+ ('uni_port_id', models.IntegerField(help_text=b'ONU UNI port ID')),
+ ('admin_onu_state', models.CharField(choices=[(b'AWAITING', b'Awaiting'), (b'ENABLED', b'Enabled'), (b'DISABLED', b'Disabled')], default=b'AWAITING', help_text=b'ONU administrative state', max_length=256)),
+ ('status_message', models.CharField(blank=True, default=b'', help_text=b'Status text of current state machine state', max_length=256, null=True)),
+ ('pppoe_state', models.CharField(choices=[(b'AWAITING', b'Awaiting'), (b'INITIATED', b'Initiated'), (b'CONNECTED', b'Connected'), (b'DISCONNECTED', b'Disconnected')], default=b'AWAITING', help_text=b'State of the subscriber PPPoE session', max_length=256)),
+ ('pppoe_session_id', models.CharField(blank=True, help_text=b'Subscriber PPPoE session ID', max_length=20, null=True)),
+ ('ipcp_state', models.CharField(choices=[(b'AWAITING', b'Awaiting'), (b'CONF_ACK', b'Ack'), (b'CONF_REQUEST', b'Requested')], default=b'AWAITING', help_text=b'State of the IPCP protocol for IP address assignment', max_length=256)),
+ ('ip_address', models.CharField(blank=True, help_text=b'Subscriber IP address, learned from IPCP', max_length=20, null=True)),
+ ('mac_address', models.CharField(blank=True, help_text=b'Subscriber MAC address', max_length=20, null=True)),
+ ('oper_onu_status', models.CharField(choices=[(b'AWAITING', b'Awaiting'), (b'ENABLED', b'Enabled'), (b'DISABLED', b'Disabled')], default=b'AWAITING', help_text=b'ONU operational state', max_length=256)),
+ ],
+ options={
+ 'verbose_name': 'DtWorkflowDriver Service Instance',
+ },
+ bases=('core.serviceinstance',),
+ ),
+ migrations.CreateModel(
+ name='DtWorkflowDriverWhiteListEntry',
+ fields=[
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('created', models.DateTimeField(auto_now_add=True, help_text=b'Time this model was created')),
+ ('updated', models.DateTimeField(default=django.utils.timezone.now, help_text=b'Time this model was changed by a non-synchronizer')),
+ ('enacted', models.DateTimeField(blank=True, default=None, help_text=b'When synced, set to the timestamp of the data that was synced', null=True)),
+ ('policed', models.DateTimeField(blank=True, default=None, help_text=b'When policed, set to the timestamp of the data that was policed', null=True)),
+ ('backend_register', models.CharField(blank=True, default=b'{}', max_length=1024, null=True)),
+ ('backend_need_delete', models.BooleanField(default=False)),
+ ('backend_need_reap', models.BooleanField(default=False)),
+ ('backend_status', models.CharField(default=b'Provisioning in progress', max_length=1024)),
+ ('backend_code', models.IntegerField(default=0)),
+ ('deleted', models.BooleanField(default=False)),
+ ('write_protect', models.BooleanField(default=False)),
+ ('lazy_blocked', models.BooleanField(default=False)),
+ ('no_sync', models.BooleanField(default=False)),
+ ('no_policy', models.BooleanField(default=False)),
+ ('policy_status', models.CharField(blank=True, default=b'Policy in process', max_length=1024, null=True)),
+ ('policy_code', models.IntegerField(blank=True, default=0, null=True)),
+ ('leaf_model_name', models.CharField(help_text=b'The most specialized model in this chain of inheritance, often defined by a service developer', max_length=1024)),
+ ('backend_need_delete_policy', models.BooleanField(default=False, help_text=b'True if delete model_policy must be run before object can be reaped')),
+ ('xos_managed', models.BooleanField(default=True, help_text=b'True if xos is responsible for creating/deleting this object')),
+ ('backend_handle', models.CharField(blank=True, help_text=b'Handle used by the backend to track this object', max_length=1024, null=True)),
+ ('changed_by_step', models.DateTimeField(blank=True, default=None, help_text=b'Time this model was changed by a sync step', null=True)),
+ ('changed_by_policy', models.DateTimeField(blank=True, default=None, help_text=b'Time this model was changed by a model policy', null=True)),
+ ('serial_number', models.CharField(help_text=b'ONU Serial Number', max_length=256)),
+ ('pon_port_id', models.IntegerField(help_text=b'PON Port on which this ONU is expected to show up')),
+ ('device_id', models.CharField(help_text=b'OLT Device (logical device id) on which this ONU is expected to show up', max_length=54)),
+ ('owner', models.ForeignKey(help_text=b'DtWorkflowDriverService that owns this white list entry', on_delete=django.db.models.deletion.CASCADE, related_name='whitelist_entries', to='dt-workflow-driver.DtWorkflowDriverService')),
+ ],
+ options={
+ 'verbose_name': 'ONU Whitelist',
+ },
+ bases=(models.Model, core.models.xosbase_header.PlModelMixIn),
+ ),
+ migrations.AlterUniqueTogether(
+ name='dtworkflowdriverwhitelistentry',
+ unique_together=set([('owner', 'serial_number')]),
+ ),
+ ]
diff --git a/xos/synchronizer/migrations/__init__.py b/xos/synchronizer/migrations/__init__.py
new file mode 100755
index 0000000..dd67de8
--- /dev/null
+++ b/xos/synchronizer/migrations/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
\ No newline at end of file
diff --git a/xos/synchronizer/model_policies/__init__.py b/xos/synchronizer/model_policies/__init__.py
new file mode 100755
index 0000000..8612cfd
--- /dev/null
+++ b/xos/synchronizer/model_policies/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
diff --git a/xos/synchronizer/model_policies/model_policy_dt_workflow_driver_serviceinstance.py b/xos/synchronizer/model_policies/model_policy_dt_workflow_driver_serviceinstance.py
new file mode 100755
index 0000000..f885459
--- /dev/null
+++ b/xos/synchronizer/model_policies/model_policy_dt_workflow_driver_serviceinstance.py
@@ -0,0 +1,208 @@
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+
+from helpers import DtHelpers
+from xossynchronizer.model_policies.policy import Policy
+
+import os
+import sys
+
+sync_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
+sys.path.append(sync_path)
+
+
+class DeferredException(Exception):
+ pass
+
+
+class DtWorkflowDriverServiceInstancePolicy(Policy):
+ model_name = "DtWorkflowDriverServiceInstance"
+
+ def handle_create(self, si):
+ self.logger.debug("MODEL_POLICY: handle_create for DtWorkflowDriverServiceInstance %s " % si.id)
+ self.handle_update(si)
+
+ def handle_update(self, si):
+ self.logger.debug("MODEL_POLICY: handle_update for DtWorkflowDriverServiceInstance %s " %
+ (si.id), onu_state=si.admin_onu_state, authentication_state=si.authentication_state)
+
+ # Changing ONU state can change auth state
+ # Changing auth state can change IPCP state
+ # So need to process in this order
+ self.process_onu_state(si)
+
+ self.validate_states(si)
+
+ self.process_pppoe_state(si)
+ self.process_ipcp_state(si)
+
+ # handling the subscriber status
+ # It's a combination of all the other states
+ subscriber = self.get_subscriber(si.serial_number)
+ if subscriber:
+ self.update_subscriber(subscriber, si)
+
+ if si.pppoe_state != "CONNECTED" or si.oper_onu_status != "ENABLED" or si.admin_onu_state != "ENABLED":
+ # Clean-up of SI
+ si.pppoe_session_id = ""
+ si.ip_address = ""
+ si.mac_address = ""
+
+ si.save_changed_fields()
+
+ # Check the whitelist to see if the ONU is valid. If it is, make sure that it's enabled.
+ def process_onu_state(self, si):
+ [valid, message] = DtHelpers.validate_onu(self.model_accessor, self.logger, si)
+ si.status_message = message
+ if valid:
+ si.admin_onu_state = "ENABLED"
+ self.update_onu(si.serial_number, "ENABLED")
+ else:
+ si.admin_onu_state = "DISABLED"
+ self.update_onu(si.serial_number, "DISABLED")
+
+ def process_pppoe_state(self, si):
+ pppoe_msgs = {
+ "AWAITING": " - Awaiting PPPoE connection",
+ "INITIATED": "",
+ "CONNECTED": "",
+ "DISCONNECTED": " - PPPoE session terminated",
+ }
+ si.status_message += pppoe_msgs[si.pppoe_state]
+
+ def process_ipcp_state(self, si):
+ ipcp_msgs = {
+ "AWAITING": "",
+ "CONF_ACK": " - IP address assigned",
+ "CONF_REQUEST": ""
+ }
+ si.status_message += ipcp_msgs[si.ipcp_state]
+
+ def validate_states(self, si):
+ if si.pppoe_state != "CONNECTED" or si.oper_onu_status != "ENABLED" or si.admin_onu_state != "ENABLED":
+ # Clean-up of SI
+ si.ipcp_state = "AWAITING"
+ si.authentication_state = "AWAITING"
+
+ def update_onu(self, serial_number, admin_state):
+ onu = [onu for onu in self.model_accessor.ONUDevice.objects.all() if onu.serial_number.lower()
+ == serial_number.lower()][0]
+ if onu.admin_state == "ADMIN_DISABLED":
+ self.logger.debug(
+ "MODEL_POLICY: ONUDevice [%s] has been manually disabled, not changing state to %s" %
+ (serial_number, admin_state))
+ return
+ if onu.admin_state == admin_state:
+ self.logger.debug(
+ "MODEL_POLICY: ONUDevice [%s] already has admin_state to %s" %
+ (serial_number, admin_state))
+ else:
+ self.logger.debug("MODEL_POLICY: setting ONUDevice [%s] admin_state to %s" % (serial_number, admin_state))
+ onu.admin_state = admin_state
+ onu.save_changed_fields(always_update_timestamp=True)
+
+ def get_subscriber(self, serial_number):
+ try:
+ return [s for s in self.model_accessor.RCORDSubscriber.objects.all() if s.onu_device.lower()
+ == serial_number.lower()][0]
+ except IndexError:
+ # If the subscriber doesn't exist we don't do anything
+ self.logger.debug(
+ "MODEL_POLICY: subscriber does not exists for this SI, doing nothing",
+ onu_device=serial_number)
+ return None
+
+ def update_subscriber_ip(self, subscriber, ip):
+ # TODO check if the subscriber has an IP and update it,
+ # or create a new one
+ try:
+ ip = self.model_accessor.RCORDIpAddress.objects.filter(
+ subscriber_id=subscriber.id,
+ ip=ip
+ )[0]
+ self.logger.debug("MODEL_POLICY: found existing RCORDIpAddress for subscriber",
+ onu_device=subscriber.onu_device, subscriber_status=subscriber.status, ip=ip)
+ ip.save_changed_fields()
+ except IndexError:
+ self.logger.debug(
+ "MODEL_POLICY: Creating new RCORDIpAddress for subscriber",
+ onu_device=subscriber.onu_device,
+ subscriber_status=subscriber.status,
+ ip=ip)
+ ip = self.model_accessor.RCORDIpAddress(
+ subscriber_id=subscriber.id,
+ ip=ip,
+ description="IPCP Assigned IP Address"
+ )
+ ip.save()
+
+ def delete_subscriber_ip(self, subscriber, ip):
+ try:
+ ip = self.model_accessor.RCORDIpAddress.objects.filter(
+ subscriber_id=subscriber.id,
+ ip=ip
+ )[0]
+ self.logger.debug(
+ "MODEL_POLICY: delete RCORDIpAddress for subscriber",
+ onu_device=subscriber.onu_device,
+ subscriber_status=subscriber.status,
+ ip=ip)
+ ip.delete()
+ except BaseException:
+ self.logger.warning("MODEL_POLICY: no RCORDIpAddress object found, cannot delete", ip=ip)
+
+ def update_subscriber(self, subscriber, si):
+ cur_status = subscriber.status
+ if si.oper_onu_status == "ENABLED" and si.admin_onu_state == "ENABLED":
+ subscriber.status = "enabled"
+ # FIXME: SEBA-670
+ # elif si.admin_onu_state == "DISABLED":
+ # subscriber.status = "disabled"
+
+ # FIXME: we need subscriber to be always in enabled state to be able
+ # to handle pppoe authentication via thew asg/pppoe relay, otherwise
+ # packets will be dropped at the OLT.
+ # We should either create an intermediate state to allow passing
+ # traffic from the OLT to the ASG, or we should relay PPPPoE
+ # control packets from the OLT.
+
+ if si.ipcp_state == "CONF_ACK" and si.ip_address:
+ self.update_subscriber_ip(subscriber, si.ip_address)
+ else:
+ self.delete_subscriber_ip(subscriber, si.ip_address)
+
+ if si.ipcp_state == "CONF_ACK" and si.mac_address:
+ subscriber.mac_address = si.mac_address
+ else:
+ subscriber.mac_address = ""
+
+ important_changes = cur_status != subscriber.status
+ if important_changes or si.pppoe_state == "DISCONNECTED" or si.ipcp_state == "CONF_ACK":
+ # NOTE SEBA-744
+ # Trigger sync_step only when the subscriber state change
+ self.logger.debug(
+ "MODEL_POLICY: updating subscriber",
+ onu_device=subscriber.onu_device,
+ authentication_state=si.authentication_state,
+ subscriber_status=subscriber.status,
+ always_update_timestamp=important_changes)
+ subscriber.save_changed_fields(always_update_timestamp=important_changes)
+ else:
+ self.logger.debug("MODEL_POLICY: subscriber status has not changed", onu_device=subscriber.onu_device,
+ authentication_state=si.authentication_state, subscriber_status=subscriber.status)
+
+ def handle_delete(self, si):
+ pass
diff --git a/xos/synchronizer/model_policies/model_policy_dt_workflow_driver_whitelistentry.py b/xos/synchronizer/model_policies/model_policy_dt_workflow_driver_whitelistentry.py
new file mode 100755
index 0000000..9bd456c
--- /dev/null
+++ b/xos/synchronizer/model_policies/model_policy_dt_workflow_driver_whitelistentry.py
@@ -0,0 +1,82 @@
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+
+from helpers import DtHelpers
+from xossynchronizer.model_policies.policy import Policy
+import os
+import sys
+
+sync_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
+sys.path.append(sync_path)
+
+
+class DtWorkflowDriverWhiteListEntryPolicy(Policy):
+ model_name = "DtWorkflowDriverWhiteListEntry"
+
+ def handle_create(self, whitelist):
+ self.handle_update(whitelist)
+
+ # Update the SI if the onu_state has changed.
+ # The SI model policy will take care of updating other state.
+ def validate_onu_state(self, si):
+ [valid, message] = DtHelpers.validate_onu(self.model_accessor, self.logger, si)
+ if valid:
+ si.admin_onu_state = "ENABLED"
+ else:
+ si.admin_onu_state = "DISABLED"
+
+ self.logger.debug(
+ "MODEL_POLICY: activating DtWorkflowDriverServiceInstance because of change in the whitelist",
+ si=si,
+ onu_state=si.admin_onu_state,
+ authentication_state=si.authentication_state)
+ si.save_changed_fields(always_update_timestamp=True)
+
+ def handle_update(self, whitelist):
+ self.logger.debug("MODEL_POLICY: handle_update for DtWorkflowDriverWhiteListEntry", whitelist=whitelist)
+
+ sis = self.model_accessor.DtWorkflowDriverServiceInstance.objects.all()
+
+ for si in sis:
+
+ if si.serial_number.lower() != whitelist.serial_number.lower():
+ # NOTE we don't care about this SI as it has a different serial number
+ continue
+
+ self.validate_onu_state(si)
+
+ whitelist.backend_need_delete_policy = True
+ whitelist.save_changed_fields()
+
+ def handle_delete(self, whitelist):
+ self.logger.debug(
+ "MODEL_POLICY: handle_delete for DtWorkflowDriverWhiteListEntry",
+ serial_number=whitelist.serial_number,
+ pon_port=whitelist.pon_port_id,
+ device=whitelist.device_id)
+
+ # BUG: Sometimes the delete policy is not called, because the reaper deletes
+
+ assert(whitelist.owner)
+
+ sis = self.model_accessor.DtWorkflowDriverServiceInstance.objects.all()
+ sis = [si for si in sis if si.serial_number.lower() == whitelist.serial_number.lower()]
+
+ for si in sis:
+ self.validate_onu_state(si)
+
+ whitelist.backend_need_reap = True
+ whitelist.save_changed_fields()
diff --git a/xos/synchronizer/model_policies/test_model_policy_dt_workflow_driver_serviceinstance.py b/xos/synchronizer/model_policies/test_model_policy_dt_workflow_driver_serviceinstance.py
new file mode 100755
index 0000000..e520036
--- /dev/null
+++ b/xos/synchronizer/model_policies/test_model_policy_dt_workflow_driver_serviceinstance.py
@@ -0,0 +1,357 @@
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+
+import unittest
+from mock import patch
+
+import os
+import sys
+
+test_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
+
+
+class TestModelPolicyDtWorkflowDriverServiceInstance(unittest.TestCase):
+ def setUp(self):
+
+ self.sys_path_save = sys.path
+
+ config = os.path.join(test_path, "../test_config.yaml")
+ from xosconfig import Config
+ Config.clear()
+ Config.init(config, 'synchronizer-config-schema.yaml')
+
+ from xossynchronizer.mock_modelaccessor_build import mock_modelaccessor_config
+ mock_modelaccessor_config(test_path, [("dt-workflow-driver", "dt-workflow-driver.xproto"),
+ ("olt-service", "volt.xproto"),
+ ("rcord", "rcord.xproto")])
+
+ import xossynchronizer.modelaccessor
+ import mock_modelaccessor
+ reload(mock_modelaccessor) # in case nose2 loaded it in a previous test
+ reload(xossynchronizer.modelaccessor) # in case nose2 loaded it in a previous test
+
+ from xossynchronizer.modelaccessor import model_accessor
+ from model_policy_dt_workflow_driver_serviceinstance import DtWorkflowDriverServiceInstancePolicy, DtHelpers
+ self.DtHelpers = DtHelpers
+
+ # import all class names to globals
+ for (k, v) in model_accessor.all_model_classes.items():
+ globals()[k] = v
+
+ # Some of the functions we call have side-effects. For example, creating a VSGServiceInstance may lead to
+ # creation of tags. Ideally, this wouldn't happen, but it does. So make sure we reset the world.
+ model_accessor.reset_all_object_stores()
+
+ self.policy = DtWorkflowDriverServiceInstancePolicy(model_accessor=model_accessor)
+ self.si = DtWorkflowDriverServiceInstance()
+ self.si.owner = DtWorkflowDriverService()
+ self.si.serial_number = "BRCM1234"
+
+ def tearDown(self):
+ sys.path = self.sys_path_save
+
+ def test_update_onu(self):
+
+ onu = ONUDevice(
+ serial_number="BRCM1234",
+ admin_state="ENABLED"
+ )
+ with patch.object(ONUDevice.objects, "get_items") as get_onu, \
+ patch.object(onu, "save") as onu_save:
+ get_onu.return_value = [onu]
+
+ self.policy.update_onu("brcm1234", "ENABLED")
+ onu_save.assert_not_called()
+
+ self.policy.update_onu("brcm1234", "DISABLED")
+ self.assertEqual(onu.admin_state, "DISABLED")
+ onu_save.assert_called_with(
+ always_update_timestamp=True, update_fields=[
+ 'admin_state', 'serial_number', 'updated'])
+
+ def test_enable_onu(self):
+ with patch.object(self.DtHelpers, "validate_onu") as validate_onu, \
+ patch.object(self.policy, "update_onu") as update_onu:
+ validate_onu.return_value = [True, "valid onu"]
+
+ self.policy.process_onu_state(self.si)
+
+ update_onu.assert_called_once()
+ update_onu.assert_called_with("BRCM1234", "ENABLED")
+
+ self.assertIn("valid onu", self.si.status_message)
+
+ def test_disable_onu(self):
+ with patch.object(self.DtHelpers, "validate_onu") as validate_onu, \
+ patch.object(self.policy, "update_onu") as update_onu:
+ validate_onu.return_value = [False, "invalid onu"]
+
+ self.policy.process_onu_state(self.si)
+
+ update_onu.assert_called_once()
+ update_onu.assert_called_with("BRCM1234", "DISABLED")
+
+ self.assertIn("invalid onu", self.si.status_message)
+
+ def test_handle_update_validate_onu(self):
+ """
+ Testing that handle_update calls validate_onu with the correct parameters
+ when necessary
+ """
+ with patch.object(self.policy, "process_onu_state") as process_onu_state, \
+ patch.object(self.policy, "update_onu") as update_onu, \
+ patch.object(self.policy, "get_subscriber") as get_subscriber:
+ update_onu.return_value = None
+ get_subscriber.return_value = None
+
+ self.si.admin_onu_state = "AWAITING"
+ self.si.oper_onu_status = "AWAITING"
+ self.policy.handle_update(self.si)
+ process_onu_state.assert_called_with(self.si)
+
+ self.si.admin_onu_state = "ENABLED"
+ self.si.oper_onu_status = "ENABLED"
+ self.policy.handle_update(self.si)
+ process_onu_state.assert_called_with(self.si)
+
+ self.si.admin_onu_state = "DISABLED"
+ self.si.oper_onu_status = "DISABLED"
+ self.policy.handle_update(self.si)
+ process_onu_state.assert_called_with(self.si)
+
+ def test_get_subscriber(self):
+
+ sub = RCORDSubscriber(
+ onu_device="BRCM1234"
+ )
+
+ with patch.object(RCORDSubscriber.objects, "get_items") as get_subscribers:
+ get_subscribers.return_value = [sub]
+
+ res = self.policy.get_subscriber("BRCM1234")
+ self.assertEqual(res, sub)
+
+ res = self.policy.get_subscriber("brcm1234")
+ self.assertEqual(res, sub)
+
+ res = self.policy.get_subscriber("foo")
+ self.assertEqual(res, None)
+
+ def test_update_subscriber_with_onu_event(self):
+
+ sub = RCORDSubscriber(
+ onu_device="BRCM1234",
+ status="pre-provisioned"
+ )
+
+ self.assertEqual(sub.status, "pre-provisioned")
+
+ with patch.object(sub, "save") as sub_save:
+ self.si.oper_onu_status = "AWAITING"
+ self.policy.update_subscriber(sub, self.si)
+ self.assertEqual(sub.status, "pre-provisioned")
+ sub_save.assert_not_called()
+ sub_save.reset_mock()
+
+ self.si.oper_onu_status = "ENABLED"
+ self.si.admin_onu_state = "ENABLED"
+ self.policy.update_subscriber(sub, self.si)
+ self.assertEqual(sub.status, "enabled")
+ sub_save.assert_called()
+ sub_save.reset_mock()
+
+ self.si.oper_onu_status = "DISABLED"
+ self.policy.update_subscriber(sub, self.si)
+ # FIXME: the result should be disabled, but for now we force it to remain enabled
+ self.assertEqual(sub.status, "enabled")
+ # sub_save.assert_called()
+ sub_save.reset_mock()
+
+ def test_not_update_subscriber_with_auth_events(self):
+
+ sub = RCORDSubscriber(
+ onu_device="BRCM1234"
+ )
+
+ self.si.status_message = "some content"
+ self.si.oper_onu_status = "ENABLED"
+
+ with patch.object(sub, "save") as sub_save:
+ self.si.authentication_state = "AWAITING"
+ self.policy.update_subscriber(sub, self.si)
+ self.assertEqual(sub.status, "enabled")
+ sub_save.assert_not_called()
+ sub_save.reset_mock()
+ sub.status = "enabled"
+
+ self.si.authentication_state = "REQUESTED"
+ self.policy.update_subscriber(sub, self.si)
+ self.assertEqual(sub.status, "enabled")
+ sub_save.assert_not_called()
+ sub_save.reset_mock()
+ sub.status = "enabled"
+
+ self.si.authentication_state = "STARTED"
+ self.policy.update_subscriber(sub, self.si)
+ self.assertEqual(sub.status, "enabled")
+ sub_save.assert_not_called()
+ sub_save.reset_mock()
+ sub.status = "enabled"
+
+ self.si.authentication_state = "APPROVED"
+ self.policy.update_subscriber(sub, self.si)
+ self.assertEqual(sub.status, "enabled")
+ sub_save.assert_not_called()
+ sub_save.reset_mock()
+ sub.status = "enabled"
+
+ self.si.authentication_state = "DENIED"
+ self.policy.update_subscriber(sub, self.si)
+ self.assertEqual(sub.status, "enabled")
+ sub_save.assert_not_called()
+ sub_save.reset_mock()
+ sub.status = "enabled"
+
+ def test_update_subscriber_not(self):
+ sub = RCORDSubscriber(
+ onu_device="BRCM1234"
+ )
+
+ self.si.oper_onu_status = "ENABLED"
+ sub.status = "enabled"
+
+ with patch.object(sub, "save") as sub_save:
+ self.si.authentication_state = "AWAITING"
+ self.policy.update_subscriber(sub, self.si)
+ sub_save.assert_not_called()
+
+ self.si.authentication_state = "REQUESTED"
+ self.policy.update_subscriber(sub, self.si)
+ sub_save.assert_not_called()
+
+ self.si.authentication_state = "STARTED"
+ self.policy.update_subscriber(sub, self.si)
+ sub_save.assert_not_called()
+
+ self.si.authentication_state = "APPROVED"
+ self.policy.update_subscriber(sub, self.si)
+ sub_save.assert_not_called()
+
+ self.si.authentication_state = "DENIED"
+ self.policy.update_subscriber(sub, self.si)
+ sub_save.assert_not_called()
+
+ def test_update_subscriber_ipcp_with_exiting_ip(self):
+ sub = RCORDSubscriber(
+ id=10,
+ onu_device="BRCM1234"
+ )
+
+ ip = RCORDIpAddress(
+ subscriber_id=sub.id,
+ ip='10.11.2.23'
+ )
+
+ self.si.pppoe_state = "CONNECTED"
+ self.si.authentication_state = "APPROVED"
+ self.si.oper_onu_status = "ENABLED"
+ self.si.ipcp_state = "CONF_ACK"
+ self.si.ip_address = "10.11.2.23"
+ self.si.mac_address = "4321"
+
+ with patch.object(sub, "save") as sub_save, \
+ patch.object(RCORDIpAddress.objects, "get_items") as get_ips, \
+ patch.object(ip, "save_changed_fields") as ip_mock:
+
+ get_ips.return_value = [ip]
+ ip_mock.return_value = []
+
+ self.policy.update_subscriber(sub, self.si)
+ sub_save.assert_called_with(always_update_timestamp=False,
+ update_fields=['id', 'mac_address', 'onu_device'])
+ self.assertEqual(sub.mac_address, self.si.mac_address)
+
+ ip_mock.assert_called_with()
+
+ def test_update_subscriber_ipcp_with_new_ip(self):
+ sub = RCORDSubscriber(
+ id=10,
+ onu_device="BRCM1234"
+ )
+
+ self.si.pppoe_state = "CONNECTED"
+ self.si.oper_onu_status = "ENABLED"
+ self.si.authentication_state = "APPROVED"
+ self.si.ipcp_state = "CONF_ACK"
+ self.si.ip_address = "10.11.2.23"
+ self.si.mac_address = "4321"
+
+ with patch.object(sub, "save") as sub_save, \
+ patch.object(RCORDIpAddress, "save", autospec=True) as ip_mock:
+
+ ip_mock.return_value = []
+
+ self.policy.update_subscriber(sub, self.si)
+ sub_save.assert_called_with(always_update_timestamp=False,
+ update_fields=['id', 'mac_address', 'onu_device'])
+ self.assertEqual(sub.mac_address, self.si.mac_address)
+
+ saved_ip = ip_mock.call_args[0][0]
+ self.assertEqual(saved_ip.ip, self.si.ip_address)
+ self.assertEqual(saved_ip.subscriber_id, sub.id)
+ self.assertEqual(saved_ip.description, "IPCP Assigned IP Address")
+
+ def test_handle_update_subscriber(self):
+ self.si.admin_onu_state = "DISABLED"
+
+ sub = RCORDSubscriber(
+ onu_device="BRCM1234"
+ )
+
+ with patch.object(self.policy, "get_subscriber") as get_subscriber, \
+ patch.object(self.policy, "update_onu") as update_onu, \
+ patch.object(self.policy, "update_subscriber") as update_subscriber:
+
+ get_subscriber.return_value = None
+ self.policy.handle_update(self.si)
+ update_onu.assert_called_with(sub.onu_device, "DISABLED")
+ self.assertEqual(update_subscriber.call_count, 0)
+
+ get_subscriber.return_value = sub
+ self.policy.handle_update(self.si)
+ update_subscriber.assert_called_with(sub, self.si)
+
+ def test_process_auth_state(self):
+ # testing change in admin_onu_state
+ self.si.admin_onu_state = "DISABLED"
+ self.si.oper_onu_status = "ENABLED"
+ self.si.authentication_state, "APPROVED"
+
+ self.policy.validate_states(self.si)
+ self.assertEqual(self.si.authentication_state, "AWAITING")
+
+ # testing change in oper_onu_status
+ self.si.admin_onu_state = "ENABLED"
+ self.si.oper_onu_status = "DISABLED"
+ self.si.authentication_state, "APPROVED"
+
+ self.policy.validate_states(self.si)
+ self.assertEqual(self.si.authentication_state, "AWAITING")
+
+
+if __name__ == '__main__':
+ sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
+ unittest.main()
diff --git a/xos/synchronizer/model_policies/test_model_policy_dt_workflow_driver_whitelistentry.py b/xos/synchronizer/model_policies/test_model_policy_dt_workflow_driver_whitelistentry.py
new file mode 100755
index 0000000..193845f
--- /dev/null
+++ b/xos/synchronizer/model_policies/test_model_policy_dt_workflow_driver_whitelistentry.py
@@ -0,0 +1,129 @@
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+
+import unittest
+from mock import patch
+
+import os
+import sys
+
+test_path = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
+
+
+class TestModelPolicyDtWorkflowDriverWhiteListEntry(unittest.TestCase):
+ def setUp(self):
+ self.sys_path_save = sys.path
+
+ config = os.path.join(test_path, "../test_config.yaml")
+ from xosconfig import Config
+ Config.clear()
+ Config.init(config, 'synchronizer-config-schema.yaml')
+
+ from xossynchronizer.mock_modelaccessor_build import mock_modelaccessor_config
+ mock_modelaccessor_config(test_path, [("dt-workflow-driver", "dt-workflow-driver.xproto"),
+ ("olt-service", "volt.xproto"),
+ ("rcord", "rcord.xproto")])
+
+ import xossynchronizer.modelaccessor
+ import mock_modelaccessor
+ reload(mock_modelaccessor) # in case nose2 loaded it in a previous test
+ reload(xossynchronizer.modelaccessor) # in case nose2 loaded it in a previous test
+
+ from xossynchronizer.modelaccessor import model_accessor
+ from model_policy_dt_workflow_driver_whitelistentry import DtWorkflowDriverWhiteListEntryPolicy, DtHelpers
+ self.DtHelpers = DtHelpers
+
+ from mock_modelaccessor import MockObjectList
+ self.MockObjectList = MockObjectList
+
+ # import all class names to globals
+ for (k, v) in model_accessor.all_model_classes.items():
+ globals()[k] = v
+
+ # Some of the functions we call have side-effects. For example, creating a VSGServiceInstance may lead to
+ # creation of tags. Ideally, this wouldn't happen, but it does. So make sure we reset the world.
+ model_accessor.reset_all_object_stores()
+
+ self.policy = DtWorkflowDriverWhiteListEntryPolicy(model_accessor=model_accessor)
+
+ self.service = DtWorkflowDriverService()
+
+ def tearDown(self):
+ sys.path = self.sys_path_save
+ self.service = None
+
+ def test_enable_onu(self):
+ si = DtWorkflowDriverServiceInstance(serial_number="BRCM333", owner_id=self.service.id, valid="invalid")
+ with patch.object(self.DtHelpers, "validate_onu") as validate_onu, \
+ patch.object(si, "save") as save_si:
+ validate_onu.return_value = [True, "valid onu"]
+
+ self.policy.validate_onu_state(si)
+
+ save_si.assert_called_once()
+ save_si.assert_called_with(
+ always_update_timestamp=True, update_fields=[
+ 'admin_onu_state', 'serial_number', 'updated'])
+
+ def test_disable_onu(self):
+ si = DtWorkflowDriverServiceInstance(serial_number="BRCM333", owner_id=self.service.id, valid="invalid")
+ with patch.object(self.DtHelpers, "validate_onu") as validate_onu, \
+ patch.object(si, "save") as save_si:
+ validate_onu.return_value = [False, "invalid onu"]
+
+ self.policy.validate_onu_state(si)
+
+ save_si.assert_called_once()
+ save_si.assert_called_with(
+ always_update_timestamp=True, update_fields=[
+ 'admin_onu_state', 'serial_number', 'updated'])
+
+ def test_whitelist_update(self):
+ si = DtWorkflowDriverServiceInstance(serial_number="BRCM333", owner_id=self.service.id)
+ wle = DtWorkflowDriverWhiteListEntry(serial_number="brcm333", owner_id=self.service.id, owner=self.service)
+ with patch.object(DtWorkflowDriverServiceInstance.objects, "get_items") as oss_si_items, \
+ patch.object(self.policy, "validate_onu_state") as validate_onu_state, \
+ patch.object(wle, "save") as wle_save:
+ oss_si_items.return_value = [si]
+
+ self.policy.handle_update(wle)
+
+ validate_onu_state.assert_called_with(si)
+ self.assertTrue(wle.backend_need_delete_policy)
+ wle_save.assert_called_with(
+ always_update_timestamp=False, update_fields=[
+ 'backend_need_delete_policy', 'owner', 'serial_number'])
+
+ def test_whitelist_delete(self):
+ si = DtWorkflowDriverServiceInstance(serial_number="BRCM333", owner_id=self.service.id)
+ wle = DtWorkflowDriverWhiteListEntry(serial_number="brcm333", owner_id=self.service.id, owner=self.service)
+ with patch.object(DtWorkflowDriverServiceInstance.objects, "get_items") as oss_si_items, \
+ patch.object(self.policy, "validate_onu_state") as validate_onu_state, \
+ patch.object(wle, "save") as wle_save:
+ oss_si_items.return_value = [si]
+
+ self.policy.handle_delete(wle)
+
+ validate_onu_state.assert_called_with(si)
+ self.assertTrue(wle.backend_need_reap)
+ wle_save.assert_called_with(
+ always_update_timestamp=False, update_fields=[
+ 'backend_need_reap', 'owner', 'serial_number'])
+
+
+if __name__ == '__main__':
+ sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
+ unittest.main()
diff --git a/xos/synchronizer/models/dt-workflow-driver.xproto b/xos/synchronizer/models/dt-workflow-driver.xproto
new file mode 100755
index 0000000..11e6984
--- /dev/null
+++ b/xos/synchronizer/models/dt-workflow-driver.xproto
@@ -0,0 +1,94 @@
+option name = "dt-workflow-driver";
+option app_label = "dt-workflow-driver";
+
+message DtWorkflowDriverService (Service){
+ option verbose_name = "DtWorkflowDriver Service";
+ option kind = "control";
+ option description = "Service that manages the PPPoE subscriber workflow";
+}
+
+message DtWorkflowDriverServiceInstance (ServiceInstance){
+ option owner_class_name = "DtWorkflowDriverService";
+ option verbose_name = "DtWorkflowDriver Service Instance";
+ option description = "Workflow settings for a particular ONU Device";
+ option policy_implemented = "True";
+
+ required string serial_number = 2 [
+ help_text = "Serial number of ONU",
+ max_length = 256,
+ tosca_key=True,
+ unique = True];
+ required string authentication_state = 3 [
+ help_text = "Subscriber authentication state",
+ choices = "(('AWAITING', 'Awaiting'), ('STARTED', 'Started'), ('APPROVED', 'Approved'), ('DENIED', 'Denied'), )",
+ default = "AWAITING",
+ feedback_state = True,
+ max_length = 50];
+ required string of_dpid = 4 [
+ help_text = "OLT Openflow ID",
+ max_length = 256];
+ required int32 uni_port_id = 5 [
+ help_text = "ONU UNI port ID"];
+ required string admin_onu_state = 6 [
+ help_text = "ONU administrative state",
+ choices = "(('AWAITING', 'Awaiting'), ('ENABLED', 'Enabled'), ('DISABLED', 'Disabled'))",
+ default = "AWAITING",
+ feedback_state = True,
+ max_length = 256];
+ optional string status_message = 7 [
+ help_text = "Status text of current state machine state",
+ default = "",
+ max_length = 256];
+ required string pppoe_state = 8 [
+ help_text = "State of the subscriber PPPoE session",
+ max_length = 256,
+ default = "AWAITING",
+ choices = "(('AWAITING', 'Awaiting'), ('INITIATED', 'Initiated'), ('CONNECTED', 'Connected'), ('DISCONNECTED', 'Disconnected'))",
+ feedback_state = True];
+ optional string pppoe_session_id = 9 [
+ help_text = "Subscriber PPPoE session ID",
+ feedback_state = True,
+ max_length = 20];
+ required string ipcp_state = 10 [
+ help_text = "State of the IPCP protocol for IP address assignment",
+ max_length = 256,
+ default = "AWAITING",
+ choices = "(('AWAITING', 'Awaiting'), ('CONF_ACK', 'Ack'), ('CONF_REQUEST', 'Requested'))",
+ feedback_state = True];
+ optional string ip_address = 11 [
+ help_text = "Subscriber IP address, learned from IPCP",
+ feedback_state = True,
+ max_length = 20];
+ optional string mac_address = 12 [
+ help_text = "Subscriber MAC address",
+ feedback_state = True,
+ max_length = 20];
+ required string oper_onu_status = 13 [
+ help_text = "ONU operational state",
+ choices = "(('AWAITING', 'Awaiting'), ('ENABLED', 'Enabled'), ('DISABLED', 'Disabled'))",
+ default = "AWAITING",
+ feedback_state = True,
+ max_length = 256];
+}
+
+message DtWorkflowDriverWhiteListEntry (XOSBase) {
+ option verbose_name = "ONU Whitelist";
+ option plural = "dtworkflowdriverwhitelistentries";
+ option description = "White list entry that permits an ONU with a particular serial number on a particular OLT and PON";
+ option policy_implemented = "True";
+
+ required manytoone owner->DtWorkflowDriverService:whitelist_entries = 1:1001 [
+ help_text = "DtWorkflowDriverService that owns this white list entry",
+ db_index = True,
+ tosca_key = True];
+ required string serial_number = 2 [
+ help_text = "ONU Serial Number",
+ max_length = 256,
+ tosca_key = True,
+ unique_with = "owner"];
+ required int32 pon_port_id = 3 [
+ help_text = "PON Port on which this ONU is expected to show up"];
+ required string device_id = 4 [
+ help_text = "OLT Device (logical device id) on which this ONU is expected to show up",
+ max_length = 54];
+}
diff --git a/xos/synchronizer/test_config.yaml b/xos/synchronizer/test_config.yaml
new file mode 100755
index 0000000..a23ef0b
--- /dev/null
+++ b/xos/synchronizer/test_config.yaml
@@ -0,0 +1,31 @@
+
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+
+name: test-DtWorkflowDriverService-config
+accessor:
+ username: xosadmin@opencord.org
+ password: "sample"
+ kind: "testframework"
+logging:
+ version: 1
+ handlers:
+ console:
+ class: logging.StreamHandler
+ loggers:
+ 'multistructlog':
+ handlers:
+ - console
+# level: DEBUG
diff --git a/xos/synchronizer/test_helpers.py b/xos/synchronizer/test_helpers.py
new file mode 100755
index 0000000..f1f3afa
--- /dev/null
+++ b/xos/synchronizer/test_helpers.py
@@ -0,0 +1,163 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+import unittest
+from mock import patch, call, Mock, PropertyMock
+import json
+
+import os, sys
+
+test_path=os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
+
+
+class TestDtHelpers(unittest.TestCase):
+
+ def setUp(self):
+
+ self.sys_path_save = sys.path
+
+ # Setting up the config module
+ from xosconfig import Config
+ config = os.path.join(test_path, "test_config.yaml")
+ Config.clear()
+ Config.init(config, "synchronizer-config-schema.yaml")
+ # END Setting up the config module
+
+ from multistructlog import create_logger
+ self.log = create_logger(Config().get('logging'))
+
+ from xossynchronizer.mock_modelaccessor_build import mock_modelaccessor_config
+ mock_modelaccessor_config(test_path, [("dt-workflow-driver", "dt-workflow-driver.xproto"),
+ ("olt-service", "volt.xproto"),
+ ("rcord", "rcord.xproto")])
+
+ import xossynchronizer.modelaccessor
+ import mock_modelaccessor
+ reload(mock_modelaccessor) # in case nose2 loaded it in a previous test
+ reload(xossynchronizer.modelaccessor) # in case nose2 loaded it in a previous test
+
+ from xossynchronizer.modelaccessor import model_accessor
+ from helpers import DtHelpers
+
+ # import all class names to globals
+ for (k, v) in model_accessor.all_model_classes.items():
+ globals()[k] = v
+
+ self.helpers = DtHelpers
+ self.model_accessor = model_accessor
+
+ self._volt = VOLTService()
+ self._volt.id = 1
+
+ self.volt = Service()
+ self.volt.id = 1
+ self.volt.name = "vOLT"
+ self.volt.leaf_model = self._volt
+
+ self.pon_port = PONPort()
+ self.pon_port.port_no = 1234
+
+ self.onu = ONUDevice()
+ self.onu.pon_port = self.pon_port
+ self.onu.serial_number = "BRCM1234"
+
+ self.dt_si = DtWorkflowDriverServiceInstance(
+ serial_number="BRCM1234",
+ owner=self.volt,
+ owner_id=self.volt.id,
+ of_dpid="of:1234"
+ )
+
+ self.whitelist_entry = DtWorkflowDriverWhiteListEntry(
+ serial_number="BRCM1234",
+ owner=self.volt,
+ owner_id=self.volt.id,
+ pon_port_id=1234,
+ device_id="of:1234"
+ )
+
+
+ def tearDown(self):
+ sys.path = self.sys_path_save
+
+ def test_not_in_whitelist(self):
+
+ with patch.object(DtWorkflowDriverWhiteListEntry.objects, "get_items") as whitelist_mock:
+ whitelist_mock.return_value = []
+
+ [res, message] = self.helpers.validate_onu(self.model_accessor, self.log, self.dt_si)
+
+ self.assertFalse(res)
+ self.assertEqual(message, "ONU not found in whitelist")
+
+ def test_wrong_location_port(self):
+ self.pon_port.port_no = 666
+ with patch.object(DtWorkflowDriverWhiteListEntry.objects, "get_items") as whitelist_mock, \
+ patch.object(ONUDevice.objects, "get_items") as onu_mock:
+ whitelist_mock.return_value = [self.whitelist_entry]
+ onu_mock.return_value = [self.onu]
+
+ [res, message] = self.helpers.validate_onu(self.model_accessor, self.log, self.dt_si)
+
+ self.assertFalse(res)
+ self.assertEqual(message, "ONU activated in wrong location")
+
+ def test_wrong_location_device(self):
+ self.dt_si.of_dpid = 666
+ with patch.object(DtWorkflowDriverWhiteListEntry.objects, "get_items") as whitelist_mock, \
+ patch.object(ONUDevice.objects, "get_items") as onu_mock:
+ whitelist_mock.return_value = [self.whitelist_entry]
+ onu_mock.return_value = [self.onu]
+
+ [res, message] = self.helpers.validate_onu(self.model_accessor, self.log, self.dt_si)
+
+ self.assertFalse(res)
+ self.assertEqual(message, "ONU activated in wrong location")
+
+ def test_deferred_validation(self):
+ with patch.object(DtWorkflowDriverWhiteListEntry.objects, "get_items") as whitelist_mock, \
+ patch.object(ONUDevice.objects, "get_items") as onu_mock:
+ whitelist_mock.return_value = [self.whitelist_entry]
+ onu_mock.return_value = []
+
+ with self.assertRaises(Exception) as e:
+ self.helpers.validate_onu(self.model_accessor, self.log, self.dt_si)
+
+ self.assertEqual(e.exception.message, "ONU device %s is not know to XOS yet" % self.dt_si.serial_number)
+
+ def test_validating_onu(self):
+ with patch.object(DtWorkflowDriverWhiteListEntry.objects, "get_items") as whitelist_mock, \
+ patch.object(ONUDevice.objects, "get_items") as onu_mock:
+ whitelist_mock.return_value = [self.whitelist_entry]
+ onu_mock.return_value = [self.onu]
+
+ [res, message] = self.helpers.validate_onu(self.model_accessor, self.log, self.dt_si)
+
+ self.assertTrue(res)
+ self.assertEqual(message, "ONU has been validated")
+
+ def test_validating_onu_lowercase(self):
+ self.whitelist_entry.serial_number = "brcm1234"
+ with patch.object(DtWorkflowDriverWhiteListEntry.objects, "get_items") as whitelist_mock, \
+ patch.object(ONUDevice.objects, "get_items") as onu_mock:
+ whitelist_mock.return_value = [self.whitelist_entry]
+ onu_mock.return_value = [self.onu]
+
+ [res, message] = self.helpers.validate_onu(self.model_accessor, self.log, self.dt_si)
+
+ self.assertTrue(res)
+ self.assertEqual(message, "ONU has been validated")
+
+if __name__ == '__main__':
+ unittest.main()
\ No newline at end of file
diff --git a/xos/unittest.cfg b/xos/unittest.cfg
new file mode 100755
index 0000000..3db2d53
--- /dev/null
+++ b/xos/unittest.cfg
@@ -0,0 +1,14 @@
+[unittest]
+plugins=nose2.plugins.junitxml
+code-directories=synchronizer
+ model_policies
+ steps
+ pull_steps
+ event_steps
+
+[coverage]
+always-on = True
+coverage = synchronizer
+coverage-report = term
+coverage-report = html
+coverage-report = xml