Commit a176ff3c authored by Wen Wei Li's avatar Wen Wei Li

init

parents
Pipeline #4807 canceled with stages
# https://help.github.com/articles/dealing-with-line-endings/
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Explicitly declare text files you want to always be normalized
# and converted to native line endings on checkout.
*.css text
*.htm text diff=html
*.html text diff=html
*.java text diff=java
*.js text
*.jsp text
*.less text
*.properties text
*.sql text
*.xml text
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
# misc cruft
*.log
log.txt
rmr/*
docs_and_diagrams/
# documentation
.tox
docs/_build/
# standard python ignore template
.pytest_cache/
xunit-results.xml
.DS_Store
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
venv-tox/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
# Test report
xunit-reports
coverage-reports
# Eclipse
.project
.pydevproject
.settings
# ==================================================================================
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==================================================================================
FROM python:3.8-alpine
# copy rmr libraries from builder image in lieu of an Alpine package
COPY --from=nexus3.o-ran-sc.org:10002/o-ran-sc/bldr-alpine3-rmr:4.0.5 /usr/local/lib64/librmr* /usr/local/lib64/
# RMR setup
RUN mkdir -p /opt/route/
COPY init/test_route.rt /opt/route/test_route.rt
ENV LD_LIBRARY_PATH /usr/local/lib/:/usr/local/lib64
ENV RMR_SEED_RT /opt/route/test_route.rt
# sdl needs gcc
RUN apk update && apk add gcc musl-dev bash
# Install
COPY setup.py /tmp
COPY README.md /tmp
COPY LICENSE.txt /tmp/
COPY src/ /tmp/src
COPY init/ /tmp/init
RUN pip install /tmp
# Env - TODO- Configmap
ENV PYTHONUNBUFFERED 1
ENV CONFIG_FILE=/tmp/init/config-file.json
# For Default DB connection, modify for resp kubernetes env
ENV DBAAS_SERVICE_PORT=6379
ENV DBAAS_SERVICE_HOST=service-ricplt-dbaas-tcp.ricplt.svc.cluster.local
#Run
CMD run-hw-python.py
---
project: 'ric_app_hw_python'
project_creation_date: '2020-27-10'
project_category: ''
lifecycle_state: 'Incubation'
project_lead: &oran_ric_app_hw_python_ptl
name: 'Matti Hiltunen'
email: '[email protected]'
id: 'MattiHiltunen'
company: 'AT&T Labs-Research'
timezone: 'America/New_York'
primary_contact: *oran_ric_app_hw_python_ptl
issue_tracking:
type: 'jira'
url: 'https://jira.o-ran-sc.org/projects/'
key: 'ric_app_hw'
mailing_list:
type: 'groups.io'
url: 'https://lists.o-ran-sc.org/g/main'
tag: '[]'
realtime_discussion:
type: 'irc'
server: 'freenode.net'
channel: '#oran'
meetings:
- type: 'gotomeeting+irc'
agenda: 'https://wiki.o-ran-sc.org/display/'
url: ''
server: 'freenode.net'
channel: '#oran'
repeats: ''
time: ''
repositories:
- ric-app/hw-python
committers:
- <<: *oran_ric_app_hw_python_ptl
- name: 'Subhash Kumar Singh'
email: '[email protected]'
company: 'Samsung'
id: 'subhash_singh'
timezone: 'Asia/Kolkata'
- name: 'Naman Gupta'
email: '[email protected]'
company: 'Samsung'
id: 'naman.gupta'
timezone: 'Asia/Kolkata'
tsc:
# yamllint disable rule:line-length
approval: 'https://wiki.o-ran-sc.org/display/TOC#ORANSCTechnicalOversightCommittee(TOC)-20200304'
changes:
- type: 'Deletion'
name: 'Rahul Banerji'
link: 'https://lists.o-ran-sc.org/g/toc/message/438'
- type: 'Addition'
name: 'Naman Gupta'
link: 'https://lists.o-ran-sc.org/g/toc/message/438'
Unless otherwise specified, all software contained herein is licensed
under the Apache License, Version 2.0 (the "Software License");
you may not use this software except in compliance with the Software
License. You may obtain a copy of the Software License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the Software License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Software License for the specific language governing permissions
and limitations under the Software License.
Unless otherwise specified, all documentation contained herein is licensed
under the Creative Commons License, Attribution 4.0 Intl. (the
"Documentation License"); you may not use this documentation except in
compliance with the Documentation License. You may obtain a copy of the
Documentation License at
https://creativecommons.org/licenses/by/4.0/
Unless required by applicable law or agreed to in writing, documentation
distributed under the Documentation License is distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the Documentation License for the specific language governing
permissions and limitations under the Documentation License.
This diff is collapsed.
# The Jenkins job requires a tag to build the Docker image.
# Global-JJB script assumes this file is in the repo root.
---
tag: 1.1.1
This diff was suppressed by a .gitattributes entry.
from docs_conf.conf import *
linkcheck_ignore = [
'http://localhost.*',
'http://127.0.0.1.*',
'https://gerrit.o-ran-sc.org.*'
]
---
project_cfg: oran
project: ric-app-hw-py
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. SPDX-License-Identifier: CC-BY-4.0
.. Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.Copyright (C) 2020
Welcome to O-RAN SC HelloWorld xAPP Documentation
========================================================
.. toctree::
:maxdepth: 2
:caption: Contents:
overview.rst
release-notes.rst
installation-guide.rst
user-guide.rst
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. SPDX-License-Identifier: CC-BY-4.0
.. Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
Installation Guide
==================
.. contents::
:depth: 3
:local:
Abstract
--------
This document describes how to install the HelloWorld (HW) Python xAPP.
Version history
+--------------------+--------------------+--------------------+--------------------+
| **Date** | **Ver.** | **Author** | **Comment** |
| | | | |
+--------------------+--------------------+--------------------+--------------------+
| - |- |Rahul Banerji | - |
| | | | |
+--------------------+--------------------+--------------------+--------------------+
Introduction
------------
This document provides guidelines on how to install and configure the HW Python xAPP in various environments/operating modes.
The audience of this document is assumed to have good knowledge in RIC Platform.
Preface
-------
This xAPP can be run directly as a Linux binary, as a docker image, or in a pod in a Kubernetes environment. The first
two can be used for dev testing. The last option is how an xAPP is deployed in the RAN Intelligent Controller environment.
This document covers all three methods.
Software Installation and Deployment
------------------------------------
The build process assumes a Linux environment with python >= 3.8 and has been tested on Ubuntu. For building docker images,
the Docker environment must be present in the system.
Build Process
~~~~~~~~~~~~~
The HW xAPP can be either tested as a Linux binary or as a docker image.
1. **Linux binary**:
TBD
2. **Docker Image**: From the root of the repository, run *docker --no-cache build -t <image-name> ./* .
Deployment
~~~~~~~~~~
End to end deployment of `hw-python` can be referred at :
:ref: `Deployment Guide`.
Testing
--------
Unit tests TBD
This diff is collapsed.
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. SPDX-License-Identifier: CC-BY-4.0
.. Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.Copyright (C) 2020
HelloWorld Python xAPP Overview
================================
This repository contains open-source code for a prototype python xAPP for near real-time
RAN Intelligent Controller which makes use of python Xapp Framework.
This xAPP aims to provide basic implementation of :
-E2, A1 interfaces interactions.
-Read-write operations into a persistent storage.
-xAPP Configuration management
-RMR Health Check
-xAPP Health Check
-Raising alarms
-Generating metrics
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. SPDX-License-Identifier: CC-BY-4.0
.. Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.Copyright (C) 2020
Release Notes
=============
This document provides the release notes for the Bronze Release of the HelloWorld (HW) xAPP.
.. contents::
:depth: 3
:local:
Version history
---------------
+--------------------+--------------------+--------------------+--------------------+
| **Date** | **Ver.** | **Author** | **Comment** |
| | | | |
+--------------------+--------------------+--------------------+--------------------+
| 2021-06-23 | 1.0.0 | Naman Gupta | Dawn Release |
| | | | |
+--------------------+--------------------+--------------------+--------------------+
Summary
-------
The Dawn release of the go HW xAPP demonstrates the following:
- A1 interfaces interactions.
- -xAPP Health Check
- SDL Handler
- Alarm Management
Release Data
------------
+--------------------------------------+--------------------------------------+
| **Project** | RAN Intelligent Controller |
| | |
+--------------------------------------+--------------------------------------+
| **Repo/commit-ID** | TBD |
| | |
+--------------------------------------+--------------------------------------+
| **Release designation** | TBD |
| | |
+--------------------------------------+--------------------------------------+
| **Release date** | TBD |
| | |
+--------------------------------------+--------------------------------------+
| **Purpose of the delivery** | open-source Python Hello World xAPP |
| | |
| | |
+--------------------------------------+--------------------------------------+
Components
----------
TBD
Limitations
-----------
- The HW xAPP doesn't have any usecase in particular to display SDL capabilities.
- The subscription process assumes, on sending subscription request results in valid subscription response.
- The HW xAPP doesn't address any RIC usecase in particular.
sphinx
sphinx-rtd-theme
sphinxcontrib-httpdomain
recommonmark
lfdocs-conf
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. SPDX-License-Identifier: CC-BY-4.0
.. Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.Copyright (C) 2020
============================================================================================
HelloWorld xAPP (Python)
============================================================================================
--------------------------------------------------------------------------------------------
User's Guide
--------------------------------------------------------------------------------------------
Introduction
============================================================================================
The RIC platform provides set of functions as part of xAPP Python Framework that the xAPPs can use to accomplish their tasks.
This xAPP is envisioned to provide python xAPP developers, examples of implementing these sets of functions.
Note, HW xAPP does not address/implement any RIC Usecases.
HelloWorld xAPP Features
============================================================================================
RIC Platform provides many Frameworks, APIs and libraries to aid the development of xAPPs. All xAPPs will have some custom
processing functional logic core to the xApp and some additional non-functional platform related processing using
these APIs and libraries. This xAPP attempts to show the usage of such additional platform processing using xapp RIC framework APIs and libraries.
The Hello World xApp demonstrates how a python based xApp uses the A1, and E2 interfaces and persistent database read-write operations.
{
"name": "hw-python",
"version": "1.0.0",
"containers": [
{
"name": "hw-python",
"image": {
"registry": "nexus3.o-ran-sc.org:10004",
"name": "o-ran-sc/ric-app-hw-python",
"tag": "1.1.0"
}
}
],
"messaging": {
"ports": [
{
"name": "http",
"container": "hw-python",
"port": 8080,
"description": "http service"
},
{
"name": "rmrroute",
"container": "hw-python",
"port": 4561,
"description": "rmr route port for hw-python xapp"
},
{
"name": "rmrdata",
"container": "hw-python",
"port": 4560,
"rxMessages": ["RIC_SUB_RESP", "RIC_SUB_FAILURE", "RIC_SUB_DEL_RESP", "RIC_INDICATION"],
"txMessages": ["RIC_SUB_REQ", "RIC_SUB_DEL_REQ", "RIC_SGNB_ADDITION_REQ", "RIC_SGNB_ADDITION_ACK"],
"mtypes" : [
{"name":"TESTNAME1","id":55555},
{"name":"TESTNAME2","id":55556}
],
"policies": [1],
"description": "rmr data port for hw-python"
}
]
},
"rmr": {
"protPort": "tcp:4560",
"maxSize": 2072,
"numWorkers": 1,
"txMessages": [
"RIC_SUB_REQ", "A1_POLICY_RESP", "A1_POLICY_QUERY", "RIC_HEALTH_CHECK_RESP"
],
"rxMessages": [
"RIC_SUB_RESP",
"A1_POLICY_REQ", "RIC_HEALTH_CHECK_REQ"
],
"policies": [1]
},
"controls": {
"fileStrorage": false
},
"db" : {
"waitForSdl": false
}
}
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
# This initialization script reads in a json from the specified config map path
# to set up the initializations (route config map, variables etc) for the main
# xapp process
import json
import sys
import os
import signal
import time
default_routing_file = "/opt/route/test_route.rt"
lport = 0
def signal_handler(signum, frame):
print("Received signal {0}\n".format(signum))
if xapp_subprocess is None or xapp_pid is None:
print("No xapp running. Quiting without sending signal to xapp\n", flush=True)
else:
print("Sending signal {0} to xapp ...".format(signum), flush=True)
xapp_subprocess.send_signal(signum)
def parseConfigJson(config):
for k1 in config.keys():
if k1 in ParseSection:
result = ParseSection[k1](config)
if not result:
return False
def getMessagingInfo(config):
global lport
if 'messaging' in config.keys() and 'ports' in config['messaging'].keys():
port_list = config['messaging']['ports']
for portdesc in port_list:
if 'port' in portdesc.keys() and 'name' in portdesc.keys() and portdesc['name'] == 'rmr-data':
lport = portdesc['port']
# Set the environment variable
os.environ["HW_PORT"] = str(lport)
return True
if lport == 0:
print("Error! No valid listening port", flush=True)
return False
def getXappName(config):
myKey = "xapp_name"
if myKey not in config.keys():
print(("Error ! No information found for {0} in config\n".format(myKey)), flush=True)
return False
xapp_name = config[myKey]
print("Xapp Name is: " + xapp_name)
os.environ["XAPP_NAME"] = xapp_name
ParseSection = dict()
ParseSection["xapp_name"] = getXappName
ParseSection["messaging"] = getMessagingInfo
# ================================================================
if __name__ == "__main__":
import subprocess
cmd = ["/usr/local/bin/run-hw-python.py"]
config_file = os.getenv("CONFIG_FILE", None)
if config_file is None:
print("Error! No configuration file specified\n", flush=True)
sys.exit(1)
with open(config_file, 'r') as f:
try:
config = json.load(f)
except Exception as e:
print(("Error loading json file from {0}. Reason = {1}\n".format(config_file, e)), flush=True)
sys.exit(1)
result = parseConfigJson(config)
if not result:
print("Error parsing config json. Not executing xAPP", flush=True)
sys.exit(1)
else:
print("Config read successfully", flush=True)
# Register signal handlers
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Start the xAPP
print("Executing xAPP ....", flush=True)
xapp_subprocess = subprocess.Popen(cmd, shell=False, stdin=None, stdout=None, stderr=None)
xapp_pid = xapp_subprocess.pid
# Periodically poll the process every 5 seconds to check if still alive
while 1:
xapp_status = xapp_subprocess.poll()
if xapp_status is None:
time.sleep(5)
else:
print("XaPP terminated via signal {0}\n".format(-1 * xapp_status), flush=True)
break
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "#/controls",
"type": "object",
"title": "Controls Section Schema",
"required": [
],
"properties": {
}
}
newrt|start
rte|13111|127.0.0.1:4560
rte|20011|service-ricplt-a1mediator-rmr.ricplt:4562
rte|20012|service-ricplt-a1mediator-rmr.ricplt:4562
newrt|end
---
distribution_type: container
container_release_tag: 1.1.1
container_pull_registry: nexus3.o-ran-sc.org:10004
container_push_registry: nexus3.o-ran-sc.org:10002
project: ric-app/hw-python
ref: 8cf17dc3de639da53d034608c8a7efb3295d0ea0
containers:
- name: ric-app-hw-python
version: 1.1.1
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
apiVersion: v1
kind: Pod
metadata:
name: hwxapp
labels:
role: xapp
spec:
containers:
- name: hwxapp-py
image: hwxapp-py:1.0
ports:
- name: rmr
containerPort: 4560
protocol: TCP
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==================================================================================
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='hw_python',
version='0.0.1',
packages=find_packages(),
url='https://gerrit.o-ran-sc.org/r/admin/repos/ric-app/hw-python',
license='Apache 2.0',
description="Hello World Python XAPP for O-RAN RIC Platform",
long_description=read('README.md'),
author='Naman Gupta',
author_email='[email protected]',
python_requires='>=3.8',
install_requires=["ricxappframe>=1.1.1,<2.3.0"],
entry_points={"console_scripts": ["run-hw-python.py=src.main:launchXapp"]}, # adds a magical entrypoint for Docker
data_files=[("", ["LICENSE.txt"])],
)
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
import json
from ricxappframe.xapp_frame import RMRXapp, rmr
from ..utils.constants import Constants
from ._BaseHandler import _BaseHandler
class A1PolicyHandler(_BaseHandler):
def __init__(self, rmr_xapp: RMRXapp, msgtype):
super().__init__(rmr_xapp, msgtype)
def request_handler(self, rmr_xapp, summary, sbuf):
self._rmr_xapp.rmr_free(sbuf)
try:
req = json.loads(summary[rmr.RMR_MS_PAYLOAD]) # input should be a json encoded as bytes
self.logger.debug("A1PolicyHandler.resp_handler:: Handler processing request")
except (json.decoder.JSONDecodeError, KeyError):
self.logger.error("A1PolicyManager.resp_handler:: Handler failed to parse request")
return
if self.verifyPolicy(req):
self.logger.info("A1PolicyHandler.resp_handler:: Handler processed request: {}".format(req))
else:
self.logger.error("A1PolicyHandler.resp_handler:: Request verification failed: {}".format(req))
return
self.logger.debug("A1PolicyHandler.resp_handler:: Request verification success: {}".format(req))
resp = self.buildPolicyResp(req)
self._rmr_xapp.rmr_send(json.dumps(resp).encode(), Constants.A1_POLICY_RESP)
self.logger.info("A1PolicyHandler.resp_handler:: Response sent: {}".format(resp))
def verifyPolicy(self, req: dict):
for i in ["policy_type_id", "operation", "policy_instance_id"]:
if i not in req:
return False
return True
def buildPolicyResp(self, req: dict):
req["handler_id"] = self._rmr_xapp.config["xapp_name"]
del req["operation"]
req["status"] = "OK"
return req
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
import json
from ricxappframe.xapp_frame import RMRXapp
from ..utils.constants import Constants
from ._BaseHandler import _BaseHandler
# from ..manager import SdlAlarmManager
class HealthCheckHandler(_BaseHandler):
def __init__(self, rmr_xapp: RMRXapp, msgtype):
super().__init__(rmr_xapp, msgtype)
# self.sdl_alarm_mgr = SdlAlarmManager()
def request_handler(self, rmr_xapp, summary, sbuf):
ok = self._rmr_xapp.healthcheck()
# self.sdl_alarm_mgr.checkSdl()
if ok:
payload = b"OK\n"
else:
payload = b"ERROR [RMR or SDL is unhealthy]\n"
self._rmr_xapp.rmr_rts(sbuf, new_payload=payload, new_mtype=Constants.RIC_HEALTH_CHECK_RESP)
self._rmr_xapp.rmr_free(sbuf)
# ==================================================================================
#
# Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
"""
Handles subscription messages from enbs and gnbs through rmr.
"""
import json
from ricxappframe.xapp_frame import RMRXapp, rmr
from ..utils.constants import Constants
from ._BaseHandler import _BaseHandler
from ..manager.SdlManager import SdlManager
class SubscriptionHandler(_BaseHandler):
def __init__(self, rmr_xapp: RMRXapp, msgtype):
super().__init__(rmr_xapp, msgtype)
def request_handler(self, rmr_xapp, summary, sbuf):
"""
Handles subscription messages.
Parameters
----------
rmr_xapp: rmr Instance Context
summary: dict (required)
buffer content
sbuf: str (required)
length of the message
"""
self._rmr_xapp.rmr_free(sbuf)
try:
req = json.loads(summary[rmr.RMR_MS_PAYLOAD]) # input should be a json encoded as bytes
self.logger.debug("SubscriptionHandler.resp_handler:: Handler processing request")
except (json.decoder.JSONDecodeError, KeyError):
self.logger.error("Subscription.resp_handler:: Handler failed to parse request")
return
if self.verifySubscription(req):
self.logger.info("SubscriptionHandler.resp_handler:: Handler processed request: {}".format(req))
else:
self.logger.error("SubscriptionHandler.resp_handler:: Request verification failed: {}".format(req))
return
self.logger.debug("SubscriptionHandler.resp_handler:: Request verification success: {}".format(req))
def verifySubscription(self, req: dict):
for i in ["subscription_id", "message"]:
if i not in req:
return False
return True
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from ricxappframe.xapp_frame import RMRXapp
from abc import ABC, abstractmethod
class _BaseHandler(ABC):
"""
Represents base Abstract Handler class
Here initialize variables which will be common to all xapp
Parameters:
rmr_xapp: Reference to original RMRxappframe object
msgtype: Integer specifying messagetype
"""
def __init__(self, rmr_xapp: RMRXapp, msgtype):
self._rmr_xapp = rmr_xapp
self.logger = self._rmr_xapp.logger
self.msgtype = msgtype
self._rmr_xapp.register_callback(self.request_handler, msgtype)
@abstractmethod
def request_handler(self, rmr_xapp, summary, sbuf):
pass
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from .A1PolicyHandler import A1PolicyHandler
from .HealthCheckHandler import HealthCheckHandler
from .SubscriptionHandler import SubscriptionHandler
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from os import getenv
from ricxappframe.xapp_frame import RMRXapp, rmr
from .utils.constants import Constants
from .manager import *
from .handler import *
from mdclogpy import Logger
class HWXapp:
def __init__(self):
fake_sdl = getenv("USE_FAKE_SDL", False)
self._rmr_xapp = RMRXapp(self._default_handler,
config_handler=self._handle_config_change,
rmr_port=4560,
post_init=self._post_init,
use_fake_sdl=bool(fake_sdl))
def _post_init(self, rmr_xapp):
"""
Function that runs when xapp initialization is complete
"""
rmr_xapp.logger.info("HWXapp.post_init :: post_init called")
# self.sdl_alarm_mgr = SdlAlarmManager()
sdl_mgr = SdlManager(rmr_xapp)
sdl_mgr.sdlGetGnbList()
a1_mgr = A1PolicyManager(rmr_xapp)
a1_mgr.startup()
sub_mgr = SubscriptionManager(rmr_xapp)
enb_list = sub_mgr.get_enb_list()
for enb in enb_list:
sub_mgr.send_subscription_request(enb)
gnb_list = sub_mgr.get_gnb_list()
for gnb in gnb_list:
sub_mgr.send_subscription_request(gnb)
metric_mgr = MetricManager(rmr_xapp)
metric_mgr.send_metric()
def _handle_config_change(self, rmr_xapp, config):
"""
Function that runs at start and on every configuration file change.
"""
rmr_xapp.logger.info("HWXapp.handle_config_change:: config: {}".format(config))
rmr_xapp.config = config # No mutex required due to GIL
def _default_handler(self, rmr_xapp, summary, sbuf):
"""
Function that processes messages for which no handler is defined
"""
rmr_xapp.logger.info("HWXapp.default_handler called for msg type = " +
str(summary[rmr.RMR_MS_MSG_TYPE]))
rmr_xapp.rmr_free(sbuf)
def createHandlers(self):
"""
Function that creates all the handlers for RMR Messages
"""
HealthCheckHandler(self._rmr_xapp, Constants.RIC_HEALTH_CHECK_REQ)
A1PolicyHandler(self._rmr_xapp, Constants.A1_POLICY_REQ)
SubscriptionHandler(self._rmr_xapp,Constants.SUBSCRIPTION_REQ)
def start(self, thread=False):
"""
This is a convenience function that allows this xapp to run in Docker
for "real" (no thread, real SDL), but also easily modified for unit testing
(e.g., use_fake_sdl). The defaults for this function are for the Dockerized xapp.
"""
self.createHandlers()
self._rmr_xapp.run(thread)
def stop(self):
"""
can only be called if thread=True when started
TODO: could we register a signal handler for Docker SIGTERM that calls this?
"""
self._rmr_xapp.stop()
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from .hwxapp import HWXapp
def launchXapp():
hwxapp = HWXapp()
hwxapp.start()
if __name__ == "__main__":
launchXapp()
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
import json
from ricxappframe.xapp_frame import RMRXapp, rmr
from ..utils.constants import Constants
from ._BaseManager import _BaseManager
class A1PolicyManager(_BaseManager):
def __init__(self, rmr_xapp: RMRXapp):
super().__init__(rmr_xapp)
def startup(self):
policy_query = '{"policy_type_id":"' + str(Constants.HELLOWORLD_POLICY_ID) + '"}'
self._rmr_xapp.rmr_send(policy_query.encode(), Constants.A1_POLICY_QUERY)
self.logger.info("A1PolicyManager.startup:: Sent A1 policy query = " + policy_query)
# ==================================================================================
#
# Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from ricxappframe.xapp_frame import RMRXapp
from ricxappframe.metric import metric
from ._BaseManager import _BaseManager
from datetime import datetime
# noinspection PyProtectedMember,PyProtectedMember
class MetricManager(_BaseManager):
def __init__(self, rmr_xapp: RMRXapp):
super().__init__(rmr_xapp)
self.metric_mgr = metric.MetricsManager(self._rmr_xapp._mrc, "system-time", "hw-python")
def send_metric(self):
# datetime object containing current date and time
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
metric_list = [dt_string]
self.logger.info("MetricManager:: metric time {}".format(metric_list))
self.metric_mgr.send_metrics(metric_list)
self.logger.info("MetricManager:: metric sent")
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from ricxappframe.xapp_frame import RMRXapp
from ricxappframe.alarm import alarm
from ._BaseManager import _BaseManager
# noinspection PyProtectedMember,PyProtectedMember
class SdlAlarmManager(_BaseManager):
def __init__(self, rmr_xapp: RMRXapp):
super().__init__(rmr_xapp)
self.alarm_mgr = alarm.AlarmManager(self._rmr_xapp._mrc, "ric-xapp", "hw-python")
self.alarm_sdl = None
def checkSdl(self):
if self._rmr_xapp._sdl.healthcheck():
# healthy, so clear the alarm if it was raised
if self.alarm_sdl:
self.logger.info("SdlAlarmManager:: clearing alarm")
self.alarm_mgr.clear_alarm(self.alarm_sdl)
self.alarm_sdl = None
else:
# not healthy, so (re-)raise the alarm
self.logger.info("SdlAlarmManager:: connection to SDL is not healthy, raising alarm")
if self.alarm_sdl:
self.alarm_mgr.reraise_alarm(self.alarm_sdl)
else:
self.alarm_sdl = self.alarm_mgr.create_alarm(1, alarm.AlarmSeverity.CRITICAL,
"SdlAlarmManager:: SDL failure")
self.alarm_mgr.raise_alarm(self.alarm_sdl)
self.logger.warning("SdlAlarmManager:: dropping request!")
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from ricxappframe.xapp_frame import RMRXapp
import json
from ._BaseManager import _BaseManager
class SdlManager(_BaseManager):
__namespace = "e2Manager"
def __init__(self, rmr_xapp: RMRXapp):
super().__init__(rmr_xapp)
def sdlGetGnbList(self):
gnblist = self._rmr_xapp.sdl_find_and_get(self.__namespace, "GNB")
self.logger.info("SdlManager.sdlGetGnbList:: Processed request: {}".format(json.dumps(gnblist)))
def sdlGetEnbList(self):
enblist = self._rmr_xapp.sdl_find_and_get(self.__namespace, "ENB")
self.logger.info("SdlManager.sdlGetGnbList:: Handler processed request: {}".format(json.dumps(enblist)))
# ==================================================================================
#
# Copyright (c) 2021 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
"""
"""
import requests
from ricxappframe.xapp_frame import RMRXapp
import json
from ..utils.constants import Constants
from ._BaseManager import _BaseManager
class SubscriptionManager(_BaseManager):
__namespace = "e2Manager"
def __init__(self, rmr_xapp: RMRXapp):
super().__init__(rmr_xapp)
def get_gnb_list(self):
gnblist = self._rmr_xapp.get_list_gnb_ids() # yet to come in library
self.logger.info("SubscriptionManager.getGnbList:: Processed request: {}".format(json.dumps(gnblist)))
return gnblist
def get_enb_list(self):
enblist = self._rmr_xapp.get_list_enb_ids() # yet to come in library
self.logger.info("SubscriptionManager.sdlGetGnbList:: Handler processed request: {}".format(json.dumps(enblist)))
return enblist
def send_subscription_request(self,xnb_id):
subscription_request = {"xnb_id": xnb_id, "action_type": Constants.ACTION_TYPE}
try:
json_object = json.dumps(subscription_request,indent=4)
except TypeError:
print("Unable to serialize the object")
url = Constants.SUBSCRIPTION_PATH.format(Constants.PLT_NAMESPACE,
Constants.SUBSCRIPTION_SERVICE,
Constants.SUBSCRIPTION_PORT)
try:
response = requests.post(url , json=json_object)
response.raise_for_status()
except requests.exceptions.HTTPError as err_h:
return "An Http Error occurred:" + repr(err_h)
except requests.exceptions.ConnectionError as err_c:
return "An Error Connecting to the API occurred:" + repr(err_c)
except requests.exceptions.Timeout as err_t:
return "A Timeout Error occurred:" + repr(err_t)
except requests.exceptions.RequestException as err:
return "An Unknown Error occurred" + repr(err)
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from ricxappframe.xapp_frame import RMRXapp
from abc import ABC
class _BaseManager(ABC):
"""
Represents base Manager Abstract class
Here initialize variables which will be common to all xapp
Parameters:
rmr_xapp: Reference to original RMRxappframe object
"""
def __init__(self, rmr_xapp: RMRXapp):
self._rmr_xapp = rmr_xapp
self.logger = self._rmr_xapp.logger
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
from .A1PolicyManager import A1PolicyManager
from .SdlAlarmManager import SdlAlarmManager
from .SdlManager import SdlManager
from .SubscriptionManager import SubscriptionManager
from .MetricManager import MetricManager
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
# ==================================================================================
#
# Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==================================================================================
class Constants:
A1_POLICY_QUERY = 20012
HELLOWORLD_POLICY_ID = 2
RIC_HEALTH_CHECK_REQ = 100
RIC_HEALTH_CHECK_RESP = 101
A1_POLICY_REQ = 20010
A1_POLICY_RESP = 20011
RIC_ALARM_UPDATE = 110
ACTION_TYPE = "REPORT"
SUBSCRIPTION_PATH = "http://service-{}-{}-http:{}"
PLT_NAMESPACE = "ricplt"
SUBSCRIPTION_SERVICE = "submgr"
SUBSCRIPTION_PORT = "3800"
SUBSCRIPTION_REQ = 12011
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment