-FROM python:3.10-slim-buster\r
-\r
-RUN apt-get update; apt-get install -y git gcc\r
-\r
-# in case git repo is not accessable\r
-# RUN mkdir -p /cgtsclient\r
-# COPY temp/config /cgtsclient/\r
-RUN git clone --depth 1 --branch master https://opendev.org/starlingx/config.git /cgtsclient\r
-RUN pip install -e /cgtsclient/sysinv/cgts-client/cgts-client/\r
-\r
-# RUN mkdir -p /distcloud-client\r
-# COPY temp/distcloud-client /distcloud-client/\r
-RUN git clone --depth 1 --branch master https://opendev.org/starlingx/distcloud-client.git /distcloud-client/\r
-RUN pip install -e /distcloud-client/distributedcloud-client\r
-# in case git repo is not accessable\r
-\r
-# RUN git clone --depth 1 --branch master https://github.com/cloudify-incubator/cloudify-helm-plugin.git /helmsdk\r
-\r
-\r
-COPY requirements.txt /tmp/\r
-COPY requirements-stx.txt /tmp/\r
-COPY constraints.txt /tmp/\r
-\r
-RUN pip install -r /tmp/requirements.txt -c /tmp/constraints.txt\r
-\r
-# RUN pip install -r /tmp/requirements-stx.txt\r
-\r
-COPY requirements-test.txt /tmp/\r
-RUN pip install -r /tmp/requirements-test.txt\r
-\r
-\r
-RUN mkdir -p /src\r
-COPY o2ims/ /src/o2ims/\r
-COPY o2dms/ /src/o2dms/\r
-COPY o2common/ /src/o2common/\r
-\r
-RUN mkdir -p /src/o2app/\r
-COPY o2app/ /src/o2app/\r
-COPY setup.py /src/\r
-\r
-RUN pip install -e /src\r
-\r
-COPY configs/ /etc/o2/\r
-\r
-COPY tests/ /tests/\r
-\r
-RUN apt-get install -y procps vim curl\r
-\r
-RUN curl -O https://get.helm.sh/helm-v3.3.1-linux-amd64.tar.gz;\r
-RUN tar -zxvf helm-v3.3.1-linux-amd64.tar.gz; cp linux-amd64/helm /usr/local/bin\r
-\r
-WORKDIR /src\r
+FROM python:3.10-slim-buster
+
+RUN apt-get update; apt-get install -y git gcc
+
+# in case git repo is not accessable
+# RUN mkdir -p /cgtsclient
+# COPY temp/config /cgtsclient/
+RUN git clone --depth 1 --branch master https://opendev.org/starlingx/config.git /cgtsclient
+RUN pip install -e /cgtsclient/sysinv/cgts-client/cgts-client/
+
+# RUN mkdir -p /distcloud-client
+# COPY temp/distcloud-client /distcloud-client/
+RUN git clone --depth 1 --branch master https://opendev.org/starlingx/distcloud-client.git /distcloud-client/
+RUN pip install -e /distcloud-client/distributedcloud-client
+# in case git repo is not accessable
+
+# RUN git clone --depth 1 --branch master https://github.com/cloudify-incubator/cloudify-helm-plugin.git /helmsdk
+
+
+COPY requirements.txt /tmp/
+COPY requirements-stx.txt /tmp/
+COPY constraints.txt /tmp/
+
+RUN pip install -r /tmp/requirements.txt -c /tmp/constraints.txt
+
+# RUN pip install -r /tmp/requirements-stx.txt
+
+COPY requirements-test.txt /tmp/
+RUN pip install -r /tmp/requirements-test.txt
+
+
+RUN mkdir -p /src
+COPY o2ims/ /src/o2ims/
+COPY o2dms/ /src/o2dms/
+COPY o2common/ /src/o2common/
+
+RUN mkdir -p /src/o2app/
+COPY o2app/ /src/o2app/
+COPY setup.py /src/
+
+RUN pip install -e /src
+
+COPY configs/ /etc/o2/
+
+COPY tests/ /tests/
+
+RUN apt-get install -y procps vim curl
+
+RUN curl -O https://get.helm.sh/helm-v3.3.1-linux-amd64.tar.gz;
+RUN tar -zxvf helm-v3.3.1-linux-amd64.tar.gz; cp linux-amd64/helm /usr/local/bin
+
+WORKDIR /src
-FROM python:3.10-slim-buster\r
-\r
-RUN apt-get update; apt-get install -y git gcc\r
-\r
-# in case git repo is not accessable\r
-RUN mkdir -p /cgtsclient\r
-COPY temp/config /cgtsclient/\r
-RUN pip install -e cgtsclient/sysinv/cgts-client/cgts-client/\r
-\r
-RUN mkdir -p /distcloud-client\r
-COPY temp/distcloud-client /distcloud-client/\r
-RUN pip install -e /distcloud-client/distributedcloud-client\r
-# in case git repo is not accessable\r
-\r
-\r
-COPY requirements.txt /tmp/\r
-COPY constraints.txt /tmp/\r
-\r
-RUN pip install -r /tmp/requirements.txt -c /tmp/constraints.txt\r
-\r
-COPY requirements-test.txt /tmp/\r
-RUN pip install -r /tmp/requirements-test.txt\r
-\r
-\r
-RUN mkdir -p /src\r
-COPY o2ims/ /src/o2ims/\r
-COPY o2dms/ /src/o2dms/\r
-COPY o2common/ /src/o2common/\r
-\r
-RUN mkdir -p /src/o2app/\r
-COPY o2app/ /src/o2app/\r
-\r
-RUN mkdir -p /src/helm_sdk/\r
-COPY helm_sdk/ /src/helm_sdk/\r
-\r
-COPY setup.py /src/\r
-\r
-COPY configs/ /etc/o2/\r
-\r
-# RUN mkdir -p /helmsdk\r
-# COPY temp/helmsdk /helmsdk/\r
-# # RUN git clone --depth 1 --branch master https://github.com/cloudify-incubator/cloudify-helm-plugin.git helmsdk\r
-# COPY /helmsdk/helm_sdk /src/helm_sdk\r
-\r
-# RUN pip install -e /src\r
-COPY tests/ /tests/\r
-\r
-RUN apt-get install -y procps vim\r
-\r
-RUN apt-get install -y curl\r
-RUN curl -O https://get.helm.sh/helm-v3.3.1-linux-amd64.tar.gz;\r
-RUN tar -zxvf helm-v3.3.1-linux-amd64.tar.gz; cp linux-amd64/helm /usr/local/bin\r
-\r
-RUN mkdir -p /etc/kubeconfig/\r
-# COPY temp/kubeconfig/config /etc/kubeconfig/\r
-\r
-WORKDIR /src\r
+FROM python:3.10-slim-buster
+
+RUN apt-get update; apt-get install -y git gcc
+
+# in case git repo is not accessable
+RUN mkdir -p /cgtsclient
+COPY temp/config /cgtsclient/
+RUN pip install -e cgtsclient/sysinv/cgts-client/cgts-client/
+
+RUN mkdir -p /distcloud-client
+COPY temp/distcloud-client /distcloud-client/
+RUN pip install -e /distcloud-client/distributedcloud-client
+# in case git repo is not accessable
+
+
+COPY requirements.txt /tmp/
+COPY constraints.txt /tmp/
+
+RUN pip install -r /tmp/requirements.txt -c /tmp/constraints.txt
+
+COPY requirements-test.txt /tmp/
+RUN pip install -r /tmp/requirements-test.txt
+
+
+RUN mkdir -p /src
+COPY o2ims/ /src/o2ims/
+COPY o2dms/ /src/o2dms/
+COPY o2common/ /src/o2common/
+
+RUN mkdir -p /src/o2app/
+COPY o2app/ /src/o2app/
+
+RUN mkdir -p /src/helm_sdk/
+COPY helm_sdk/ /src/helm_sdk/
+
+COPY setup.py /src/
+
+COPY configs/ /etc/o2/
+
+# RUN mkdir -p /helmsdk
+# COPY temp/helmsdk /helmsdk/
+# # RUN git clone --depth 1 --branch master https://github.com/cloudify-incubator/cloudify-helm-plugin.git helmsdk
+# COPY /helmsdk/helm_sdk /src/helm_sdk
+
+# RUN pip install -e /src
+COPY tests/ /tests/
+
+RUN apt-get install -y procps vim
+
+RUN apt-get install -y curl
+RUN curl -O https://get.helm.sh/helm-v3.3.1-linux-amd64.tar.gz;
+RUN tar -zxvf helm-v3.3.1-linux-amd64.tar.gz; cp linux-amd64/helm /usr/local/bin
+
+RUN mkdir -p /etc/kubeconfig/
+# COPY temp/kubeconfig/config /etc/kubeconfig/
+
+WORKDIR /src
-\r
-## Build and deploy O2 services over O-Cloud (INF)\r
-\r
-\r
-## Bring up builder container from O-Cloud controller node\r
-\r
-\r
-```sh\r
-mkdir -p /home/sysadmin/share\r
-sudo docker run -dt --privileged -v /home/sysadmin/share/:/home/sysadmin/share/ -v /var/run:/var/run --name o2imsbuilder centos:7\r
-```\r
-\r
-## Build O2 service images inside the builder container\r
-\r
-\r
-```sh\r
-sudo docker exec -it o2imsbuilder bash\r
-```\r
-\r
-\r
-```sh\r
-curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\r
-chmod +x /usr/local/bin/docker-compose\r
-docker-compose -v\r
-\r
-yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo\r
-yum makecache fast\r
-yum install -y docker-ce\r
-docker ps\r
-\r
-yum install -y git\r
-\r
-cd /home/sysadmin/share/\r
-git clone "https://gerrit.o-ran-sc.org/r/pti/o2"\r
-cd o2\r
-\r
-mkdir -p temp\r
-cd temp\r
-git clone --depth 1 --branch master https://opendev.org/starlingx/config.git\r
-git clone --depth 1 --branch master https://opendev.org/starlingx/distcloud-client.git\r
-cd -\r
-\r
-docker-compose build\r
-\r
-exit\r
-\r
-```\r
-\r
-### Push O2 service images to local registry (with auth user admin)\r
-\r
-```sh\r
-sudo docker tag o2imsdms:latest registry.local:9001/admin/o2imsdms:0.1.4\r
-sudo docker image push registry.local:9001/admin/o2imsdms:0.1.4\r
-\r
-```\r
-\r
-## Deploy O2 services with helm chart over O-Cloud controller node (with auth user admin)\r
-\r
-```sh\r
-export NAMESPACE=orano2\r
-kubectl create ns ${NAMESPACE}\r
-\r
-cd /home/sysadmin/\r
-source /etc/platform/openrc\r
-cat <<EOF>ocloud-override.yaml\r
-o2ims:\r
- imagePullSecrets: admin-orano2-registry-secret\r
- image:\r
- repository: registry.local:9001/admin/o2imsdms\r
- tag: 0.1.4\r
- pullPolicy: IfNotPresent\r
- logginglevel: "DEBUG"\r
-\r
-ocloud:\r
- OS_AUTH_URL: "${OS_AUTH_URL}"\r
- OS_USERNAME: "${OS_USERNAME}"\r
- OS_PASSWORD: "${OS_PASSWORD}"\r
-EOF\r
-\r
-sudo docker login registry.local:9001 -u ${OS_PROJECT_NAME} -p ${OS_PASSWORD}\r
-\r
-kubectl -n ${NAMESPACE} create secret docker-registry ${OS_PROJECT_NAME}-${NAMESPACE}-registry-secret \\r
---docker-server=registry.local:9001 --docker-username=${OS_PROJECT_NAME} \\r
---docker-password=${OS_PASSWORD} --docker-email=noreply@windriver.com\r
-\r
-cd /home/sysadmin/share/o2\r
-\r
-helm install o2imstest charts/ -f /home/sysadmin/ocloud-override.yaml\r
-\r
-kubectl -n ${NAMESPACE} get pods\r
-\r
-```\r
-\r
-### test api endpoint\r
-\r
-```sh\r
-curl -k http(s)://<Node IP>:30205\r
-curl -k http(s)://<Node IP>:30205/o2ims_infrastructureInventory/v1\r
-```\r
-\r
-\r
-### Debug tips\r
-\r
-```sh\r
-kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c o2api\r
-kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c postgres\r
-kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c o2pubsub\r
-kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c watcher\r
-\r
-\r
-kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c o2api\r
-\r
-kubectl -n ${NAMESPACE} exec -it o2api-<xxx> -c postgres -- bash\r
- psql -U o2ims\r
-\r
- \c o2ims\r
-\r
- \d\r
-\r
- select * from ocloud;\r
-\r
- \q\r
-\r
- exit\r
-\r
-```\r
-\r
-## Issues:\r
-\r
-1, there is chance the containers crash due to random bootstrap order of containers\r
+
+## Build and deploy O2 services over O-Cloud (INF)
+
+
+## Bring up builder container from O-Cloud controller node
+
+
+```sh
+mkdir -p /home/sysadmin/share
+sudo docker run -dt --privileged -v /home/sysadmin/share/:/home/sysadmin/share/ -v /var/run:/var/run --name o2imsbuilder centos:7
+```
+
+## Build O2 service images inside the builder container
+
+
+```sh
+sudo docker exec -it o2imsbuilder bash
+```
+
+
+```sh
+curl -L https://get.daocloud.io/docker/compose/releases/download/1.25.4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
+chmod +x /usr/local/bin/docker-compose
+docker-compose -v
+
+yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
+yum makecache fast
+yum install -y docker-ce
+docker ps
+
+yum install -y git
+
+cd /home/sysadmin/share/
+git clone "https://gerrit.o-ran-sc.org/r/pti/o2"
+cd o2
+
+mkdir -p temp
+cd temp
+git clone --depth 1 --branch master https://opendev.org/starlingx/config.git
+git clone --depth 1 --branch master https://opendev.org/starlingx/distcloud-client.git
+cd -
+
+docker-compose build
+
+exit
+
+```
+
+### Push O2 service images to local registry (with auth user admin)
+
+```sh
+sudo docker tag o2imsdms:latest registry.local:9001/admin/o2imsdms:0.1.4
+sudo docker image push registry.local:9001/admin/o2imsdms:0.1.4
+
+```
+
+## Deploy O2 services with helm chart over O-Cloud controller node (with auth user admin)
+
+```sh
+export NAMESPACE=orano2
+kubectl create ns ${NAMESPACE}
+
+cd /home/sysadmin/
+source /etc/platform/openrc
+cat <<EOF>ocloud-override.yaml
+o2ims:
+ imagePullSecrets: admin-orano2-registry-secret
+ image:
+ repository: registry.local:9001/admin/o2imsdms
+ tag: 0.1.4
+ pullPolicy: IfNotPresent
+ logginglevel: "DEBUG"
+
+ocloud:
+ OS_AUTH_URL: "${OS_AUTH_URL}"
+ OS_USERNAME: "${OS_USERNAME}"
+ OS_PASSWORD: "${OS_PASSWORD}"
+EOF
+
+sudo docker login registry.local:9001 -u ${OS_PROJECT_NAME} -p ${OS_PASSWORD}
+
+kubectl -n ${NAMESPACE} create secret docker-registry ${OS_PROJECT_NAME}-${NAMESPACE}-registry-secret \
+--docker-server=registry.local:9001 --docker-username=${OS_PROJECT_NAME} \
+--docker-password=${OS_PASSWORD} --docker-email=noreply@windriver.com
+
+cd /home/sysadmin/share/o2
+
+helm install o2imstest charts/ -f /home/sysadmin/ocloud-override.yaml
+
+kubectl -n ${NAMESPACE} get pods
+
+```
+
+### test api endpoint
+
+```sh
+curl -k http(s)://<Node IP>:30205
+curl -k http(s)://<Node IP>:30205/o2ims_infrastructureInventory/v1
+```
+
+
+### Debug tips
+
+```sh
+kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c o2api
+kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c postgres
+kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c o2pubsub
+kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c watcher
+
+
+kubectl -n ${NAMESPACE} logs -f o2api-<xxx> -c o2api
+
+kubectl -n ${NAMESPACE} exec -it o2api-<xxx> -c postgres -- bash
+ psql -U o2ims
+
+ \c o2ims
+
+ \d
+
+ select * from ocloud;
+
+ \q
+
+ exit
+
+```
+
+## Issues:
+
+1, there is chance the containers crash due to random bootstrap order of containers
-## Building containers\r
-\r
-To accommodate the git repo access issue, the cgts-client and distributed client are\r
-cloned into temp before docker building\r
-\r
-```sh\r
-mkdir -p temp\r
-cd temp\r
-git clone --depth 1 --branch master https://opendev.org/starlingx/config.git\r
-git clone --depth 1 --branch master https://opendev.org/starlingx/distcloud-client.git\r
-cd -\r
-```\r
-\r
-```sh\r
-docker-compose build\r
-```\r
-\r
-## Running the tests\r
-\r
-\r
-```sh\r
-source ./admin_openrc.sh\r
-export |grep OS_AUTH_URL\r
-export |grep OS_USERNAME\r
-export |grep OS_PASSWORD\r
-docker-compose up -d\r
-docker-compose run --rm --no-deps --entrypoint=pytest api /tests/unit /tests/integration\r
-```\r
-\r
-## Running the tests with a O-Cloud\r
-\r
-Prerequisite: in case of testing against real ocloud, download openrc file from ocloud dashboard, e.g. \r
-\r
-```sh\r
-admin_openrc.sh\r
-docker-compose run --rm --no-deps --entrypoint=pytest api /tests/unit /tests/integration-ocloud\r
-\r
-docker-compose run --rm --no-deps --entrypoint=pytest api /tests/integration-ocloud --log-level=DEBUG --log-file=/test\r
-s/debug.log\r
-```\r
-\r
-## Tear down containers\r
-\r
-```sh\r
-docker-compose down --remove-orphans\r
-```\r
-\r
-## Test with local virtualenv\r
-\r
-```sh\r
-python3.8 -m venv .venv && source .venv/bin/activate\r
-pip install -r requirements.txt -c constraints.txt\r
-pip install -r requirements-test.txt\r
-pip install -e o2ims\r
-# pip install -e o2dms -e o2common\r
-pytest tests/unit\r
-pytest tests/integration\r
-pytest tests/e2e\r
-```\r
-\r
-\r
-Test O2DMS with docker-compose\r
-==============================\r
-\r
-## setup account over INF and get token\r
-\r
-```sh\r
-USER="admin-user"\r
-NAMESPACE="kube-system"\r
-\r
-cat <<EOF > admin-login.yaml\r
-apiVersion: v1\r
-kind: ServiceAccount\r
-metadata:\r
- name: ${USER}\r
- namespace: kube-system\r
----\r
-apiVersion: rbac.authorization.k8s.io/v1\r
-kind: ClusterRoleBinding\r
-metadata:\r
- name: ${USER}\r
-roleRef:\r
- apiGroup: rbac.authorization.k8s.io\r
- kind: ClusterRole\r
- name: cluster-admin\r
-subjects:\r
-- kind: ServiceAccount\r
- name: ${USER}\r
- namespace: kube-system\r
-EOF\r
-kubectl apply -f admin-login.yaml\r
-TOKEN_DATA=$(kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep ${USER} | awk '{print $1}') | grep "token:" | awk '{print $2}')\r
-\r
-```\r
-\r
-## setup remote cli to access kubenetes cluster over INF\r
-\r
-```sh\r
-sudo apt-get install -y apt-transport-https\r
-echo "deb http://mirrors.ustc.edu.cn/kubernetes/apt kubernetes-xenial main" | \\r
-sudo tee -a /etc/apt/sources.list.d/kubernetes.list\r
-sudo apt-get update\r
-sudo apt-get install -y kubectl\r
-\r
-source <(kubectl completion bash) # setup autocomplete in bash into the current shell, bash-completion package should be installed first.\r
-echo "source <(kubectl completion bash)" >> ~/.bashrc # add autocomplete permanently to your bash shell.\r
-\r
-https://get.helm.sh/helm-v3.5.3-linux-amd64.tar.gz\r
-tar xvf helm-v3.5.3-linux-amd64.tar.gz\r
-sudo cp linux-amd64/helm /usr/local/bin\r
-\r
-source <(helm completion bash)\r
-echo "source <(helm completion bash)" >> ~/.bashrc\r
-\r
-OAM_IP=<INF OAM IP>\r
-NAMESPACE=default\r
-TOKEN_DATA=<TOKEN_DATA from INF>\r
-\r
-USER="admin-user"\r
-\r
-kubectl config set-cluster inf-cluster --server=https://${OAM_IP}:6443 --insecure-skip-tls-verify\r
-kubectl config set-credentials ${USER} --token=$TOKEN_DATA\r
-kubectl config set-context ${USER}@inf-cluster --cluster=inf-cluster --user ${USER} --namespace=${NAMESPACE}\r
-kubectl config use-context ${USER}@inf-cluster\r
-\r
-kubectl get pods -A\r
-\r
-```\r
-\r
-\r
-## setup local repo: o2imsrepo\r
-\r
-```sh\r
-helm repo add chartmuseum https://chartmuseum.github.io/charts\r
-helm repo update\r
-helm pull chartmuseum/chartmuseum # download chartmuseum-3.4.0.tgz to local\r
-tar zxvf chartmuseum-3.4.0.tgz\r
-\r
-export NODE_IP=<INF OAM IP>\r
-\r
-cat <<EOF>chartmuseum-override.yaml\r
-env:\r
- open:\r
- DISABLE_API: false\r
-service:\r
- type: NodePort\r
- nodePort: 30330\r
-EOF\r
-\r
-helm install chartmuseumrepo chartmuseum/chartmuseum -f chartmuseum-override.yaml\r
-kubectl get pods\r
-Kubectl get services\r
-\r
-helm repo add o2imsrepo http://${NODE_IP}:30330\r
-helm repo update\r
-\r
-helm repo add bitnami https://charts.bitnami.com/bitnami\r
-helm repo update\r
-\r
-helm pull bitnami/mysql\r
-helm push mysql-8.8.16.tgz o2imsrepo\r
-helm repo update\r
-\r
-helm install my-release o2imsrepo/mysql\r
-kubectl get pods\r
-helm del my-release\r
-\r
-```\r
-\r
-\r
-\r
-## Verify CFW over INF: Test with cnf firewall-host-netdevice\r
-\r
-## Setup host netdevice over INF\r
-\r
-```sh\r
-ssh sysadmin@<inf oam IP>\r
-sudo ip link add name veth11 type veth peer name veth12\r
-sudo ip link add name veth21 type veth peer name veth22\r
-sudo ip link |grep veth\r
-exit\r
-```\r
-\r
-\r
-## verify CNF over INF\r
-```sh\r
-git clone https://github.com/biny993/firewall-host-netdevice.git\r
-\r
-cat <<EOF> cfw-hostdev-override.yaml\r
-\r
-image:\r
- repository: ubuntu\r
- tag: 18.04\r
- pullPolicy: IfNotPresent\r
-\r
-resources:\r
- cpu: 2\r
- memory: 2Gi\r
- hugepage: 256Mi\r
-\r
-#global vars for parent and subcharts.\r
-\r
-\r
- unprotectedNetPortVpg: veth11\r
- unprotectedNetPortVfw: veth12\r
- unprotectedNetCidr: 10.10.1.0/24\r
- unprotectedNetGwIp: 10.10.1.1\r
-\r
- protectedNetPortVfw: veth21\r
- protectedNetPortVsn: veth22\r
- protectedNetCidr: 10.10.2.0/24\r
- protectedNetGwIp: 10.10.2.1\r
-\r
- vfwPrivateIp0: 10.10.1.1\r
- vfwPrivateIp1: 10.10.2.1\r
-\r
- vpgPrivateIp0: 10.10.1.2\r
-\r
- vsnPrivateIp0: 10.10.2.2\r
-\r
-EOF\r
-\r
-helm install cfw1 firewall-host-netdevice -f cfw-hostdev-override.yaml\r
-kubectl get pods\r
-helm del cfw1\r
-```\r
-\r
-## push repo to o2imsrepo\r
-\r
-```sh\r
-tar -zcvf firewall-host-netdevice-1.0.0.tgz firewall-host-netdevice/\r
-helm push firewall-host-netdevice-1.0.0.tgz o2imsrepo\r
-helm repo update\r
-helm search repo firewall\r
-\r
-helm install cfw1 o2imsrepo/firewall-host-netdevice -f cfw-hostdev-override.yaml\r
-kubectl get pods\r
-helm del cfw1\r
-```\r
-\r
-## build docker image for o2 services\r
-```sh\r
-cd o2\r
-docker-compose build\r
-\r
-```\r
-\r
-## bootstrap o2 service with docker-compose\r
-```sh\r
-\r
-mkdir -p temp/kubeconfig/\r
-cp <your .kube/config> temp/kubeconfig/\r
-\r
-source ./admin_openrc.sh\r
-export K8S_KUBECONFIG=/etc/kubeconfig/config\r
-docker-compose up -d\r
-docker logs -f o2_redis_pubsub_1\r
-\r
-```\r
-\r
-## simiulate SMO to deploy CFW\r
-\r
-```sh\r
-\r
-curl --location --request GET 'http://localhost:5005/o2ims_infrastructureInventory/v1/deploymentManagers'\r
-export dmsId=<DMS ID>\r
-curl --location --request POST 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeploymentDescriptor' \\r
---header 'Content-Type: application/json' \\r
---data-raw '{\r
- "name": "cfwdesc1",\r
- "description": "demo nf deployment descriptor",\r
- "artifactRepoUrl": "http://128.224.115.15:30330",\r
- "artifactName": "firewall-host-netdevice",\r
- "inputParams": \r
- "{\n \"image\": {\n \"repository\": \"ubuntu\",\n \"tag\": 18.04,\n \"pullPolicy\": \"IfNotPresent\"\n },\n \"resources\": {\n \"cpu\": 2,\n \"memory\": \"2Gi\",\n \"hugepage\": \"256Mi\",\n \"unprotectedNetPortVpg\": \"veth11\",\n \"unprotectedNetPortVfw\": \"veth12\",\n \"unprotectedNetCidr\": \"10.10.1.0/24\",\n \"unprotectedNetGwIp\": \"10.10.1.1\",\n \"protectedNetPortVfw\": \"veth21\",\n \"protectedNetPortVsn\": \"veth22\",\n \"protectedNetCidr\": \"10.10.2.0/24\",\n \"protectedNetGwIp\": \"10.10.2.1\",\n \"vfwPrivateIp0\": \"10.10.1.1\",\n \"vfwPrivateIp1\": \"10.10.2.1\",\n \"vpgPrivateIp0\": \"10.10.1.2\",\n \"vsnPrivateIp0\": \"10.10.2.2\"\n }\n}",\r
- "outputParams": "{\"output1\": 100}"\r
-}'\r
-\r
-curl --location --request GET 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeploymentDescriptor'\r
-\r
-curl --location --request POST 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeployment' \\r
---header 'Content-Type: application/json' \\r
---data-raw '{\r
- "name": "cfw100",\r
- "description": "demo nf deployment",\r
- "descriptorId": "<NfDeploymentDescriptorId>",\r
- "parentDeploymentId": ""\r
-}'\r
-\r
-curl --location --request GET 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeployment'\r
-\r
-export NfDeploymentId=<NfDeployment Id>\r
-\r
-```\r
-\r
-## check logs\r
-\r
-```sh\r
-docker logs -f o2_redis_pubsub_1\r
-kubectl get pods\r
-kubectl logs -f cfw100-sink-host-netdevice-59bf6fbd4b-845p4\r
-```\r
-\r
-## watch traffic stats\r
-\r
-open browswer with url: http://<NODE_IP>:30667\r
-\r
-\r
-## bring down CFW\r
-\r
-```sh\r
-curl --location --request DELETE 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeployment/${NfDeploymentId}'\r
-```\r
+## Building containers
+
+To accommodate the git repo access issue, the cgts-client and distributed client are
+cloned into temp before docker building
+
+```sh
+mkdir -p temp
+cd temp
+git clone --depth 1 --branch master https://opendev.org/starlingx/config.git
+git clone --depth 1 --branch master https://opendev.org/starlingx/distcloud-client.git
+cd -
+```
+
+```sh
+docker-compose build
+```
+
+## Running the tests
+
+
+```sh
+source ./admin_openrc.sh
+export |grep OS_AUTH_URL
+export |grep OS_USERNAME
+export |grep OS_PASSWORD
+docker-compose up -d
+docker-compose run --rm --no-deps --entrypoint=pytest api /tests/unit /tests/integration
+```
+
+## Running the tests with a O-Cloud
+
+Prerequisite: in case of testing against real ocloud, download openrc file from ocloud dashboard, e.g.
+
+```sh
+admin_openrc.sh
+docker-compose run --rm --no-deps --entrypoint=pytest api /tests/unit /tests/integration-ocloud
+
+docker-compose run --rm --no-deps --entrypoint=pytest api /tests/integration-ocloud --log-level=DEBUG --log-file=/test
+s/debug.log
+```
+
+## Tear down containers
+
+```sh
+docker-compose down --remove-orphans
+```
+
+## Test with local virtualenv
+
+```sh
+python3.8 -m venv .venv && source .venv/bin/activate
+pip install -r requirements.txt -c constraints.txt
+pip install -r requirements-test.txt
+pip install -e o2ims
+# pip install -e o2dms -e o2common
+pytest tests/unit
+pytest tests/integration
+pytest tests/e2e
+```
+
+
+Test O2DMS with docker-compose
+==============================
+
+## setup account over INF and get token
+
+```sh
+USER="admin-user"
+NAMESPACE="kube-system"
+
+cat <<EOF > admin-login.yaml
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: ${USER}
+ namespace: kube-system
+---
+apiVersion: rbac.authorization.k8s.io/v1
+kind: ClusterRoleBinding
+metadata:
+ name: ${USER}
+roleRef:
+ apiGroup: rbac.authorization.k8s.io
+ kind: ClusterRole
+ name: cluster-admin
+subjects:
+- kind: ServiceAccount
+ name: ${USER}
+ namespace: kube-system
+EOF
+kubectl apply -f admin-login.yaml
+TOKEN_DATA=$(kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep ${USER} | awk '{print $1}') | grep "token:" | awk '{print $2}')
+
+```
+
+## setup remote cli to access kubenetes cluster over INF
+
+```sh
+sudo apt-get install -y apt-transport-https
+echo "deb http://mirrors.ustc.edu.cn/kubernetes/apt kubernetes-xenial main" | \
+sudo tee -a /etc/apt/sources.list.d/kubernetes.list
+sudo apt-get update
+sudo apt-get install -y kubectl
+
+source <(kubectl completion bash) # setup autocomplete in bash into the current shell, bash-completion package should be installed first.
+echo "source <(kubectl completion bash)" >> ~/.bashrc # add autocomplete permanently to your bash shell.
+
+https://get.helm.sh/helm-v3.5.3-linux-amd64.tar.gz
+tar xvf helm-v3.5.3-linux-amd64.tar.gz
+sudo cp linux-amd64/helm /usr/local/bin
+
+source <(helm completion bash)
+echo "source <(helm completion bash)" >> ~/.bashrc
+
+OAM_IP=<INF OAM IP>
+NAMESPACE=default
+TOKEN_DATA=<TOKEN_DATA from INF>
+
+USER="admin-user"
+
+kubectl config set-cluster inf-cluster --server=https://${OAM_IP}:6443 --insecure-skip-tls-verify
+kubectl config set-credentials ${USER} --token=$TOKEN_DATA
+kubectl config set-context ${USER}@inf-cluster --cluster=inf-cluster --user ${USER} --namespace=${NAMESPACE}
+kubectl config use-context ${USER}@inf-cluster
+
+kubectl get pods -A
+
+```
+
+
+## setup local repo: o2imsrepo
+
+```sh
+helm repo add chartmuseum https://chartmuseum.github.io/charts
+helm repo update
+helm pull chartmuseum/chartmuseum # download chartmuseum-3.4.0.tgz to local
+tar zxvf chartmuseum-3.4.0.tgz
+
+export NODE_IP=<INF OAM IP>
+
+cat <<EOF>chartmuseum-override.yaml
+env:
+ open:
+ DISABLE_API: false
+service:
+ type: NodePort
+ nodePort: 30330
+EOF
+
+helm install chartmuseumrepo chartmuseum/chartmuseum -f chartmuseum-override.yaml
+kubectl get pods
+Kubectl get services
+
+helm repo add o2imsrepo http://${NODE_IP}:30330
+helm repo update
+
+helm repo add bitnami https://charts.bitnami.com/bitnami
+helm repo update
+
+helm pull bitnami/mysql
+helm push mysql-8.8.16.tgz o2imsrepo
+helm repo update
+
+helm install my-release o2imsrepo/mysql
+kubectl get pods
+helm del my-release
+
+```
+
+
+
+## Verify CFW over INF: Test with cnf firewall-host-netdevice
+
+## Setup host netdevice over INF
+
+```sh
+ssh sysadmin@<inf oam IP>
+sudo ip link add name veth11 type veth peer name veth12
+sudo ip link add name veth21 type veth peer name veth22
+sudo ip link |grep veth
+exit
+```
+
+
+## verify CNF over INF
+```sh
+git clone https://github.com/biny993/firewall-host-netdevice.git
+
+cat <<EOF> cfw-hostdev-override.yaml
+
+image:
+ repository: ubuntu
+ tag: 18.04
+ pullPolicy: IfNotPresent
+
+resources:
+ cpu: 2
+ memory: 2Gi
+ hugepage: 256Mi
+
+#global vars for parent and subcharts.
+
+
+ unprotectedNetPortVpg: veth11
+ unprotectedNetPortVfw: veth12
+ unprotectedNetCidr: 10.10.1.0/24
+ unprotectedNetGwIp: 10.10.1.1
+
+ protectedNetPortVfw: veth21
+ protectedNetPortVsn: veth22
+ protectedNetCidr: 10.10.2.0/24
+ protectedNetGwIp: 10.10.2.1
+
+ vfwPrivateIp0: 10.10.1.1
+ vfwPrivateIp1: 10.10.2.1
+
+ vpgPrivateIp0: 10.10.1.2
+
+ vsnPrivateIp0: 10.10.2.2
+
+EOF
+
+helm install cfw1 firewall-host-netdevice -f cfw-hostdev-override.yaml
+kubectl get pods
+helm del cfw1
+```
+
+## push repo to o2imsrepo
+
+```sh
+tar -zcvf firewall-host-netdevice-1.0.0.tgz firewall-host-netdevice/
+helm push firewall-host-netdevice-1.0.0.tgz o2imsrepo
+helm repo update
+helm search repo firewall
+
+helm install cfw1 o2imsrepo/firewall-host-netdevice -f cfw-hostdev-override.yaml
+kubectl get pods
+helm del cfw1
+```
+
+## build docker image for o2 services
+```sh
+cd o2
+docker-compose build
+
+```
+
+## bootstrap o2 service with docker-compose
+```sh
+
+mkdir -p temp/kubeconfig/
+cp <your .kube/config> temp/kubeconfig/
+
+source ./admin_openrc.sh
+export K8S_KUBECONFIG=/etc/kubeconfig/config
+docker-compose up -d
+docker logs -f o2_redis_pubsub_1
+
+```
+
+## simiulate SMO to deploy CFW
+
+```sh
+
+curl --location --request GET 'http://localhost:5005/o2ims_infrastructureInventory/v1/deploymentManagers'
+export dmsId=<DMS ID>
+curl --location --request POST 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeploymentDescriptor' \
+--header 'Content-Type: application/json' \
+--data-raw '{
+ "name": "cfwdesc1",
+ "description": "demo nf deployment descriptor",
+ "artifactRepoUrl": "http://128.224.115.15:30330",
+ "artifactName": "firewall-host-netdevice",
+ "inputParams":
+ "{\n \"image\": {\n \"repository\": \"ubuntu\",\n \"tag\": 18.04,\n \"pullPolicy\": \"IfNotPresent\"\n },\n \"resources\": {\n \"cpu\": 2,\n \"memory\": \"2Gi\",\n \"hugepage\": \"256Mi\",\n \"unprotectedNetPortVpg\": \"veth11\",\n \"unprotectedNetPortVfw\": \"veth12\",\n \"unprotectedNetCidr\": \"10.10.1.0/24\",\n \"unprotectedNetGwIp\": \"10.10.1.1\",\n \"protectedNetPortVfw\": \"veth21\",\n \"protectedNetPortVsn\": \"veth22\",\n \"protectedNetCidr\": \"10.10.2.0/24\",\n \"protectedNetGwIp\": \"10.10.2.1\",\n \"vfwPrivateIp0\": \"10.10.1.1\",\n \"vfwPrivateIp1\": \"10.10.2.1\",\n \"vpgPrivateIp0\": \"10.10.1.2\",\n \"vsnPrivateIp0\": \"10.10.2.2\"\n }\n}",
+ "outputParams": "{\"output1\": 100}"
+}'
+
+curl --location --request GET 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeploymentDescriptor'
+
+curl --location --request POST 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeployment' \
+--header 'Content-Type: application/json' \
+--data-raw '{
+ "name": "cfw100",
+ "description": "demo nf deployment",
+ "descriptorId": "<NfDeploymentDescriptorId>",
+ "parentDeploymentId": ""
+}'
+
+curl --location --request GET 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeployment'
+
+export NfDeploymentId=<NfDeployment Id>
+
+```
+
+## check logs
+
+```sh
+docker logs -f o2_redis_pubsub_1
+kubectl get pods
+kubectl logs -f cfw100-sink-host-netdevice-59bf6fbd4b-845p4
+```
+
+## watch traffic stats
+
+open browswer with url: http://<NODE_IP>:30667
+
+
+## bring down CFW
+
+```sh
+curl --location --request DELETE 'http://localhost:5005/o2dms/v1/${dmsId}/O2dms_DeploymentLifecycle/NfDeployment/${NfDeploymentId}'
+```
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
----\r
-apiVersion: apps/v1\r
-kind: Deployment\r
-metadata:\r
- name: o2api\r
- namespace: {{ .Values.global.namespace }}\r
- labels:\r
- app: o2api\r
-spec:\r
- replicas: 1\r
- selector:\r
- matchLabels:\r
- app: o2api\r
- template:\r
- metadata:\r
- labels:\r
- app: o2api\r
- spec:\r
- imagePullSecrets:\r
- - name: {{ .Values.o2ims.imagePullSecrets }}\r
-{{- if .Values.o2ims.affinity }}\r
- affinity:\r
-{{ toYaml .Values.o2ims.affinity | indent 8 }}\r
-{{- end }}\r
- containers:\r
- - name: postgres\r
- image: postgres:9.6\r
- ports:\r
- - containerPort: 5432\r
- env:\r
- - name: POSTGRES_PASSWORD\r
- value: o2ims123\r
- - name: POSTGRES_USER\r
- value: o2ims\r
- command: ["/bin/bash", "/opt/postgres_start.sh"]\r
- volumeMounts:\r
- - name: scripts\r
- mountPath: /opt\r
- - name: redis\r
- image: redis:alpine\r
- ports:\r
- - containerPort: 6379\r
- - name: o2pubsub\r
- image: "{{ .Values.o2ims.image.repository }}:{{ .Values.o2ims.image.tag }}"\r
- command: ["/bin/bash", "/opt/o2pubsub_start.sh"]\r
- env:\r
- - name: DB_HOST\r
- value: postgres\r
- - name: DB_PASSWORD\r
- value: o2ims123\r
- - name: LOGGING_CONFIG_LEVEL\r
- value: {{ .Values.o2ims.logginglevel }}\r
- - name: OS_AUTH_URL\r
- value: {{ .Values.ocloud.OS_AUTH_URL }}\r
- - name: OS_PASSWORD\r
- value: {{ .Values.ocloud.OS_PASSWORD }}\r
- - name: OS_USERNAME\r
- value: {{ .Values.ocloud.OS_USERNAME }}\r
- - name: PYTHONDONTWRITEBYTECODE\r
- value: "1"\r
- - name: REDIS_HOST\r
- value: redis\r
- - name: K8S_KUBECONFIG\r
- value: {{ .Values.ocloud.K8S_KUBECONFIG }}\r
- volumeMounts:\r
- - name: scripts\r
- mountPath: /opt\r
- - name: watcher\r
- image: "{{ .Values.o2ims.image.repository }}:{{ .Values.o2ims.image.tag }}"\r
- command: ["/bin/bash", "/opt/o2watcher_start.sh"]\r
- env:\r
- - name: API_HOST_EXTERNAL_FLOATING\r
- value: {{ .Values.ocloud.API_HOST_EXTERNAL_FLOATING }}\r
- - name: DB_HOST\r
- value: postgres\r
- - name: DB_PASSWORD\r
- value: o2ims123\r
- - name: LOGGING_CONFIG_LEVEL\r
- value: {{ .Values.o2ims.logginglevel }}\r
- - name: OS_AUTH_URL\r
- value: {{ .Values.ocloud.OS_AUTH_URL }}\r
- - name: OS_PASSWORD\r
- value: {{ .Values.ocloud.OS_PASSWORD }}\r
- - name: OS_USERNAME\r
- value: {{ .Values.ocloud.OS_USERNAME }}\r
- - name: PYTHONDONTWRITEBYTECODE\r
- value: "1"\r
- - name: REDIS_HOST\r
- value: redis\r
- volumeMounts:\r
- - name: scripts\r
- mountPath: /opt\r
- - name: o2api\r
- image: "{{ .Values.o2ims.image.repository }}:{{ .Values.o2ims.image.tag }}"\r
- ports:\r
- - containerPort: 80\r
- env:\r
- - name: API_HOST\r
- value: api\r
- - name: DB_HOST\r
- value: postgres\r
- - name: DB_PASSWORD\r
- value: o2ims123\r
- - name: FLASK_APP\r
- value: /root/o2/o2app/entrypoints/flask_application.py\r
- - name: FLASK_DEBUG\r
- value: {{ .Values.o2ims.logginglevel }}\r
- - name: LOGGING_CONFIG_LEVEL\r
- value: {{ .Values.o2ims.logginglevel }}\r
- - name: OS_AUTH_URL\r
- - name: OS_PASSWORD\r
- - name: OS_USERNAME\r
- - name: PYTHONDONTWRITEBYTECODE\r
- value: "1"\r
- - name: PYTHONUNBUFFERED\r
- value: "1"\r
- - name: REDIS_HOST\r
- value: redis\r
- command: ["/bin/bash", "/opt/o2api_start.sh"]\r
- volumeMounts:\r
- - name: scripts\r
- mountPath: /opt\r
- volumes:\r
- - name: scripts\r
- configMap:\r
- name: {{ .Chart.Name }}-scripts-configmap\r
----\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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: apps/v1
+kind: Deployment
+metadata:
+ name: o2api
+ namespace: {{ .Values.global.namespace }}
+ labels:
+ app: o2api
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: o2api
+ template:
+ metadata:
+ labels:
+ app: o2api
+ spec:
+ imagePullSecrets:
+ - name: {{ .Values.o2ims.imagePullSecrets }}
+{{- if .Values.o2ims.affinity }}
+ affinity:
+{{ toYaml .Values.o2ims.affinity | indent 8 }}
+{{- end }}
+ containers:
+ - name: postgres
+ image: postgres:9.6
+ ports:
+ - containerPort: 5432
+ env:
+ - name: POSTGRES_PASSWORD
+ value: o2ims123
+ - name: POSTGRES_USER
+ value: o2ims
+ command: ["/bin/bash", "/opt/postgres_start.sh"]
+ volumeMounts:
+ - name: scripts
+ mountPath: /opt
+ - name: redis
+ image: redis:alpine
+ ports:
+ - containerPort: 6379
+ - name: o2pubsub
+ image: "{{ .Values.o2ims.image.repository }}:{{ .Values.o2ims.image.tag }}"
+ command: ["/bin/bash", "/opt/o2pubsub_start.sh"]
+ env:
+ - name: DB_HOST
+ value: postgres
+ - name: DB_PASSWORD
+ value: o2ims123
+ - name: LOGGING_CONFIG_LEVEL
+ value: {{ .Values.o2ims.logginglevel }}
+ - name: OS_AUTH_URL
+ value: {{ .Values.ocloud.OS_AUTH_URL }}
+ - name: OS_PASSWORD
+ value: {{ .Values.ocloud.OS_PASSWORD }}
+ - name: OS_USERNAME
+ value: {{ .Values.ocloud.OS_USERNAME }}
+ - name: PYTHONDONTWRITEBYTECODE
+ value: "1"
+ - name: REDIS_HOST
+ value: redis
+ - name: K8S_KUBECONFIG
+ value: {{ .Values.ocloud.K8S_KUBECONFIG }}
+ volumeMounts:
+ - name: scripts
+ mountPath: /opt
+ - name: watcher
+ image: "{{ .Values.o2ims.image.repository }}:{{ .Values.o2ims.image.tag }}"
+ command: ["/bin/bash", "/opt/o2watcher_start.sh"]
+ env:
+ - name: API_HOST_EXTERNAL_FLOATING
+ value: {{ .Values.ocloud.API_HOST_EXTERNAL_FLOATING }}
+ - name: DB_HOST
+ value: postgres
+ - name: DB_PASSWORD
+ value: o2ims123
+ - name: LOGGING_CONFIG_LEVEL
+ value: {{ .Values.o2ims.logginglevel }}
+ - name: OS_AUTH_URL
+ value: {{ .Values.ocloud.OS_AUTH_URL }}
+ - name: OS_PASSWORD
+ value: {{ .Values.ocloud.OS_PASSWORD }}
+ - name: OS_USERNAME
+ value: {{ .Values.ocloud.OS_USERNAME }}
+ - name: PYTHONDONTWRITEBYTECODE
+ value: "1"
+ - name: REDIS_HOST
+ value: redis
+ volumeMounts:
+ - name: scripts
+ mountPath: /opt
+ - name: o2api
+ image: "{{ .Values.o2ims.image.repository }}:{{ .Values.o2ims.image.tag }}"
+ ports:
+ - containerPort: 80
+ env:
+ - name: API_HOST
+ value: api
+ - name: DB_HOST
+ value: postgres
+ - name: DB_PASSWORD
+ value: o2ims123
+ - name: FLASK_APP
+ value: /root/o2/o2app/entrypoints/flask_application.py
+ - name: FLASK_DEBUG
+ value: {{ .Values.o2ims.logginglevel }}
+ - name: LOGGING_CONFIG_LEVEL
+ value: {{ .Values.o2ims.logginglevel }}
+ - name: OS_AUTH_URL
+ - name: OS_PASSWORD
+ - name: OS_USERNAME
+ - name: PYTHONDONTWRITEBYTECODE
+ value: "1"
+ - name: PYTHONUNBUFFERED
+ value: "1"
+ - name: REDIS_HOST
+ value: redis
+ command: ["/bin/bash", "/opt/o2api_start.sh"]
+ volumeMounts:
+ - name: scripts
+ mountPath: /opt
+ volumes:
+ - name: scripts
+ configMap:
+ name: {{ .Chart.Name }}-scripts-configmap
+---
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-#\r
----\r
-apiVersion: v1\r
-kind: Service\r
-metadata:\r
- name: o2api\r
- namespace: {{ .Values.global.namespace }}\r
-spec:\r
- type: NodePort\r
- ports:\r
- - name: o2api\r
- port: 5005\r
- targetPort: 80\r
- nodePort: 30205\r
- protocol: TCP\r
- selector:\r
- app: o2api\r
----\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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: Service
+metadata:
+ name: o2api
+ namespace: {{ .Values.global.namespace }}
+spec:
+ type: NodePort
+ ports:
+ - name: o2api
+ port: 5005
+ targetPort: 80
+ nodePort: 30205
+ protocol: TCP
+ selector:
+ app: o2api
+---
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-version: 1\r
-disable_existing_loggers: False\r
-\r
-loggers:\r
- root:\r
- handlers: [console_handler, file_handler]\r
- level: "WARNING"\r
- propagate: False\r
- o2common:\r
- handlers: [console_handler, file_handler]\r
- level: "WARNING"\r
- propagate: False\r
- o2ims:\r
- handlers: [console_handler, file_handler]\r
- level: "DEBUG"\r
- propagate: False\r
- o2dms:\r
- handlers: [console_handler, file_handler]\r
- level: "DEBUG"\r
- propagate: False\r
-handlers:\r
- console_handler:\r
- level: "DEBUG"\r
- class: "logging.StreamHandler"\r
- formatter: "standard"\r
- file_handler:\r
- level: "DEBUG"\r
- class: "logging.handlers.RotatingFileHandler"\r
- filename: "/var/log/o2.log"\r
- formatter: "standard"\r
- maxBytes: 52428800\r
- backupCount: 10\r
-formatters:\r
- standard:\r
- format: "%(asctime)s:[%(name)s]:[%(filename)s]-[%(lineno)d] [%(levelname)s]:%(message)s"\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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.
+
+version: 1
+disable_existing_loggers: False
+
+loggers:
+ root:
+ handlers: [console_handler, file_handler]
+ level: "WARNING"
+ propagate: False
+ o2common:
+ handlers: [console_handler, file_handler]
+ level: "WARNING"
+ propagate: False
+ o2ims:
+ handlers: [console_handler, file_handler]
+ level: "DEBUG"
+ propagate: False
+ o2dms:
+ handlers: [console_handler, file_handler]
+ level: "DEBUG"
+ propagate: False
+handlers:
+ console_handler:
+ level: "DEBUG"
+ class: "logging.StreamHandler"
+ formatter: "standard"
+ file_handler:
+ level: "DEBUG"
+ class: "logging.handlers.RotatingFileHandler"
+ filename: "/var/log/o2.log"
+ formatter: "standard"
+ maxBytes: 52428800
+ backupCount: 10
+formatters:
+ standard:
+ format: "%(asctime)s:[%(name)s]:[%(filename)s]-[%(lineno)d] [%(levelname)s]:%(message)s"
-FROM python:3.10-slim-buster\r
-\r
-RUN apt-get update; apt-get install -y git gcc\r
-\r
-COPY requirements.txt /tmp/\r
-RUN pip install -r /tmp/requirements.txt \r
-\r
-# COPY requirements-test.txt /tmp/\r
-# RUN pip install -r /tmp/requirements-test.txt\r
-\r
-RUN mkdir -p /src\r
-COPY mock_smo/ /src/mock_smo/\r
-\r
-COPY setup.py o2app-mock-smo.sh /src/\r
-RUN pip install -e /src\r
-\r
-COPY etc/ /etc/mock_smo/\r
-\r
-# COPY tests/ /tests/\r
-\r
-# RUN apt-get install -y procps vim\r
-\r
-WORKDIR /src\r
+FROM python:3.10-slim-buster
+
+RUN apt-get update; apt-get install -y git gcc
+
+COPY requirements.txt /tmp/
+RUN pip install -r /tmp/requirements.txt
+
+# COPY requirements-test.txt /tmp/
+# RUN pip install -r /tmp/requirements-test.txt
+
+RUN mkdir -p /src
+COPY mock_smo/ /src/mock_smo/
+
+COPY setup.py o2app-mock-smo.sh /src/
+RUN pip install -e /src
+
+COPY etc/ /etc/mock_smo/
+
+# COPY tests/ /tests/
+
+# RUN apt-get install -y procps vim
+
+WORKDIR /src
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-version: 1\r
-disable_existing_loggers: False\r
-\r
-loggers:\r
- root:\r
- handlers: [console_handler, file_handler]\r
- level: "WARNING"\r
- propagate: False\r
- o2common:\r
- handlers: [console_handler, file_handler]\r
- level: "WARNING"\r
- propagate: False\r
- o2ims:\r
- handlers: [console_handler, file_handler]\r
- level: "DEBUG"\r
- propagate: False\r
- o2dms:\r
- handlers: [console_handler, file_handler]\r
- level: "DEBUG"\r
- propagate: False\r
-handlers:\r
- console_handler:\r
- level: "DEBUG"\r
- class: "logging.StreamHandler"\r
- formatter: "standard"\r
- file_handler:\r
- level: "DEBUG"\r
- class: "logging.handlers.RotatingFileHandler"\r
- filename: "/var/log/mock_smo.log"\r
- formatter: "standard"\r
- maxBytes: 52428800\r
- backupCount: 10\r
-formatters:\r
- standard:\r
- format: "%(asctime)s:[%(name)s]:[%(filename)s]-[%(lineno)d] [%(levelname)s]:%(message)s"\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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.
+
+version: 1
+disable_existing_loggers: False
+
+loggers:
+ root:
+ handlers: [console_handler, file_handler]
+ level: "WARNING"
+ propagate: False
+ o2common:
+ handlers: [console_handler, file_handler]
+ level: "WARNING"
+ propagate: False
+ o2ims:
+ handlers: [console_handler, file_handler]
+ level: "DEBUG"
+ propagate: False
+ o2dms:
+ handlers: [console_handler, file_handler]
+ level: "DEBUG"
+ propagate: False
+handlers:
+ console_handler:
+ level: "DEBUG"
+ class: "logging.StreamHandler"
+ formatter: "standard"
+ file_handler:
+ level: "DEBUG"
+ class: "logging.handlers.RotatingFileHandler"
+ filename: "/var/log/mock_smo.log"
+ formatter: "standard"
+ maxBytes: 52428800
+ backupCount: 10
+formatters:
+ standard:
+ format: "%(asctime)s:[%(name)s]:[%(filename)s]-[%(lineno)d] [%(levelname)s]:%(message)s"
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import json\r
-import redis\r
-import http.client\r
-from flask import Flask, request\r
-from flask.helpers import url_for\r
-\r
-import mock_smo.config as config\r
-import mock_smo.logging as logging\r
-logger = logging.get_logger(__name__)\r
-\r
-apibase = config.get_o2ims_api_base()\r
-app = Flask(__name__)\r
-\r
-r = redis.Redis(**config.get_redis_host_and_port())\r
-REDIS_SUB_KEY = 'mock_smo_sub_key'\r
-REDIS_O2IMS_URL = 'mock_smo_o2ims_url'\r
-\r
-\r
-@app.route('/', methods=['GET', 'POST'])\r
-def index():\r
- if request.method == 'POST':\r
- url = request.form['url']\r
- consumerSubscriptionId = request.form['consumerSubId']\r
- sub_id = subscription_ims(url, consumerSubscriptionId)\r
- return """\r
-<h1>Subscribed O2IMS</h1>\r
-<h3>Subscription ID: %s</h3>\r
-<h3>Subscribed O2IMS URL: %s</h3>\r
-<a href="%s">\r
- <input type="button" value="Unsubscription" />\r
-</a>\r
-""" % (sub_id, url, url_for('unsubscription'))\r
- return """\r
-<h1>Subscribe O2IMS</h1>\r
-<form method="POST">\r
- <label for="url">O2 IMS URL: </label>\r
- <input type="text" id="url" name="url" value="api:80"></br></br>\r
- <label for="consumerSubId">Consumer Sub ID: </label>\r
- <input type="text" id="consumerSubId" name="consumerSubId"></br></br>\r
- <input type="submit" value="Submit">\r
-</form>\r
-"""\r
-\r
-\r
-@app.route('/unsubscription')\r
-def unsubscription():\r
- sub_key = r.get(REDIS_SUB_KEY)\r
- logger.info('Subscription key is {}'.format(sub_key))\r
- if sub_key is None:\r
- return '<h1>Already unsubscribed</h1>'\r
- url = r.get(REDIS_O2IMS_URL).decode('utf-8')\r
- logger.info('O2 IMS API is: {}'.format(url))\r
- unsubscription_ims(url, sub_key.decode('utf-8'))\r
- r.delete(REDIS_O2IMS_URL)\r
- r.delete(REDIS_SUB_KEY)\r
- return """\r
-<h1>Unsubscribed O2IMS</h1>\r
-<a href="/">\r
- <input type="button" value="Go Back" />\r
-</a>\r
-"""\r
-\r
-\r
-@app.route('/callback', methods=['POST'])\r
-def callback():\r
- logger.info('Callback data: {}'.format(request.get_data()))\r
- return '', 202\r
-\r
-\r
-@app.route('/registration', methods=['POST'])\r
-def registration():\r
- logger.info('Registration data: {}'.format(request.get_data()))\r
- return '', 200\r
-\r
-\r
-def subscription_ims(url, consumerSubscriptionId):\r
- sub_key = r.get(REDIS_SUB_KEY)\r
- logger.info('Subscription key is {}'.format(sub_key))\r
- if sub_key is not None:\r
- return sub_key.decode('utf-8')\r
-\r
- logger.info(request.host_url)\r
- conn = http.client.HTTPConnection(url)\r
- headers = {'Content-type': 'application/json'}\r
- post_val = {\r
- 'callback': 'http://mock_smo:80' + url_for('callback'),\r
- 'consumerSubscriptionId': consumerSubscriptionId,\r
- 'filter': '["pserver"]' # '["pserver","pserver_mem"]'\r
- }\r
- json_val = json.dumps(post_val)\r
- conn.request('POST', apibase+'/subscriptions', json_val, headers)\r
- resp = conn.getresponse()\r
- data = resp.read().decode('utf-8')\r
- logger.info('Subscription response: {} {}, data: {}'.format(\r
- resp.status, resp.reason, data))\r
- json_data = json.loads(data)\r
-\r
- r.set(REDIS_SUB_KEY, json_data['subscriptionId'])\r
- r.set(REDIS_O2IMS_URL, url)\r
- return json_data['subscriptionId']\r
-\r
-\r
-def unsubscription_ims(url, subId):\r
- conn = http.client.HTTPConnection(url)\r
- conn.request('DELETE', apibase + '/subscriptions/' + subId)\r
- resp = conn.getresponse()\r
- logger.info('Unsubscription response: {} {}'.format(\r
- resp.status, resp.reason))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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
+import redis
+import http.client
+from flask import Flask, request
+from flask.helpers import url_for
+
+import mock_smo.config as config
+import mock_smo.logging as logging
+logger = logging.get_logger(__name__)
+
+apibase = config.get_o2ims_api_base()
+app = Flask(__name__)
+
+r = redis.Redis(**config.get_redis_host_and_port())
+REDIS_SUB_KEY = 'mock_smo_sub_key'
+REDIS_O2IMS_URL = 'mock_smo_o2ims_url'
+
+
+@app.route('/', methods=['GET', 'POST'])
+def index():
+ if request.method == 'POST':
+ url = request.form['url']
+ consumerSubscriptionId = request.form['consumerSubId']
+ sub_id = subscription_ims(url, consumerSubscriptionId)
+ return """
+<h1>Subscribed O2IMS</h1>
+<h3>Subscription ID: %s</h3>
+<h3>Subscribed O2IMS URL: %s</h3>
+<a href="%s">
+ <input type="button" value="Unsubscription" />
+</a>
+""" % (sub_id, url, url_for('unsubscription'))
+ return """
+<h1>Subscribe O2IMS</h1>
+<form method="POST">
+ <label for="url">O2 IMS URL: </label>
+ <input type="text" id="url" name="url" value="api:80"></br></br>
+ <label for="consumerSubId">Consumer Sub ID: </label>
+ <input type="text" id="consumerSubId" name="consumerSubId"></br></br>
+ <input type="submit" value="Submit">
+</form>
+"""
+
+
+@app.route('/unsubscription')
+def unsubscription():
+ sub_key = r.get(REDIS_SUB_KEY)
+ logger.info('Subscription key is {}'.format(sub_key))
+ if sub_key is None:
+ return '<h1>Already unsubscribed</h1>'
+ url = r.get(REDIS_O2IMS_URL).decode('utf-8')
+ logger.info('O2 IMS API is: {}'.format(url))
+ unsubscription_ims(url, sub_key.decode('utf-8'))
+ r.delete(REDIS_O2IMS_URL)
+ r.delete(REDIS_SUB_KEY)
+ return """
+<h1>Unsubscribed O2IMS</h1>
+<a href="/">
+ <input type="button" value="Go Back" />
+</a>
+"""
+
+
+@app.route('/callback', methods=['POST'])
+def callback():
+ logger.info('Callback data: {}'.format(request.get_data()))
+ return '', 202
+
+
+@app.route('/registration', methods=['POST'])
+def registration():
+ logger.info('Registration data: {}'.format(request.get_data()))
+ return '', 200
+
+
+def subscription_ims(url, consumerSubscriptionId):
+ sub_key = r.get(REDIS_SUB_KEY)
+ logger.info('Subscription key is {}'.format(sub_key))
+ if sub_key is not None:
+ return sub_key.decode('utf-8')
+
+ logger.info(request.host_url)
+ conn = http.client.HTTPConnection(url)
+ headers = {'Content-type': 'application/json'}
+ post_val = {
+ 'callback': 'http://mock_smo:80' + url_for('callback'),
+ 'consumerSubscriptionId': consumerSubscriptionId,
+ 'filter': '["pserver"]' # '["pserver","pserver_mem"]'
+ }
+ json_val = json.dumps(post_val)
+ conn.request('POST', apibase+'/subscriptions', json_val, headers)
+ resp = conn.getresponse()
+ data = resp.read().decode('utf-8')
+ logger.info('Subscription response: {} {}, data: {}'.format(
+ resp.status, resp.reason, data))
+ json_data = json.loads(data)
+
+ r.set(REDIS_SUB_KEY, json_data['subscriptionId'])
+ r.set(REDIS_O2IMS_URL, url)
+ return json_data['subscriptionId']
+
+
+def unsubscription_ims(url, subId):
+ conn = http.client.HTTPConnection(url)
+ conn.request('DELETE', apibase + '/subscriptions/' + subId)
+ resp = conn.getresponse()
+ logger.info('Unsubscription response: {} {}'.format(
+ resp.status, resp.reason))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import logging\r
-import logging.config\r
-import logging.handlers\r
-import os\r
-import yaml\r
-\r
-\r
-def get_logger(name=None):\r
- CONFIG_FILE = os.environ.get(\r
- "LOGGING_CONFIG_FILE", "/etc/mock_smo/log.yaml")\r
- if os.path.exists(CONFIG_FILE):\r
- with open(file=CONFIG_FILE, mode='r', encoding="utf-8") as file:\r
- config_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)\r
- logging.config.dictConfig(config=config_yaml)\r
-\r
- logger = logging.getLogger(name)\r
-\r
- # override logging level\r
- LOGGING_CONFIG_LEVEL = os.environ.get("LOGGING_CONFIG_LEVEL", None)\r
- if LOGGING_CONFIG_LEVEL:\r
- logger.setLevel(LOGGING_CONFIG_LEVEL)\r
- return logger\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 logging
+import logging.config
+import logging.handlers
+import os
+import yaml
+
+
+def get_logger(name=None):
+ CONFIG_FILE = os.environ.get(
+ "LOGGING_CONFIG_FILE", "/etc/mock_smo/log.yaml")
+ if os.path.exists(CONFIG_FILE):
+ with open(file=CONFIG_FILE, mode='r', encoding="utf-8") as file:
+ config_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)
+ logging.config.dictConfig(config=config_yaml)
+
+ logger = logging.getLogger(name)
+
+ # override logging level
+ LOGGING_CONFIG_LEVEL = os.environ.get("LOGGING_CONFIG_LEVEL", None)
+ if LOGGING_CONFIG_LEVEL:
+ logger.setLevel(LOGGING_CONFIG_LEVEL)
+ return logger
-flask\r
-flask-restx\r
-redis\r
-PyYAML>=5.4.1\r
-\r
+flask
+flask-restx
+redis
+PyYAML>=5.4.1
+
-from setuptools import setup\r
-from setuptools import find_packages\r
-\r
-setup(\r
- name="mock_smo",\r
- version="1.0",\r
- packages=find_packages(),\r
- license="LICENSE",\r
- description="Mock SMO server for O2 IMS and DMS",\r
- install_requires=[\r
- 'httplib2',\r
- ]\r
-)\r
+from setuptools import setup
+from setuptools import find_packages
+
+setup(
+ name="mock_smo",
+ version="1.0",
+ packages=find_packages(),
+ license="LICENSE",
+ description="Mock SMO server for O2 IMS and DMS",
+ install_requires=[
+ 'httplib2',
+ ]
+)
-[mypy]\r
-ignore_missing_imports = False\r
-mypy_path = ./src\r
-check_untyped_defs = True\r
-\r
-[mypy-pytest.*,sqlalchemy.*,redis.*]\r
-ignore_missing_imports = True\r
+[mypy]
+ignore_missing_imports = False
+mypy_path = ./src
+check_untyped_defs = True
+
+[mypy-pytest.*,sqlalchemy.*,redis.*]
+ignore_missing_imports = True
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# pylint: disable=attribute-defined-outside-init\r
-from __future__ import annotations\r
-from sqlalchemy import create_engine\r
-from sqlalchemy.orm import sessionmaker\r
-from sqlalchemy.orm.session import Session\r
-\r
-from o2common.config import config\r
-from o2common.service.unit_of_work import AbstractUnitOfWork\r
-\r
-from o2ims.adapter import ocloud_repository\r
-from o2dms.adapter import dms_repository\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-engine = create_engine(\r
- config.get_postgres_uri(),\r
- isolation_level="REPEATABLE READ",\r
- pool_size=200, max_overflow=0,\r
- pool_recycle=3600\r
-)\r
-\r
-DEFAULT_SESSION_FACTORY = sessionmaker(\r
- autocommit=False, autoflush=False, bind=engine\r
-)\r
-\r
-\r
-class SqlAlchemyUnitOfWork(AbstractUnitOfWork):\r
-\r
- def __init__(self, session_factory=DEFAULT_SESSION_FACTORY):\r
- self.session_factory = session_factory\r
-\r
- def __enter__(self):\r
- self.session = self.session_factory() # type: Session\r
- self.oclouds = ocloud_repository\\r
- .OcloudSqlAlchemyRepository(self.session)\r
- self.resource_types = ocloud_repository\\r
- .ResouceTypeSqlAlchemyRepository(self.session)\r
- self.resource_pools = ocloud_repository\\r
- .ResourcePoolSqlAlchemyRepository(self.session)\r
- self.resources = ocloud_repository\\r
- .ResourceSqlAlchemyRepository(self.session)\r
- self.subscriptions = ocloud_repository\\r
- .SubscriptionSqlAlchemyRepository(self.session)\r
- self.configurations = ocloud_repository\\r
- .ConfigurationSqlAlchemyRepository(self.session)\r
- self.deployment_managers = ocloud_repository\\r
- .DeploymentManagerSqlAlchemyRepository(self.session)\r
- self.nfdeployment_descs = dms_repository\\r
- .NfDeploymentDescSqlAlchemyRepository(self.session)\r
- self.nfdeployments = dms_repository\\r
- .NfDeploymentSqlAlchemyRepository(self.session)\r
- self.ocloudvresources = dms_repository\\r
- .NfOCloudVResourceSqlAlchemyRepository(self.session)\r
- return super().__enter__()\r
-\r
- def __exit__(self, *args):\r
- super().__exit__(*args)\r
- self.session.close()\r
-\r
- def _commit(self):\r
- self.session.commit()\r
-\r
- def rollback(self):\r
- self.session.rollback()\r
-\r
- def _collect_new_events(self):\r
- for entry in self.oclouds.seen:\r
- # while hasattr(entry, 'events') and len(entry.events) > 0:\r
- while entry.events is not None and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.resource_pools.seen:\r
- while entry.events is not None and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.resources.seen:\r
- while entry.events is not None and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.resource_types.seen:\r
- while hasattr(entry, 'events') and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.deployment_managers.seen:\r
- while hasattr(entry, 'events') and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.subscriptions.seen:\r
- while hasattr(entry, 'events') and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.configurations.seen:\r
- while hasattr(entry, 'events') and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.nfdeployment_descs.seen:\r
- while hasattr(entry, 'events') and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.nfdeployments.seen:\r
- while hasattr(entry, 'events') and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
- for entry in self.ocloudvresources.seen:\r
- while hasattr(entry, 'events') and len(entry.events) > 0:\r
- yield entry.events.pop(0)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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.
+
+# pylint: disable=attribute-defined-outside-init
+from __future__ import annotations
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.orm.session import Session
+
+from o2common.config import config
+from o2common.service.unit_of_work import AbstractUnitOfWork
+
+from o2ims.adapter import ocloud_repository
+from o2dms.adapter import dms_repository
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+engine = create_engine(
+ config.get_postgres_uri(),
+ isolation_level="REPEATABLE READ",
+ pool_size=200, max_overflow=0,
+ pool_recycle=3600
+)
+
+DEFAULT_SESSION_FACTORY = sessionmaker(
+ autocommit=False, autoflush=False, bind=engine
+)
+
+
+class SqlAlchemyUnitOfWork(AbstractUnitOfWork):
+
+ def __init__(self, session_factory=DEFAULT_SESSION_FACTORY):
+ self.session_factory = session_factory
+
+ def __enter__(self):
+ self.session = self.session_factory() # type: Session
+ self.oclouds = ocloud_repository\
+ .OcloudSqlAlchemyRepository(self.session)
+ self.resource_types = ocloud_repository\
+ .ResouceTypeSqlAlchemyRepository(self.session)
+ self.resource_pools = ocloud_repository\
+ .ResourcePoolSqlAlchemyRepository(self.session)
+ self.resources = ocloud_repository\
+ .ResourceSqlAlchemyRepository(self.session)
+ self.subscriptions = ocloud_repository\
+ .SubscriptionSqlAlchemyRepository(self.session)
+ self.configurations = ocloud_repository\
+ .ConfigurationSqlAlchemyRepository(self.session)
+ self.deployment_managers = ocloud_repository\
+ .DeploymentManagerSqlAlchemyRepository(self.session)
+ self.nfdeployment_descs = dms_repository\
+ .NfDeploymentDescSqlAlchemyRepository(self.session)
+ self.nfdeployments = dms_repository\
+ .NfDeploymentSqlAlchemyRepository(self.session)
+ self.ocloudvresources = dms_repository\
+ .NfOCloudVResourceSqlAlchemyRepository(self.session)
+ return super().__enter__()
+
+ def __exit__(self, *args):
+ super().__exit__(*args)
+ self.session.close()
+
+ def _commit(self):
+ self.session.commit()
+
+ def rollback(self):
+ self.session.rollback()
+
+ def _collect_new_events(self):
+ for entry in self.oclouds.seen:
+ # while hasattr(entry, 'events') and len(entry.events) > 0:
+ while entry.events is not None and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.resource_pools.seen:
+ while entry.events is not None and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.resources.seen:
+ while entry.events is not None and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.resource_types.seen:
+ while hasattr(entry, 'events') and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.deployment_managers.seen:
+ while hasattr(entry, 'events') and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.subscriptions.seen:
+ while hasattr(entry, 'events') and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.configurations.seen:
+ while hasattr(entry, 'events') and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.nfdeployment_descs.seen:
+ while hasattr(entry, 'events') and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.nfdeployments.seen:
+ while hasattr(entry, 'events') and len(entry.events) > 0:
+ yield entry.events.pop(0)
+ for entry in self.ocloudvresources.seen:
+ while hasattr(entry, 'events') and len(entry.events) > 0:
+ yield entry.events.pop(0)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from flask import Flask\r
-from flask_restx import Api\r
-\r
-from o2app import bootstrap\r
-from o2ims.views import configure_namespace as ims_route_configure_namespace\r
-from o2dms.api import configure_namespace as dms_route_configure_namespace\r
-\r
-\r
-# apibase = config.get_o2ims_api_base()\r
-app = Flask(__name__)\r
-app.config.SWAGGER_UI_DOC_EXPANSION = 'list'\r
-api = Api(app, version='1.0.0',\r
- title='INF O2 Services API',\r
- description='Swagger OpenAPI document for the INF O2 Services',\r
- )\r
-bus = bootstrap.bootstrap()\r
-\r
-ims_route_configure_namespace(api)\r
-dms_route_configure_namespace(api)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 flask import Flask
+from flask_restx import Api
+
+from o2app import bootstrap
+from o2ims.views import configure_namespace as ims_route_configure_namespace
+from o2dms.api import configure_namespace as dms_route_configure_namespace
+
+
+# apibase = config.get_o2ims_api_base()
+app = Flask(__name__)
+app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
+api = Api(app, version='1.0.0',
+ title='INF O2 Services API',
+ description='Swagger OpenAPI document for the INF O2 Services',
+ )
+bus = bootstrap.bootstrap()
+
+ims_route_configure_namespace(api)
+dms_route_configure_namespace(api)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import cotyledon\r
-\r
-from o2app import bootstrap\r
-from o2common.service.watcher.base import WatcherTree\r
-from o2common.service.watcher.worker import PollWorker\r
-\r
-from o2ims.service.watcher.ocloud_watcher import OcloudWatcher\r
-from o2ims.service.watcher.ocloud_watcher import DmsWatcher\r
-from o2ims.service.watcher.resourcepool_watcher import ResourcePoolWatcher\r
-from o2ims.adapter.clients.ocloud_sa_client import StxSaDmsClient\r
-from o2ims.adapter.clients.ocloud_sa_client import StxSaOcloudClient\r
-from o2ims.adapter.clients.ocloud_sa_client import StxSaResourcePoolClient\r
-\r
-from o2ims.service.watcher.pserver_watcher import PServerWatcher\r
-from o2ims.adapter.clients.ocloud_sa_client import StxPserverClient\r
-\r
-from o2ims.service.watcher.pserver_cpu_watcher import PServerCpuWatcher\r
-from o2ims.adapter.clients.ocloud_sa_client import StxCpuClient\r
-\r
-from o2ims.service.watcher.pserver_mem_watcher import PServerMemWatcher\r
-from o2ims.adapter.clients.ocloud_sa_client import StxMemClient\r
-\r
-from o2ims.service.watcher.pserver_if_watcher import PServerIfWatcher\r
-from o2ims.adapter.clients.ocloud_sa_client import StxIfClient\r
-\r
-from o2ims.service.watcher.pserver_port_watcher import PServerIfPortWatcher\r
-from o2ims.adapter.clients.ocloud_sa_client import StxIfPortClient\r
-\r
-from o2ims.service.watcher.pserver_eth_watcher import PServerEthWatcher\r
-from o2ims.adapter.clients.ocloud_sa_client import StxEthClient\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-# r = redis.Redis(**config.get_redis_host_and_port())\r
-\r
-\r
-class WatcherService(cotyledon.Service):\r
- def __init__(self, worker_id, args=None) -> None:\r
- super().__init__(worker_id)\r
- self.args = args\r
- self.bus = bootstrap.bootstrap()\r
- self.worker = PollWorker(bus=self.bus)\r
-\r
- def run(self):\r
- try:\r
- root = WatcherTree(OcloudWatcher(\r
- StxSaOcloudClient(), self.bus))\r
- root.addchild(\r
- DmsWatcher(StxSaDmsClient(), self.bus))\r
-\r
- child_respool = root.addchild(\r
- ResourcePoolWatcher(StxSaResourcePoolClient(),\r
- self.bus))\r
- child_pserver = child_respool.addchild(\r
- PServerWatcher(StxPserverClient(), self.bus))\r
- child_pserver.addchild(\r
- PServerCpuWatcher(StxCpuClient(), self.bus))\r
- child_pserver.addchild(\r
- PServerMemWatcher(StxMemClient(), self.bus))\r
- child_pserver.addchild(\r
- PServerEthWatcher(StxEthClient(), self.bus))\r
- child_if = child_pserver.addchild(\r
- PServerIfWatcher(StxIfClient(), self.bus))\r
- # child_if.addchild(\r
- # PServerIfPortWatcher(StxIfPortClient(), self.bus))\r
-\r
- self.worker.add_watcher(root)\r
-\r
- self.worker.start()\r
- except Exception as ex:\r
- logger.warning("WorkerService Exception:" + str(ex))\r
- finally:\r
- self.worker.stop()\r
-\r
-\r
-def start_watchers(sm: cotyledon.ServiceManager = None):\r
- watchersm = sm if sm else cotyledon.ServiceManager()\r
- watchersm.add(WatcherService, workers=1, args=())\r
- watchersm.run()\r
-\r
-\r
-def main():\r
- logger.info("Resource watcher starting")\r
- start_watchers()\r
-\r
-\r
-if __name__ == "__main__":\r
- main()\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 cotyledon
+
+from o2app import bootstrap
+from o2common.service.watcher.base import WatcherTree
+from o2common.service.watcher.worker import PollWorker
+
+from o2ims.service.watcher.ocloud_watcher import OcloudWatcher
+from o2ims.service.watcher.ocloud_watcher import DmsWatcher
+from o2ims.service.watcher.resourcepool_watcher import ResourcePoolWatcher
+from o2ims.adapter.clients.ocloud_sa_client import StxSaDmsClient
+from o2ims.adapter.clients.ocloud_sa_client import StxSaOcloudClient
+from o2ims.adapter.clients.ocloud_sa_client import StxSaResourcePoolClient
+
+from o2ims.service.watcher.pserver_watcher import PServerWatcher
+from o2ims.adapter.clients.ocloud_sa_client import StxPserverClient
+
+from o2ims.service.watcher.pserver_cpu_watcher import PServerCpuWatcher
+from o2ims.adapter.clients.ocloud_sa_client import StxCpuClient
+
+from o2ims.service.watcher.pserver_mem_watcher import PServerMemWatcher
+from o2ims.adapter.clients.ocloud_sa_client import StxMemClient
+
+from o2ims.service.watcher.pserver_if_watcher import PServerIfWatcher
+from o2ims.adapter.clients.ocloud_sa_client import StxIfClient
+
+from o2ims.service.watcher.pserver_port_watcher import PServerIfPortWatcher
+from o2ims.adapter.clients.ocloud_sa_client import StxIfPortClient
+
+from o2ims.service.watcher.pserver_eth_watcher import PServerEthWatcher
+from o2ims.adapter.clients.ocloud_sa_client import StxEthClient
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+# r = redis.Redis(**config.get_redis_host_and_port())
+
+
+class WatcherService(cotyledon.Service):
+ def __init__(self, worker_id, args=None) -> None:
+ super().__init__(worker_id)
+ self.args = args
+ self.bus = bootstrap.bootstrap()
+ self.worker = PollWorker(bus=self.bus)
+
+ def run(self):
+ try:
+ root = WatcherTree(OcloudWatcher(
+ StxSaOcloudClient(), self.bus))
+ root.addchild(
+ DmsWatcher(StxSaDmsClient(), self.bus))
+
+ child_respool = root.addchild(
+ ResourcePoolWatcher(StxSaResourcePoolClient(),
+ self.bus))
+ child_pserver = child_respool.addchild(
+ PServerWatcher(StxPserverClient(), self.bus))
+ child_pserver.addchild(
+ PServerCpuWatcher(StxCpuClient(), self.bus))
+ child_pserver.addchild(
+ PServerMemWatcher(StxMemClient(), self.bus))
+ child_pserver.addchild(
+ PServerEthWatcher(StxEthClient(), self.bus))
+ child_if = child_pserver.addchild(
+ PServerIfWatcher(StxIfClient(), self.bus))
+ # child_if.addchild(
+ # PServerIfPortWatcher(StxIfPortClient(), self.bus))
+
+ self.worker.add_watcher(root)
+
+ self.worker.start()
+ except Exception as ex:
+ logger.warning("WorkerService Exception:" + str(ex))
+ finally:
+ self.worker.stop()
+
+
+def start_watchers(sm: cotyledon.ServiceManager = None):
+ watchersm = sm if sm else cotyledon.ServiceManager()
+ watchersm.add(WatcherService, workers=1, args=())
+ watchersm.run()
+
+
+def main():
+ logger.info("Resource watcher starting")
+ start_watchers()
+
+
+if __name__ == "__main__":
+ main()
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from datetime import datetime\r
-from typing import List\r
-from sqlalchemy.inspection import inspect\r
-from sqlalchemy.exc import NoInspectionAvailable\r
-# from sqlalchemy.orm.exc import DetachedInstanceError\r
-from .events import Event\r
-\r
-\r
-class AgRoot:\r
-\r
- events = []\r
-\r
- def __init__(self) -> None:\r
- self.hash = ""\r
- self.updatetime = datetime.now()\r
- self.createtime = datetime.now()\r
- self.events = [] # type: List[Event]\r
- # self.id = ""\r
-\r
- # def append_event(self, event: Event):\r
- # self.events = self.events.append(event)\r
-\r
-\r
-class Serializer(object):\r
-\r
- def serialize(self):\r
- try:\r
- # d = {c: getattr(self, c) for c in inspect(self).attrs.keys()}\r
- # if 'createtime' in d:\r
- # d['createtime'] = d['createtime'].isoformat()\r
- # if 'updatetime' in d:\r
- # d['updatetime'] = d['updatetime'].isoformat()\r
- # return d\r
- return {c: getattr(self, c) for c in inspect(self).attrs.keys()}\r
- except NoInspectionAvailable:\r
- return self.__dict__\r
-\r
- @staticmethod\r
- def serialize_list(li):\r
- return [m.serialize() for m in li]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 datetime import datetime
+from typing import List
+from sqlalchemy.inspection import inspect
+from sqlalchemy.exc import NoInspectionAvailable
+# from sqlalchemy.orm.exc import DetachedInstanceError
+from .events import Event
+
+
+class AgRoot:
+
+ events = []
+
+ def __init__(self) -> None:
+ self.hash = ""
+ self.updatetime = datetime.now()
+ self.createtime = datetime.now()
+ self.events = [] # type: List[Event]
+ # self.id = ""
+
+ # def append_event(self, event: Event):
+ # self.events = self.events.append(event)
+
+
+class Serializer(object):
+
+ def serialize(self):
+ try:
+ # d = {c: getattr(self, c) for c in inspect(self).attrs.keys()}
+ # if 'createtime' in d:
+ # d['createtime'] = d['createtime'].isoformat()
+ # if 'updatetime' in d:
+ # d['updatetime'] = d['updatetime'].isoformat()
+ # return d
+ return {c: getattr(self, c) for c in inspect(self).attrs.keys()}
+ except NoInspectionAvailable:
+ return self.__dict__
+
+ @staticmethod
+ def serialize_list(li):
+ return [m.serialize() for m in li]
-# Copyright (C) 2022 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# pylint: disable=too-few-public-methods\r
-\r
-class Orano2Exception(Exception):\r
- pass\r
+# Copyright (C) 2022 Wind River Systems, Inc.
+#
+# 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.
+
+# pylint: disable=too-few-public-methods
+
+class Orano2Exception(Exception):
+ pass
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import logging\r
-import logging.config\r
-import logging.handlers\r
-import os\r
-import yaml\r
-\r
-\r
-def get_logger(name=None):\r
- CONFIG_FILE = os.environ.get(\r
- "LOGGING_CONFIG_FILE", "/etc/o2/log.yaml")\r
- if os.path.exists(CONFIG_FILE):\r
- with open(file=CONFIG_FILE, mode='r', encoding="utf-8") as file:\r
- config_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)\r
- logging.config.dictConfig(config=config_yaml)\r
-\r
- logger = logging.getLogger(name)\r
-\r
- # override logging level\r
- LOGGING_CONFIG_LEVEL = os.environ.get("LOGGING_CONFIG_LEVEL", None)\r
- if LOGGING_CONFIG_LEVEL:\r
- logger.setLevel(LOGGING_CONFIG_LEVEL)\r
- return logger\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 logging
+import logging.config
+import logging.handlers
+import os
+import yaml
+
+
+def get_logger(name=None):
+ CONFIG_FILE = os.environ.get(
+ "LOGGING_CONFIG_FILE", "/etc/o2/log.yaml")
+ if os.path.exists(CONFIG_FILE):
+ with open(file=CONFIG_FILE, mode='r', encoding="utf-8") as file:
+ config_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)
+ logging.config.dictConfig(config=config_yaml)
+
+ logger = logging.getLogger(name)
+
+ # override logging level
+ LOGGING_CONFIG_LEVEL = os.environ.get("LOGGING_CONFIG_LEVEL", None)
+ if LOGGING_CONFIG_LEVEL:
+ logger.setLevel(LOGGING_CONFIG_LEVEL)
+ return logger
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import abc\r
-# from typing import Optional, List, Set\r
-# from typing import List\r
-\r
-\r
-class BaseClient(abc.ABC):\r
- def __init__(self):\r
- pass\r
-\r
- def list(self, **filters):\r
- return self._list(**filters)\r
-\r
- def get(self, id):\r
- return self._get(id)\r
-\r
- @abc.abstractmethod\r
- def _get(self, id):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _list(self, **filters):\r
- raise NotImplementedError\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 abc
+# from typing import Optional, List, Set
+# from typing import List
+
+
+class BaseClient(abc.ABC):
+ def __init__(self):
+ pass
+
+ def list(self, **filters):
+ return self._list(**filters)
+
+ def get(self, id):
+ return self._get(id)
+
+ @abc.abstractmethod
+ def _get(self, id):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _list(self, **filters):
+ raise NotImplementedError
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# from logging import exception\r
-# from cgtsclient import exc\r
-from o2common.service.client.base_client import BaseClient\r
-from o2common.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class BaseWatcher(object):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__()\r
- self._client = client\r
- self._bus = bus\r
- # self._uow = bus.uow\r
-\r
- def targetname(self) -> str:\r
- return self._targetname()\r
-\r
- def probe(self, parent: commands.Command = None):\r
- try:\r
- cmds = self._probe(parent.data if parent else None)\r
- for cmd in cmds:\r
- self._bus.handle(cmd)\r
-\r
- # return self._probe(parent)\r
- return cmds\r
- except Exception as ex:\r
- logger.warning("Failed to probe resource due to: " + str(ex))\r
- return []\r
-\r
- def _probe(self, parent: object = None) -> commands.Command:\r
- raise NotImplementedError\r
-\r
- def _targetname(self):\r
- raise NotImplementedError\r
-\r
- # def _compare_and_update(self, newmodel: StxGenericModel) -> bool:\r
- # with self._uow:\r
- # # localmodel = self._uow.stxobjects.get(ocloudmodel.id)\r
- # localmodel = self._uow.stxobjects.get(str(newmodel.id))\r
- # if not localmodel:\r
- # logger.info("add entry:" + newmodel.name)\r
- # self._uow.stxobjects.add(newmodel)\r
- # elif localmodel.is_outdated(newmodel):\r
- # logger.info("update entry:" + newmodel.name)\r
- # localmodel.update_by(newmodel)\r
- # self._uow.stxobjects.update(localmodel)\r
- # self._uow.commit()\r
-\r
-\r
-# node to organize watchers in tree hierachy\r
-class WatcherTree(object):\r
- def __init__(self, watcher: BaseWatcher) -> None:\r
- super().__init__()\r
- self.watcher = watcher\r
- self.children = {}\r
-\r
- def addchild(self, watcher: BaseWatcher) -> object:\r
- child = WatcherTree(watcher)\r
- self.children[watcher.targetname()] = child\r
- return child\r
-\r
- def removechild(self, targetname: str) -> object:\r
- return self.children.pop(targetname)\r
-\r
- # probe all resources by parent, depth = 0 for indefinite recursive\r
- def probe(self, parentresource=None, depth: int = 0):\r
- logger.debug("probe resources with watcher: "\r
- + self.watcher.targetname())\r
- childdepth = depth - 1 if depth > 0 else 0\r
- resources = self.watcher.probe(parentresource)\r
- logger.debug("probe returns " + str(len(resources)) + " resources")\r
-\r
- if depth == 1:\r
- # stop recursive\r
- return\r
-\r
- for res in resources:\r
- for targetname in self.children.keys():\r
- self.children[targetname].probe(res, childdepth)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 logging import exception
+# from cgtsclient import exc
+from o2common.service.client.base_client import BaseClient
+from o2common.domain import commands
+from o2common.service.messagebus import MessageBus
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class BaseWatcher(object):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__()
+ self._client = client
+ self._bus = bus
+ # self._uow = bus.uow
+
+ def targetname(self) -> str:
+ return self._targetname()
+
+ def probe(self, parent: commands.Command = None):
+ try:
+ cmds = self._probe(parent.data if parent else None)
+ for cmd in cmds:
+ self._bus.handle(cmd)
+
+ # return self._probe(parent)
+ return cmds
+ except Exception as ex:
+ logger.warning("Failed to probe resource due to: " + str(ex))
+ return []
+
+ def _probe(self, parent: object = None) -> commands.Command:
+ raise NotImplementedError
+
+ def _targetname(self):
+ raise NotImplementedError
+
+ # def _compare_and_update(self, newmodel: StxGenericModel) -> bool:
+ # with self._uow:
+ # # localmodel = self._uow.stxobjects.get(ocloudmodel.id)
+ # localmodel = self._uow.stxobjects.get(str(newmodel.id))
+ # if not localmodel:
+ # logger.info("add entry:" + newmodel.name)
+ # self._uow.stxobjects.add(newmodel)
+ # elif localmodel.is_outdated(newmodel):
+ # logger.info("update entry:" + newmodel.name)
+ # localmodel.update_by(newmodel)
+ # self._uow.stxobjects.update(localmodel)
+ # self._uow.commit()
+
+
+# node to organize watchers in tree hierachy
+class WatcherTree(object):
+ def __init__(self, watcher: BaseWatcher) -> None:
+ super().__init__()
+ self.watcher = watcher
+ self.children = {}
+
+ def addchild(self, watcher: BaseWatcher) -> object:
+ child = WatcherTree(watcher)
+ self.children[watcher.targetname()] = child
+ return child
+
+ def removechild(self, targetname: str) -> object:
+ return self.children.pop(targetname)
+
+ # probe all resources by parent, depth = 0 for indefinite recursive
+ def probe(self, parentresource=None, depth: int = 0):
+ logger.debug("probe resources with watcher: "
+ + self.watcher.targetname())
+ childdepth = depth - 1 if depth > 0 else 0
+ resources = self.watcher.probe(parentresource)
+ logger.debug("probe returns " + str(len(resources)) + " resources")
+
+ if depth == 1:
+ # stop recursive
+ return
+
+ for res in resources:
+ for targetname in self.children.keys():
+ self.children[targetname].probe(res, childdepth)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import time\r
-import sched\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2common.service.watcher.base import WatcherTree\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class PollWorker(object):\r
- def __init__(self, interval=10, bus=None) -> None:\r
- super().__init__()\r
- self.watchers = []\r
- self.schedinstance = sched.scheduler(time.time, time.sleep)\r
- self.schedinterval = interval\r
- self._stopped = True\r
- self._bus = bus\r
-\r
- def set_interval(self, interval):\r
- if interval > 0:\r
- self.schedinterval = interval\r
- else:\r
- raise Exception("Invalid interval:" + interval)\r
-\r
- def add_watcher(self, watcher: WatcherTree):\r
- self.watchers.append(watcher)\r
-\r
- def _repeat(self):\r
- logger.debug("_repeat started")\r
- if self._stopped:\r
- return\r
- for w in self.watchers:\r
- try:\r
- # logger.debug("about to probe:"+w)\r
- w.probe(None)\r
- except Exception as ex:\r
- logger.warning("Worker raises exception:" + str(ex))\r
- continue\r
-\r
- # handle events\r
- if self._bus is not None:\r
- events = self._bus.uow.collect_new_events()\r
- for event in events:\r
- self._bus.handle(event)\r
-\r
- self.schedinstance.enter(self.schedinterval, 1, self._repeat)\r
-\r
- # note the sched run will block current thread\r
- def start(self):\r
- self._stopped = False\r
- logger.debug('about to start sched task')\r
- self.schedinstance.enter(self.schedinterval, 1, self._repeat)\r
- self.schedinstance.run()\r
-\r
- def stop(self):\r
- self._stopped = True\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 time
+import sched
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2common.service.watcher.base import WatcherTree
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class PollWorker(object):
+ def __init__(self, interval=10, bus=None) -> None:
+ super().__init__()
+ self.watchers = []
+ self.schedinstance = sched.scheduler(time.time, time.sleep)
+ self.schedinterval = interval
+ self._stopped = True
+ self._bus = bus
+
+ def set_interval(self, interval):
+ if interval > 0:
+ self.schedinterval = interval
+ else:
+ raise Exception("Invalid interval:" + interval)
+
+ def add_watcher(self, watcher: WatcherTree):
+ self.watchers.append(watcher)
+
+ def _repeat(self):
+ logger.debug("_repeat started")
+ if self._stopped:
+ return
+ for w in self.watchers:
+ try:
+ # logger.debug("about to probe:"+w)
+ w.probe(None)
+ except Exception as ex:
+ logger.warning("Worker raises exception:" + str(ex))
+ continue
+
+ # handle events
+ if self._bus is not None:
+ events = self._bus.uow.collect_new_events()
+ for event in events:
+ self._bus.handle(event)
+
+ self.schedinstance.enter(self.schedinterval, 1, self._repeat)
+
+ # note the sched run will block current thread
+ def start(self):
+ self._stopped = False
+ logger.debug('about to start sched task')
+ self.schedinstance.enter(self.schedinterval, 1, self._repeat)
+ self.schedinstance.run()
+
+ def stop(self):
+ self._stopped = True
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from retry import retry\r
-from sqlalchemy import (\r
- Table,\r
- MetaData,\r
- Column,\r
- Integer,\r
- String,\r
- Text,\r
- # Date,\r
- DateTime,\r
- # ForeignKey,\r
- # engine,\r
- # event,\r
- exc\r
-)\r
-\r
-from sqlalchemy.orm import mapper\r
-from o2dms.domain import dms as dmsModel\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-metadata = MetaData()\r
-\r
-nfDeploymentDesc = Table(\r
- "nfDeploymentDesc",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("id", String(255), primary_key=True),\r
- Column("deploymentManagerId", String(255)),\r
- Column("name", String(255)),\r
- Column("description", String(255)),\r
- Column("inputParams", Text()),\r
- Column("outputParams", String(255)),\r
- Column("artifactRepoUrl", String(255)),\r
- Column("artifactName", String(255)),\r
- # Column("extensions", String(1024))\r
-)\r
-\r
-nfDeployment = Table(\r
- "nfDeployment",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("id", String(255), primary_key=True),\r
- Column("deploymentManagerId", String(255)),\r
- Column("name", String(255)),\r
- Column("description", String(255)),\r
- Column("descriptorId", String(255)),\r
- Column("parentDeploymentId", String(255)),\r
- Column("status", Integer)\r
-)\r
-\r
-nfOCloudVResource = Table(\r
- "nfOcloudVRes",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("id", String(255), primary_key=True),\r
- Column("deploymentManagerId", String(255)),\r
- Column("name", String(255)),\r
- Column("description", String(255)),\r
- Column("descriptorId", String(255)),\r
- Column("vresourceType", String(255)),\r
- Column("status", Integer),\r
- Column("metadata", String(2048)),\r
- Column("nfDeploymentId", String(255))\r
-)\r
-\r
-\r
-@retry((exc.IntegrityError), tries=3, delay=2)\r
-def wait_for_metadata_ready(engine):\r
- # wait for mapper ready\r
- metadata.create_all(engine, checkfirst=True)\r
- logger.info("metadata is ready")\r
-\r
-\r
-def start_o2dms_mappers(engine=None):\r
- logger.info("Starting O2 DMS mappers")\r
-\r
- mapper(dmsModel.NfDeploymentDesc, nfDeploymentDesc)\r
- mapper(dmsModel.NfDeployment, nfDeployment)\r
- mapper(dmsModel.NfOCloudVResource, nfOCloudVResource)\r
-\r
- if engine is not None:\r
- wait_for_metadata_ready(engine)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 retry import retry
+from sqlalchemy import (
+ Table,
+ MetaData,
+ Column,
+ Integer,
+ String,
+ Text,
+ # Date,
+ DateTime,
+ # ForeignKey,
+ # engine,
+ # event,
+ exc
+)
+
+from sqlalchemy.orm import mapper
+from o2dms.domain import dms as dmsModel
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+metadata = MetaData()
+
+nfDeploymentDesc = Table(
+ "nfDeploymentDesc",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("id", String(255), primary_key=True),
+ Column("deploymentManagerId", String(255)),
+ Column("name", String(255)),
+ Column("description", String(255)),
+ Column("inputParams", Text()),
+ Column("outputParams", String(255)),
+ Column("artifactRepoUrl", String(255)),
+ Column("artifactName", String(255)),
+ # Column("extensions", String(1024))
+)
+
+nfDeployment = Table(
+ "nfDeployment",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("id", String(255), primary_key=True),
+ Column("deploymentManagerId", String(255)),
+ Column("name", String(255)),
+ Column("description", String(255)),
+ Column("descriptorId", String(255)),
+ Column("parentDeploymentId", String(255)),
+ Column("status", Integer)
+)
+
+nfOCloudVResource = Table(
+ "nfOcloudVRes",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("id", String(255), primary_key=True),
+ Column("deploymentManagerId", String(255)),
+ Column("name", String(255)),
+ Column("description", String(255)),
+ Column("descriptorId", String(255)),
+ Column("vresourceType", String(255)),
+ Column("status", Integer),
+ Column("metadata", String(2048)),
+ Column("nfDeploymentId", String(255))
+)
+
+
+@retry((exc.IntegrityError), tries=3, delay=2)
+def wait_for_metadata_ready(engine):
+ # wait for mapper ready
+ metadata.create_all(engine, checkfirst=True)
+ logger.info("metadata is ready")
+
+
+def start_o2dms_mappers(engine=None):
+ logger.info("Starting O2 DMS mappers")
+
+ mapper(dmsModel.NfDeploymentDesc, nfDeploymentDesc)
+ mapper(dmsModel.NfDeployment, nfDeployment)
+ mapper(dmsModel.NfOCloudVResource, nfOCloudVResource)
+
+ if engine is not None:
+ wait_for_metadata_ready(engine)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2dms.api.dms_api_ns import api_dms_lcm_v1\r
-from . import dms_route\r
-from . import nfdeployment_desc_route\r
-from . import nfdeployment_route\r
-from o2common.config import config\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def configure_namespace(app):\r
- apibase = config.get_o2dms_api_base()\r
- logger.info(\r
- "Expose O2DMS API:{}".format(apibase))\r
-\r
- dms_route.configure_api_route()\r
- nfdeployment_desc_route.configure_api_route()\r
- nfdeployment_route.configure_api_route()\r
- app.add_namespace(api_dms_lcm_v1, path=apibase)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2dms.api.dms_api_ns import api_dms_lcm_v1
+from . import dms_route
+from . import nfdeployment_desc_route
+from . import nfdeployment_route
+from o2common.config import config
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def configure_namespace(app):
+ apibase = config.get_o2dms_api_base()
+ logger.info(
+ "Expose O2DMS API:{}".format(apibase))
+
+ dms_route.configure_api_route()
+ nfdeployment_desc_route.configure_api_route()
+ nfdeployment_route.configure_api_route()
+ app.add_namespace(api_dms_lcm_v1, path=apibase)
-from flask_restx import Namespace\r
-\r
-\r
-api_dms_lcm_v1 = Namespace(\r
- "O2DMS_LCM", description='DMS LCM related operations.')\r
+from flask_restx import Namespace
+
+
+api_dms_lcm_v1 = Namespace(
+ "O2DMS_LCM", description='DMS LCM related operations.')
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from sqlalchemy import select\r
-import uuid\r
-from o2dms.domain.states import NfDeploymentState\r
-from o2common.service import messagebus\r
-from o2common.service import unit_of_work\r
-from o2dms.adapter.orm import nfDeployment\r
-from o2dms.api.dms_dto import DmsLcmNfDeploymentDTO\r
-from o2dms.domain.dms import NfDeployment\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def lcm_nfdeployment_list(\r
- deploymentManagerID: str, uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(nfDeployment).where(\r
- nfDeployment.c.deploymentManagerId == deploymentManagerID))\r
- return [dict(r) for r in res]\r
-\r
-\r
-def lcm_nfdeployment_one(\r
- nfdeploymentid: str, uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(nfDeployment).where(\r
- nfDeployment.c.id == nfdeploymentid))\r
- first = res.first()\r
- return None if first is None else dict(first)\r
-\r
-\r
-def lcm_nfdeployment_create(\r
- deploymentManagerId: str,\r
- input: DmsLcmNfDeploymentDTO.\r
- NfDeployment_create,\r
- bus: messagebus.MessageBus):\r
-\r
- uow = bus.uow\r
- id = str(uuid.uuid4())\r
- with uow:\r
- _check_duplication(input, uow)\r
- _check_dependencies(input, uow)\r
- entity = NfDeployment(\r
- id, input['name'], deploymentManagerId, input['description'],\r
- input['descriptorId'], input['parentDeploymentId'])\r
- uow.nfdeployments.add(entity)\r
- # entity.transit_state(NfDeploymentState.NotInstalled)\r
-\r
- # to be refactor later according to O2 DMS API design\r
- entity.transit_state(NfDeploymentState.Installing)\r
- uow.commit()\r
- _handle_events(bus)\r
-\r
- return id\r
-\r
-\r
-def lcm_nfdeployment_update(\r
- nfdeploymentid: str,\r
- input: DmsLcmNfDeploymentDTO.NfDeployment_update,\r
- bus: messagebus.MessageBus):\r
-\r
- uow = bus.uow\r
- with uow:\r
- entity: NfDeployment = uow.nfdeployments.get(nfdeploymentid)\r
- entity.name = input['name']\r
- entity.description = input['description']\r
- entity.outputParams = input['parentDeploymentId']\r
- entity.transit_state(NfDeploymentState.Updating)\r
- uow.commit()\r
- _handle_events(bus)\r
- return True\r
-\r
-\r
-def _handle_events(bus: messagebus.MessageBus):\r
- # handle events\r
- events = bus.uow.collect_new_events()\r
- for event in events:\r
- bus.handle(event)\r
- return True\r
-\r
-\r
-def lcm_nfdeployment_uninstall(\r
- nfdeploymentid: str,\r
- bus: messagebus.MessageBus):\r
-\r
- uow = bus.uow\r
- with uow:\r
- entity: NfDeployment = uow.nfdeployments.get(nfdeploymentid)\r
- if not entity:\r
- pass\r
- elif entity.status == NfDeploymentState.Initial:\r
- bus.uow.nfdeployments.delete(nfdeploymentid)\r
- # elif entity.status == NfDeploymentState.NotInstalled:\r
- # bus.uow.nfdeployments.delete(nfdeploymentid)\r
- elif entity.status == NfDeploymentState.Installing:\r
- entity.transit_state(NfDeploymentState.Uninstalling)\r
- elif entity.status == NfDeploymentState.Installed:\r
- entity.transit_state(NfDeploymentState.Uninstalling)\r
- elif entity.status == NfDeploymentState.Updating:\r
- entity.transit_state(NfDeploymentState.Uninstalling)\r
- elif entity.status == NfDeploymentState.Uninstalling:\r
- pass\r
- elif entity.status == NfDeploymentState.Abnormal:\r
- bus.uow.nfdeployments.delete(nfdeploymentid)\r
- else:\r
- entity.transit_state(NfDeploymentState.Abnormal)\r
- uow.commit()\r
- _handle_events(bus)\r
- return True\r
-\r
-\r
-# def lcm_nfdeployment_delete(\r
-# nfdeploymentid: str,\r
-# bus: messagebus.MessageBus):\r
-\r
-# uow = bus.uow\r
-# with uow:\r
-# entity = uow.nfdeployments.get(nfdeploymentid)\r
-# if entity.status != NfDeploymentState.Initial:\r
-# raise Exception(\r
-# "NfDeployment {} is not in status to delete".format(\r
-# nfdeploymentid))\r
-# uow.nfdeployments.delete(nfdeploymentid)\r
-# entity.transit_state(NfDeploymentState.Deleting)\r
-# uow.commit()\r
-# return True\r
-\r
-\r
-def _check_duplication(\r
- input: DmsLcmNfDeploymentDTO,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- name = input['name']\r
- descriptorId = input['descriptorId']\r
- if uow.nfdeployments.count(name=name) > 0:\r
- raise Exception(\r
- "NfDeployment with name {} exists already".format(name))\r
- if uow.nfdeployments.count(descriptorId=descriptorId) > 0:\r
- raise Exception(\r
- "NfDeployment with descriptorId {} exists already".format(\r
- descriptorId))\r
-\r
-\r
-def _check_dependencies(\r
- input: DmsLcmNfDeploymentDTO,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- descriptorId = input['descriptorId']\r
- if uow.nfdeployment_descs.count(id=descriptorId) == 0:\r
- raise Exception(\r
- "NfDeploymentDescriptor with id {} does not exist".format(\r
- descriptorId))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 sqlalchemy import select
+import uuid
+from o2dms.domain.states import NfDeploymentState
+from o2common.service import messagebus
+from o2common.service import unit_of_work
+from o2dms.adapter.orm import nfDeployment
+from o2dms.api.dms_dto import DmsLcmNfDeploymentDTO
+from o2dms.domain.dms import NfDeployment
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def lcm_nfdeployment_list(
+ deploymentManagerID: str, uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(nfDeployment).where(
+ nfDeployment.c.deploymentManagerId == deploymentManagerID))
+ return [dict(r) for r in res]
+
+
+def lcm_nfdeployment_one(
+ nfdeploymentid: str, uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(nfDeployment).where(
+ nfDeployment.c.id == nfdeploymentid))
+ first = res.first()
+ return None if first is None else dict(first)
+
+
+def lcm_nfdeployment_create(
+ deploymentManagerId: str,
+ input: DmsLcmNfDeploymentDTO.
+ NfDeployment_create,
+ bus: messagebus.MessageBus):
+
+ uow = bus.uow
+ id = str(uuid.uuid4())
+ with uow:
+ _check_duplication(input, uow)
+ _check_dependencies(input, uow)
+ entity = NfDeployment(
+ id, input['name'], deploymentManagerId, input['description'],
+ input['descriptorId'], input['parentDeploymentId'])
+ uow.nfdeployments.add(entity)
+ # entity.transit_state(NfDeploymentState.NotInstalled)
+
+ # to be refactor later according to O2 DMS API design
+ entity.transit_state(NfDeploymentState.Installing)
+ uow.commit()
+ _handle_events(bus)
+
+ return id
+
+
+def lcm_nfdeployment_update(
+ nfdeploymentid: str,
+ input: DmsLcmNfDeploymentDTO.NfDeployment_update,
+ bus: messagebus.MessageBus):
+
+ uow = bus.uow
+ with uow:
+ entity: NfDeployment = uow.nfdeployments.get(nfdeploymentid)
+ entity.name = input['name']
+ entity.description = input['description']
+ entity.outputParams = input['parentDeploymentId']
+ entity.transit_state(NfDeploymentState.Updating)
+ uow.commit()
+ _handle_events(bus)
+ return True
+
+
+def _handle_events(bus: messagebus.MessageBus):
+ # handle events
+ events = bus.uow.collect_new_events()
+ for event in events:
+ bus.handle(event)
+ return True
+
+
+def lcm_nfdeployment_uninstall(
+ nfdeploymentid: str,
+ bus: messagebus.MessageBus):
+
+ uow = bus.uow
+ with uow:
+ entity: NfDeployment = uow.nfdeployments.get(nfdeploymentid)
+ if not entity:
+ pass
+ elif entity.status == NfDeploymentState.Initial:
+ bus.uow.nfdeployments.delete(nfdeploymentid)
+ # elif entity.status == NfDeploymentState.NotInstalled:
+ # bus.uow.nfdeployments.delete(nfdeploymentid)
+ elif entity.status == NfDeploymentState.Installing:
+ entity.transit_state(NfDeploymentState.Uninstalling)
+ elif entity.status == NfDeploymentState.Installed:
+ entity.transit_state(NfDeploymentState.Uninstalling)
+ elif entity.status == NfDeploymentState.Updating:
+ entity.transit_state(NfDeploymentState.Uninstalling)
+ elif entity.status == NfDeploymentState.Uninstalling:
+ pass
+ elif entity.status == NfDeploymentState.Abnormal:
+ bus.uow.nfdeployments.delete(nfdeploymentid)
+ else:
+ entity.transit_state(NfDeploymentState.Abnormal)
+ uow.commit()
+ _handle_events(bus)
+ return True
+
+
+# def lcm_nfdeployment_delete(
+# nfdeploymentid: str,
+# bus: messagebus.MessageBus):
+
+# uow = bus.uow
+# with uow:
+# entity = uow.nfdeployments.get(nfdeploymentid)
+# if entity.status != NfDeploymentState.Initial:
+# raise Exception(
+# "NfDeployment {} is not in status to delete".format(
+# nfdeploymentid))
+# uow.nfdeployments.delete(nfdeploymentid)
+# entity.transit_state(NfDeploymentState.Deleting)
+# uow.commit()
+# return True
+
+
+def _check_duplication(
+ input: DmsLcmNfDeploymentDTO,
+ uow: unit_of_work.AbstractUnitOfWork):
+ name = input['name']
+ descriptorId = input['descriptorId']
+ if uow.nfdeployments.count(name=name) > 0:
+ raise Exception(
+ "NfDeployment with name {} exists already".format(name))
+ if uow.nfdeployments.count(descriptorId=descriptorId) > 0:
+ raise Exception(
+ "NfDeployment with descriptorId {} exists already".format(
+ descriptorId))
+
+
+def _check_dependencies(
+ input: DmsLcmNfDeploymentDTO,
+ uow: unit_of_work.AbstractUnitOfWork):
+ descriptorId = input['descriptorId']
+ if uow.nfdeployment_descs.count(id=descriptorId) == 0:
+ raise Exception(
+ "NfDeploymentDescriptor with id {} does not exist".format(
+ descriptorId))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from sqlalchemy import select\r
-from o2common.service import unit_of_work\r
-from o2dms.adapter.orm import nfOCloudVResource\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def lcm_nfocloudvresource_list(\r
- nfDeploymentId: str, uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(nfOCloudVResource).where(\r
- nfOCloudVResource.c.nfDeploymentId == nfDeploymentId))\r
- return [dict(r) for r in res]\r
-\r
-\r
-def lcm_nfocloudvresource_one(\r
- ocloudvresourceId: str, uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(nfOCloudVResource).where(\r
- nfOCloudVResource.c.id == ocloudvresourceId))\r
- first = res.first()\r
- return None if first is None else dict(first)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 sqlalchemy import select
+from o2common.service import unit_of_work
+from o2dms.adapter.orm import nfOCloudVResource
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def lcm_nfocloudvresource_list(
+ nfDeploymentId: str, uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(nfOCloudVResource).where(
+ nfOCloudVResource.c.nfDeploymentId == nfDeploymentId))
+ return [dict(r) for r in res]
+
+
+def lcm_nfocloudvresource_one(
+ ocloudvresourceId: str, uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(nfOCloudVResource).where(
+ nfOCloudVResource.c.id == ocloudvresourceId))
+ first = res.first()
+ return None if first is None else dict(first)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import json\r
-from sqlalchemy import select\r
-import uuid\r
-from o2common.service import unit_of_work\r
-from o2dms.adapter.orm import nfDeploymentDesc\r
-from o2dms.api.dms_dto import DmsLcmNfDeploymentDescriptorDTO\r
-from o2dms.domain.dms import NfDeploymentDesc\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def lcm_nfdeploymentdesc_list(deploymentManagerID: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(nfDeploymentDesc).where(\r
- nfDeploymentDesc.c.deploymentManagerId == deploymentManagerID))\r
- return [dict(r) for r in res]\r
-\r
-\r
-def lcm_nfdeploymentdesc_one(nfdeploymentdescriptorid: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(nfDeploymentDesc).where(\r
- nfDeploymentDesc.c.id == nfdeploymentdescriptorid))\r
- first = res.first()\r
- return None if first is None else dict(first)\r
-\r
-\r
-def _check_duplication(name: str, uow: unit_of_work.AbstractUnitOfWork):\r
- if uow.nfdeployment_descs.count(name=name) > 0:\r
- raise Exception(\r
- "NfDeploymentDescriptor with name {} exists already".format(name))\r
-\r
-\r
-def lcm_nfdeploymentdesc_create(\r
- deploymentManagerId: str,\r
- input: DmsLcmNfDeploymentDescriptorDTO.\r
- NfDeploymentDescriptor_create,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
-\r
- with uow:\r
- _check_duplication(input['name'], uow)\r
- id = str(uuid.uuid4())\r
- entity = NfDeploymentDesc(\r
- id, input['name'], deploymentManagerId, input['description'],\r
- input['inputParams'], input['outputParams'],\r
- input['artifactRepoUrl'], input['artifactName'])\r
- _nfdeploymentdesc_validate(entity)\r
- uow.nfdeployment_descs.add(entity)\r
- uow.commit()\r
- return id\r
-\r
-\r
-def _nfdeploymentdesc_validate(desc: NfDeploymentDesc):\r
- try:\r
- if desc.inputParams:\r
- json.loads(desc.inputParams)\r
- if desc.outputParams:\r
- json.loads(desc.outputParams)\r
- if not desc.deploymentManagerId:\r
- raise Exception("Invalid deploymentManager Id")\r
- if not desc.artifactRepoUrl:\r
- raise Exception("Invalid artifactRepoUrl")\r
- if not desc.artifactName:\r
- raise Exception("Invalid artifactName")\r
- return\r
- except json.decoder.JSONDecodeError as e:\r
- logger.debug("NfDeploymentDesc json error with: %s" % (str(e)))\r
- raise e\r
- except Exception as e:\r
- logger.debug("NfDeploymentDesc validate error with: %s" % (str(e)))\r
- raise e\r
-\r
-\r
-def lcm_nfdeploymentdesc_update(\r
- nfdeploymentdescriptorid: str,\r
- input: DmsLcmNfDeploymentDescriptorDTO.NfDeploymentDescriptor_update,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
-\r
- with uow:\r
- entity = uow.nfdeployment_descs.get(nfdeploymentdescriptorid)\r
- entity.name = input['name']\r
- entity.description = input['description']\r
- entity.inputParams = input['inputParams']\r
- entity.outputParams = input['outputParams']\r
- entity.artifactRepoUrl = input['artifactRepoUrl']\r
- entity.artifactName = input['artifactName']\r
- uow.commit()\r
- return True\r
-\r
-\r
-def lcm_nfdeploymentdesc_delete(\r
- nfdeploymentdescriptorid: str, uow: unit_of_work.AbstractUnitOfWork):\r
-\r
- with uow:\r
- # check dependency\r
- _check_dependencies(nfdeploymentdescriptorid, uow)\r
- uow.nfdeployment_descs.delete(nfdeploymentdescriptorid)\r
- uow.commit()\r
- return True\r
-\r
-\r
-def _check_dependencies(\r
- descriptorId: str, uow: unit_of_work.AbstractUnitOfWork\r
-):\r
- # check if nfdeployment depends on it\r
- if uow.nfdeployments.count(descriptorId=descriptorId) > 0:\r
- raise Exception(\r
- "NfDeployment with descriptorId {} exists".format(\r
- descriptorId))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 sqlalchemy import select
+import uuid
+from o2common.service import unit_of_work
+from o2dms.adapter.orm import nfDeploymentDesc
+from o2dms.api.dms_dto import DmsLcmNfDeploymentDescriptorDTO
+from o2dms.domain.dms import NfDeploymentDesc
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def lcm_nfdeploymentdesc_list(deploymentManagerID: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(nfDeploymentDesc).where(
+ nfDeploymentDesc.c.deploymentManagerId == deploymentManagerID))
+ return [dict(r) for r in res]
+
+
+def lcm_nfdeploymentdesc_one(nfdeploymentdescriptorid: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(nfDeploymentDesc).where(
+ nfDeploymentDesc.c.id == nfdeploymentdescriptorid))
+ first = res.first()
+ return None if first is None else dict(first)
+
+
+def _check_duplication(name: str, uow: unit_of_work.AbstractUnitOfWork):
+ if uow.nfdeployment_descs.count(name=name) > 0:
+ raise Exception(
+ "NfDeploymentDescriptor with name {} exists already".format(name))
+
+
+def lcm_nfdeploymentdesc_create(
+ deploymentManagerId: str,
+ input: DmsLcmNfDeploymentDescriptorDTO.
+ NfDeploymentDescriptor_create,
+ uow: unit_of_work.AbstractUnitOfWork):
+
+ with uow:
+ _check_duplication(input['name'], uow)
+ id = str(uuid.uuid4())
+ entity = NfDeploymentDesc(
+ id, input['name'], deploymentManagerId, input['description'],
+ input['inputParams'], input['outputParams'],
+ input['artifactRepoUrl'], input['artifactName'])
+ _nfdeploymentdesc_validate(entity)
+ uow.nfdeployment_descs.add(entity)
+ uow.commit()
+ return id
+
+
+def _nfdeploymentdesc_validate(desc: NfDeploymentDesc):
+ try:
+ if desc.inputParams:
+ json.loads(desc.inputParams)
+ if desc.outputParams:
+ json.loads(desc.outputParams)
+ if not desc.deploymentManagerId:
+ raise Exception("Invalid deploymentManager Id")
+ if not desc.artifactRepoUrl:
+ raise Exception("Invalid artifactRepoUrl")
+ if not desc.artifactName:
+ raise Exception("Invalid artifactName")
+ return
+ except json.decoder.JSONDecodeError as e:
+ logger.debug("NfDeploymentDesc json error with: %s" % (str(e)))
+ raise e
+ except Exception as e:
+ logger.debug("NfDeploymentDesc validate error with: %s" % (str(e)))
+ raise e
+
+
+def lcm_nfdeploymentdesc_update(
+ nfdeploymentdescriptorid: str,
+ input: DmsLcmNfDeploymentDescriptorDTO.NfDeploymentDescriptor_update,
+ uow: unit_of_work.AbstractUnitOfWork):
+
+ with uow:
+ entity = uow.nfdeployment_descs.get(nfdeploymentdescriptorid)
+ entity.name = input['name']
+ entity.description = input['description']
+ entity.inputParams = input['inputParams']
+ entity.outputParams = input['outputParams']
+ entity.artifactRepoUrl = input['artifactRepoUrl']
+ entity.artifactName = input['artifactName']
+ uow.commit()
+ return True
+
+
+def lcm_nfdeploymentdesc_delete(
+ nfdeploymentdescriptorid: str, uow: unit_of_work.AbstractUnitOfWork):
+
+ with uow:
+ # check dependency
+ _check_dependencies(nfdeploymentdescriptorid, uow)
+ uow.nfdeployment_descs.delete(nfdeploymentdescriptorid)
+ uow.commit()
+ return True
+
+
+def _check_dependencies(
+ descriptorId: str, uow: unit_of_work.AbstractUnitOfWork
+):
+ # check if nfdeployment depends on it
+ if uow.nfdeployments.count(descriptorId=descriptorId) > 0:
+ raise Exception(
+ "NfDeployment with descriptorId {} exists".format(
+ descriptorId))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from sqlalchemy import select\r
-from o2common.service import unit_of_work\r
-from o2ims.adapter.orm import deploymentmanager\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def deployment_managers(uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(deploymentmanager))\r
- return [dict(r) for r in res]\r
-\r
-\r
-def deployment_manager_one(deploymentManagerId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- res = uow.session.execute(select(deploymentmanager).where(\r
- deploymentmanager.c.deploymentManagerId == deploymentManagerId))\r
- first = res.first()\r
- return None if first is None else dict(first)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 sqlalchemy import select
+from o2common.service import unit_of_work
+from o2ims.adapter.orm import deploymentmanager
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def deployment_managers(uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(deploymentmanager))
+ return [dict(r) for r in res]
+
+
+def deployment_manager_one(deploymentManagerId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ res = uow.session.execute(select(deploymentmanager).where(
+ deploymentmanager.c.deploymentManagerId == deploymentManagerId))
+ first = res.first()
+ return None if first is None else dict(first)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from __future__ import annotations\r
-# from os import stat\r
-import json\r
-from o2dms.domain import events\r
-from o2dms.domain.states import NfDeploymentState\r
-\r
-from o2common.domain.base import AgRoot, Serializer\r
-\r
-\r
-class NfDeploymentDesc(AgRoot, Serializer):\r
- def __init__(self, id: str, name: str, dmsId: str, description: str = '',\r
- inputParams: str = '', outputParams: str = '',\r
- artifactRepoUrl: str = '', artifactName: str = '') -> None:\r
- super().__init__()\r
- self.id = id\r
- self.version_number = 0\r
- self.deploymentManagerId = dmsId\r
- self.name = name\r
- self.description = description\r
- self.artifactRepoUrl = artifactRepoUrl\r
- self.artifactName = artifactName\r
- self.status = 0\r
-\r
- if type(inputParams) is str:\r
- inputParams = json.loads(inputParams)\r
- self.inputParams = json.dumps(inputParams)\r
-\r
- if type(outputParams) is str:\r
- outputParams = json.loads(outputParams)\r
- self.outputParams = json.dumps(outputParams)\r
-\r
- # self.extensions = []\r
-\r
-\r
-class NfDeployment(AgRoot, Serializer):\r
- def __init__(self, id: str, name: str, dmsId: str, description: str = '',\r
- descriptorId: str = '', parentId: str = '',) -> None:\r
- super().__init__()\r
- self.id = id\r
- self.version_number = 0\r
- self.deploymentManagerId = dmsId\r
- self.name = name\r
- self.description = description\r
- self.descriptorId = descriptorId\r
- self.parentDeploymentId = parentId\r
- self.status = NfDeploymentState.Initial\r
-\r
- def transit_state(self, state: NfDeploymentState):\r
- if (self.status != state):\r
- self._append_event(self.status, state)\r
- # self.status = state\r
-\r
- def set_state(self, state: NfDeploymentState):\r
- if (self.status != state):\r
- self.status = state\r
-\r
- def _append_event(self, fromState, toState):\r
- if not hasattr(self, "events"):\r
- self.events = []\r
- self.events.append(\r
- events.NfDeploymentStateChanged(\r
- NfDeploymentId=self.id, FromState=fromState, ToState=toState))\r
-\r
-\r
-class NfOCloudVResource(AgRoot, Serializer):\r
- def __init__(self, id: str, name: str, dmsId: str, description: str = '',\r
- descriptorId: str = '', nfDeploymentId: str = '',\r
- vresourceType: int = 0,) -> None:\r
- super().__init__()\r
- self.id = id\r
- self.version_number = 0\r
- self.deploymentManagerId = dmsId\r
- self.name = name\r
- self.description = description\r
- self.descriptorId = descriptorId\r
- self.nfDeploymentId = nfDeploymentId\r
- self.vresourceType = vresourceType\r
- self.status = 0\r
- self.metadata = []\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 __future__ import annotations
+# from os import stat
+import json
+from o2dms.domain import events
+from o2dms.domain.states import NfDeploymentState
+
+from o2common.domain.base import AgRoot, Serializer
+
+
+class NfDeploymentDesc(AgRoot, Serializer):
+ def __init__(self, id: str, name: str, dmsId: str, description: str = '',
+ inputParams: str = '', outputParams: str = '',
+ artifactRepoUrl: str = '', artifactName: str = '') -> None:
+ super().__init__()
+ self.id = id
+ self.version_number = 0
+ self.deploymentManagerId = dmsId
+ self.name = name
+ self.description = description
+ self.artifactRepoUrl = artifactRepoUrl
+ self.artifactName = artifactName
+ self.status = 0
+
+ if type(inputParams) is str:
+ inputParams = json.loads(inputParams)
+ self.inputParams = json.dumps(inputParams)
+
+ if type(outputParams) is str:
+ outputParams = json.loads(outputParams)
+ self.outputParams = json.dumps(outputParams)
+
+ # self.extensions = []
+
+
+class NfDeployment(AgRoot, Serializer):
+ def __init__(self, id: str, name: str, dmsId: str, description: str = '',
+ descriptorId: str = '', parentId: str = '',) -> None:
+ super().__init__()
+ self.id = id
+ self.version_number = 0
+ self.deploymentManagerId = dmsId
+ self.name = name
+ self.description = description
+ self.descriptorId = descriptorId
+ self.parentDeploymentId = parentId
+ self.status = NfDeploymentState.Initial
+
+ def transit_state(self, state: NfDeploymentState):
+ if (self.status != state):
+ self._append_event(self.status, state)
+ # self.status = state
+
+ def set_state(self, state: NfDeploymentState):
+ if (self.status != state):
+ self.status = state
+
+ def _append_event(self, fromState, toState):
+ if not hasattr(self, "events"):
+ self.events = []
+ self.events.append(
+ events.NfDeploymentStateChanged(
+ NfDeploymentId=self.id, FromState=fromState, ToState=toState))
+
+
+class NfOCloudVResource(AgRoot, Serializer):
+ def __init__(self, id: str, name: str, dmsId: str, description: str = '',
+ descriptorId: str = '', nfDeploymentId: str = '',
+ vresourceType: int = 0,) -> None:
+ super().__init__()
+ self.id = id
+ self.version_number = 0
+ self.deploymentManagerId = dmsId
+ self.name = name
+ self.description = description
+ self.descriptorId = descriptorId
+ self.nfDeploymentId = nfDeploymentId
+ self.vresourceType = vresourceType
+ self.status = 0
+ self.metadata = []
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import abc\r
-from typing import List, Set\r
-from o2dms.domain import dms\r
-\r
-\r
-class NfDeploymentRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[dms.NfDeployment]\r
-\r
- def add(self, nfdeployment: dms.NfDeployment):\r
- self._add(nfdeployment)\r
- self.seen.add(nfdeployment)\r
-\r
- def get(self, nfdeployment_id) -> dms.NfDeployment:\r
- nfdeployment = self._get(nfdeployment_id)\r
- if nfdeployment:\r
- self.seen.add(nfdeployment)\r
- return nfdeployment\r
-\r
- def list(self) -> List[dms.NfDeployment]:\r
- return self._list()\r
-\r
- def update(self, id, **kwargs):\r
- self._update(id, **kwargs)\r
-\r
- def delete(self, nfdeployment_id):\r
- self._delete(nfdeployment_id)\r
-\r
- def count(self, **kwargs):\r
- return self._count(**kwargs)\r
-\r
- @abc.abstractmethod\r
- def _add(self, nfdeployment: dms.NfDeployment):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, nfdeployment_id) -> dms.NfDeployment:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, id, **kwargs):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _delete(self, nfdeployment_id):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _count(self, **kwargs):\r
- raise NotImplementedError\r
-\r
-\r
-class NfDeploymentDescRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[dms.NfDeploymentDesc]\r
-\r
- def add(self, nfdeployment_descriptor: dms.NfDeploymentDesc):\r
- self._add(nfdeployment_descriptor)\r
- self.seen.add(nfdeployment_descriptor)\r
-\r
- def get(self, nfdeployment_descriptor_id) -> dms.NfDeploymentDesc:\r
- nfdeployment_descriptor = self._get(nfdeployment_descriptor_id)\r
- if nfdeployment_descriptor:\r
- self.seen.add(nfdeployment_descriptor)\r
- return nfdeployment_descriptor\r
-\r
- def list(self) -> List[dms.NfDeploymentDesc]:\r
- return self._list()\r
-\r
- def update(self, id, **kwargs):\r
- self._update(id, **kwargs)\r
-\r
- def delete(self, nfdeployment_descriptor_id):\r
- self._delete(nfdeployment_descriptor_id)\r
-\r
- def count(self, **kwargs):\r
- return self._count(**kwargs)\r
-\r
- @abc.abstractmethod\r
- def _add(self, nfdeployment_descriptor: dms.NfDeploymentDesc):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, nfdeployment_descriptor_id) -> dms.NfDeploymentDesc:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, id, **kwargs):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _delete(self, nfdeployment_descriptor_id):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _count(self, **kwargs):\r
- raise NotImplementedError\r
-\r
-\r
-class NfOCloudVResourceRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[dms.NfOCloudVResource]\r
-\r
- def add(self, nfocloudvres: dms.NfOCloudVResource):\r
- self._add(nfocloudvres)\r
- self.seen.add(nfocloudvres)\r
-\r
- def get(self, nfocloudvres_id) -> dms.NfOCloudVResource:\r
- nfocloudvres = self._get(nfocloudvres_id)\r
- if nfocloudvres:\r
- self.seen.add(nfocloudvres)\r
- return nfocloudvres\r
-\r
- def list(self) -> List[dms.NfOCloudVResource]:\r
- return self._list()\r
-\r
- def update(self, nfocloudvres_id, **kwargs):\r
- self._update(nfocloudvres_id, **kwargs)\r
-\r
- def delete(self, nfocloudvres_id):\r
- self._delete(nfocloudvres_id)\r
-\r
- @abc.abstractmethod\r
- def _add(self, nfocloudvres: dms.NfOCloudVResource):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, nfocloudvres_id) -> dms.NfOCloudVResource:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, nfocloudvres_id, **kwargs):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _delete(self, nfocloudvres_id):\r
- raise NotImplementedError\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 abc
+from typing import List, Set
+from o2dms.domain import dms
+
+
+class NfDeploymentRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[dms.NfDeployment]
+
+ def add(self, nfdeployment: dms.NfDeployment):
+ self._add(nfdeployment)
+ self.seen.add(nfdeployment)
+
+ def get(self, nfdeployment_id) -> dms.NfDeployment:
+ nfdeployment = self._get(nfdeployment_id)
+ if nfdeployment:
+ self.seen.add(nfdeployment)
+ return nfdeployment
+
+ def list(self) -> List[dms.NfDeployment]:
+ return self._list()
+
+ def update(self, id, **kwargs):
+ self._update(id, **kwargs)
+
+ def delete(self, nfdeployment_id):
+ self._delete(nfdeployment_id)
+
+ def count(self, **kwargs):
+ return self._count(**kwargs)
+
+ @abc.abstractmethod
+ def _add(self, nfdeployment: dms.NfDeployment):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, nfdeployment_id) -> dms.NfDeployment:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, id, **kwargs):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _delete(self, nfdeployment_id):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _count(self, **kwargs):
+ raise NotImplementedError
+
+
+class NfDeploymentDescRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[dms.NfDeploymentDesc]
+
+ def add(self, nfdeployment_descriptor: dms.NfDeploymentDesc):
+ self._add(nfdeployment_descriptor)
+ self.seen.add(nfdeployment_descriptor)
+
+ def get(self, nfdeployment_descriptor_id) -> dms.NfDeploymentDesc:
+ nfdeployment_descriptor = self._get(nfdeployment_descriptor_id)
+ if nfdeployment_descriptor:
+ self.seen.add(nfdeployment_descriptor)
+ return nfdeployment_descriptor
+
+ def list(self) -> List[dms.NfDeploymentDesc]:
+ return self._list()
+
+ def update(self, id, **kwargs):
+ self._update(id, **kwargs)
+
+ def delete(self, nfdeployment_descriptor_id):
+ self._delete(nfdeployment_descriptor_id)
+
+ def count(self, **kwargs):
+ return self._count(**kwargs)
+
+ @abc.abstractmethod
+ def _add(self, nfdeployment_descriptor: dms.NfDeploymentDesc):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, nfdeployment_descriptor_id) -> dms.NfDeploymentDesc:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, id, **kwargs):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _delete(self, nfdeployment_descriptor_id):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _count(self, **kwargs):
+ raise NotImplementedError
+
+
+class NfOCloudVResourceRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[dms.NfOCloudVResource]
+
+ def add(self, nfocloudvres: dms.NfOCloudVResource):
+ self._add(nfocloudvres)
+ self.seen.add(nfocloudvres)
+
+ def get(self, nfocloudvres_id) -> dms.NfOCloudVResource:
+ nfocloudvres = self._get(nfocloudvres_id)
+ if nfocloudvres:
+ self.seen.add(nfocloudvres)
+ return nfocloudvres
+
+ def list(self) -> List[dms.NfOCloudVResource]:
+ return self._list()
+
+ def update(self, nfocloudvres_id, **kwargs):
+ self._update(nfocloudvres_id, **kwargs)
+
+ def delete(self, nfocloudvres_id):
+ self._delete(nfocloudvres_id)
+
+ @abc.abstractmethod
+ def _add(self, nfocloudvres: dms.NfOCloudVResource):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, nfocloudvres_id) -> dms.NfOCloudVResource:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, nfocloudvres_id, **kwargs):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _delete(self, nfocloudvres_id):
+ raise NotImplementedError
-\r
-# Copyright (C) 2022 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# pylint: disable=too-few-public-methods\r
-\r
-from o2common.domain.exceptions import Orano2Exception\r
-\r
-\r
-class NfdeploymentNotFoundError(Orano2Exception):\r
- pass\r
+
+# Copyright (C) 2022 Wind River Systems, Inc.
+#
+# 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.
+
+# pylint: disable=too-few-public-methods
+
+from o2common.domain.exceptions import Orano2Exception
+
+
+class NfdeploymentNotFoundError(Orano2Exception):
+ pass
-\r
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from __future__ import annotations\r
-from dataclasses import dataclass\r
-\r
-\r
-@dataclass\r
-class NfDeploymentState():\r
- Initial = 0\r
- # NotInstalled = 1\r
- Installing = 2\r
- Installed = 3\r
- Updating = 4\r
- Uninstalling = 5\r
- Abnormal = 6\r
- Deleting = 7\r
- # Aborting = 8\r
+
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 __future__ import annotations
+from dataclasses import dataclass
+
+
+@dataclass
+class NfDeploymentState():
+ Initial = 0
+ # NotInstalled = 1
+ Installing = 2
+ Installed = 3
+ Updating = 4
+ Uninstalling = 5
+ Abnormal = 6
+ Deleting = 7
+ # Aborting = 8
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# client talking to Stx standalone\r
-\r
-import uuid\r
-from o2common.service.client.base_client import BaseClient\r
-from typing import List\r
-# Optional, Set\r
-from o2ims.domain import stx_object as ocloudModel\r
-from o2common.config import config\r
-from o2ims.domain.resource_type import ResourceTypeEnum\r
-\r
-# from dcmanagerclient.api import client\r
-from cgtsclient.client import get_client\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class StxSaOcloudClient(BaseClient):\r
- def __init__(self, driver=None):\r
- super().__init__()\r
- self.driver = driver if driver else StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getInstanceInfo()\r
-\r
- def _list(self, **filters):\r
- return [self.driver.getInstanceInfo()]\r
-\r
-\r
-class StxSaResourcePoolClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getInstanceInfo()\r
-\r
- def _list(self, **filters):\r
- return [self.driver.getInstanceInfo()]\r
-\r
-\r
-class StxSaDmsClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, name) -> ocloudModel.StxGenericModel:\r
- return self.driver.getK8sDetail(name)\r
-\r
- def _list(self, **filters):\r
- return self.driver.getK8sList(**filters)\r
-\r
-\r
-class StxPserverClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getPserver(id)\r
-\r
- def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- return self.driver.getPserverList(**filters)\r
-\r
-\r
-class StxCpuClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- # self._pserver_id = pserver_id\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getCpu(id)\r
-\r
- def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- return self.driver.getCpuList(**filters)\r
-\r
-\r
-class StxMemClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getMem(id)\r
-\r
- def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- return self.driver.getMemList(**filters)\r
-\r
-\r
-class StxEthClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getEthernet(id)\r
-\r
- def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- return self.driver.getEthernetList(**filters)\r
-\r
-\r
-class StxIfClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getIf(id)\r
-\r
- def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- return self.driver.getIfList(**filters)\r
-\r
-\r
-class StxIfPortClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- self.driver = StxSaClientImp()\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.driver.getPort(id)\r
-\r
- def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- return self.driver.getPortList(**filters)\r
-\r
-\r
-# internal driver which implement client call to Stx Standalone instance\r
-class StxSaClientImp(object):\r
- def __init__(self, stx_client=None):\r
- super().__init__()\r
- self.stxclient = stx_client if stx_client else self.getStxClient()\r
-\r
- def getStxClient(self):\r
- os_client_args = config.get_stx_access_info()\r
- config_client = get_client(**os_client_args)\r
- return config_client\r
-\r
- def getInstanceInfo(self) -> ocloudModel.StxGenericModel:\r
- systems = self.stxclient.isystem.list()\r
- logger.debug('systems:' + str(systems[0].to_dict()))\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.OCLOUD, systems[0]) if systems else None\r
-\r
- def getPserverList(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- # resourcepoolid = filters.get("resourcepoolid", None)\r
- hosts = self.stxclient.ihost.list()\r
- logger.debug('host 1:' + str(hosts[0].to_dict()))\r
- return [ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER, self._hostconverter(host))\r
- for host in hosts if host and host.availability == 'available']\r
-\r
- def getPserver(self, id) -> ocloudModel.StxGenericModel:\r
- host = self.stxclient.ihost.get(id)\r
- logger.debug('host:' + str(host.to_dict()))\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER, self._hostconverter(host))\r
-\r
- def getK8sList(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- k8sclusters = self.stxclient.kube_cluster.list()\r
- logger.debug('k8sresources[0]:' + str(k8sclusters[0].to_dict()))\r
- return [ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.DMS,\r
- self._k8sconverter(k8sres), self._k8shasher(k8sres))\r
- for k8sres in k8sclusters if k8sres]\r
-\r
- def getK8sDetail(self, name) -> ocloudModel.StxGenericModel:\r
- if not name:\r
- k8sclusters = self.stxclient.kube_cluster.list()\r
- # logger.debug("k8sresources[0]:" + str(k8sclusters[0].to_dict()))\r
- k8scluster = k8sclusters.pop()\r
- else:\r
- k8scluster = self.stxclient.kube_cluster.get(name)\r
-\r
- if not k8scluster:\r
- return None\r
- logger.debug('k8sresource:' + str(k8scluster.to_dict()))\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.DMS,\r
- self._k8sconverter(k8scluster), self._k8shasher(k8scluster))\r
-\r
- def getCpuList(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- hostid = filters.get('hostid', None)\r
- assert (hostid is not None), 'missing hostid to query icpu list'\r
- cpulist = self.stxclient.icpu.list(hostid)\r
- return [ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_CPU,\r
- self._cpuconverter(cpures)) for cpures in cpulist if cpures]\r
-\r
- def getCpu(self, id) -> ocloudModel.StxGenericModel:\r
- cpuinfo = self.stxclient.icpu.get(id)\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_CPU, self._cpuconverter(cpuinfo))\r
-\r
- def getMemList(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- hostid = filters.get('hostid', None)\r
- assert (hostid is not None), 'missing hostid to query imem list'\r
- memlist = self.stxclient.imemory.list(hostid)\r
- return [ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_RAM,\r
- self._memconverter(memories)) for memories in memlist if memories]\r
-\r
- def getMem(self, id) -> ocloudModel.StxGenericModel:\r
- meminfo = self.stxclient.imemory.get(id)\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_RAM, self._memconverter(meminfo))\r
-\r
- def getEthernetList(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- hostid = filters.get('hostid', None)\r
- assert (hostid is not None), 'missing hostid to query port list'\r
- ethlist = self.stxclient.ethernet_port.list(hostid)\r
- return [ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_ETH,\r
- self._ethconverter(eth)) for eth in ethlist if eth]\r
-\r
- def getEthernet(self, id) -> ocloudModel.StxGenericModel:\r
- ethinfo = self.stxclient.ethernet_port.get(id)\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_ETH, self._ethconverter(ethinfo))\r
-\r
- def getIfList(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- hostid = filters.get('hostid', None)\r
- assert (hostid is not None), 'missing hostid to query iinterface list'\r
- iflist = self.stxclient.iinterface.list(hostid)\r
- return [ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_IF,\r
- self._ifconverter(ifs)) for ifs in iflist if ifs]\r
-\r
- def getIf(self, id) -> ocloudModel.StxGenericModel:\r
- ifinfo = self.stxclient.iinterface.get(id)\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_IF, self._ifconverter(ifinfo))\r
-\r
- def getPortList(self, **filters) -> List[ocloudModel.StxGenericModel]:\r
- ifid = filters.get('interfaceid', None)\r
- assert (ifid is not None), 'missing interface id to query port list'\r
- portlist = self.stxclient.iinterface.list_ports(ifid)\r
- return [ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_IF_PORT,\r
- port) for port in portlist if port]\r
-\r
- def getPort(self, id) -> ocloudModel.StxGenericModel:\r
- portinfo = self.stxclient.port.get(id)\r
- return ocloudModel.StxGenericModel(\r
- ResourceTypeEnum.PSERVER_IF_PORT, portinfo)\r
-\r
- def _getIsystems(self):\r
- return self.stxclient.isystem.list()\r
-\r
- def _getIsystem(self, id=None):\r
- if id:\r
- return self.stxclient.isystem.get(id)\r
- else:\r
- isystems = self.stxclient.isystem.list()\r
- if len(isystems) != 1 and not id:\r
- raise Exception('No system uuid was provided and '\r
- 'more than one system exists in the account.')\r
- return isystems[0]\r
-\r
- @ staticmethod\r
- def _hostconverter(host):\r
- setattr(host, 'name', host.hostname)\r
- return host\r
-\r
- @ staticmethod\r
- def _cpuconverter(cpu):\r
- setattr(cpu, 'name', cpu.ihost_uuid.split(\r
- '-', 1)[0] + '-cpu-'+str(cpu.cpu))\r
- return cpu\r
-\r
- @ staticmethod\r
- def _memconverter(mem):\r
- setattr(mem, 'name', mem.ihost_uuid.split('-', 1)[0] +\r
- '-mem-node-'+str(mem.numa_node))\r
- return mem\r
-\r
- @ staticmethod\r
- def _ethconverter(eth):\r
- setattr(eth, 'name', eth.host_uuid.split('-', 1)[0] + '-'+eth.name)\r
- setattr(eth, 'updated_at', None)\r
- setattr(eth, 'created_at', None)\r
- return eth\r
-\r
- @ staticmethod\r
- def _ifconverter(ifs):\r
- setattr(ifs, 'name', ifs.ihost_uuid.split('-', 1)[0] + '-'+ifs.ifname)\r
- setattr(ifs, 'updated_at', None)\r
- setattr(ifs, 'created_at', None)\r
- return ifs\r
-\r
- @ staticmethod\r
- def _k8sconverter(cluster):\r
- setattr(cluster, 'name', cluster.cluster_name)\r
- setattr(cluster, 'uuid',\r
- uuid.uuid3(uuid.NAMESPACE_URL, cluster.cluster_name))\r
- setattr(cluster, 'updated_at', None)\r
- setattr(cluster, 'created_at', None)\r
- setattr(cluster, 'events', [])\r
- logger.debug('k8s cluster name/uuid:' +\r
- cluster.name + '/' + str(cluster.uuid))\r
- return cluster\r
-\r
- @ staticmethod\r
- def _k8shasher(cluster):\r
- return str(hash((cluster.cluster_name,\r
- cluster.cluster_api_endpoint, cluster.admin_user)))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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.
+
+# client talking to Stx standalone
+
+import uuid
+from o2common.service.client.base_client import BaseClient
+from typing import List
+# Optional, Set
+from o2ims.domain import stx_object as ocloudModel
+from o2common.config import config
+from o2ims.domain.resource_type import ResourceTypeEnum
+
+# from dcmanagerclient.api import client
+from cgtsclient.client import get_client
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class StxSaOcloudClient(BaseClient):
+ def __init__(self, driver=None):
+ super().__init__()
+ self.driver = driver if driver else StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getInstanceInfo()
+
+ def _list(self, **filters):
+ return [self.driver.getInstanceInfo()]
+
+
+class StxSaResourcePoolClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ self.driver = StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getInstanceInfo()
+
+ def _list(self, **filters):
+ return [self.driver.getInstanceInfo()]
+
+
+class StxSaDmsClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ self.driver = StxSaClientImp()
+
+ def _get(self, name) -> ocloudModel.StxGenericModel:
+ return self.driver.getK8sDetail(name)
+
+ def _list(self, **filters):
+ return self.driver.getK8sList(**filters)
+
+
+class StxPserverClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ self.driver = StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getPserver(id)
+
+ def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ return self.driver.getPserverList(**filters)
+
+
+class StxCpuClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ # self._pserver_id = pserver_id
+ self.driver = StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getCpu(id)
+
+ def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ return self.driver.getCpuList(**filters)
+
+
+class StxMemClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ self.driver = StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getMem(id)
+
+ def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ return self.driver.getMemList(**filters)
+
+
+class StxEthClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ self.driver = StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getEthernet(id)
+
+ def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ return self.driver.getEthernetList(**filters)
+
+
+class StxIfClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ self.driver = StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getIf(id)
+
+ def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ return self.driver.getIfList(**filters)
+
+
+class StxIfPortClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ self.driver = StxSaClientImp()
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.driver.getPort(id)
+
+ def _list(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ return self.driver.getPortList(**filters)
+
+
+# internal driver which implement client call to Stx Standalone instance
+class StxSaClientImp(object):
+ def __init__(self, stx_client=None):
+ super().__init__()
+ self.stxclient = stx_client if stx_client else self.getStxClient()
+
+ def getStxClient(self):
+ os_client_args = config.get_stx_access_info()
+ config_client = get_client(**os_client_args)
+ return config_client
+
+ def getInstanceInfo(self) -> ocloudModel.StxGenericModel:
+ systems = self.stxclient.isystem.list()
+ logger.debug('systems:' + str(systems[0].to_dict()))
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.OCLOUD, systems[0]) if systems else None
+
+ def getPserverList(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ # resourcepoolid = filters.get("resourcepoolid", None)
+ hosts = self.stxclient.ihost.list()
+ logger.debug('host 1:' + str(hosts[0].to_dict()))
+ return [ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER, self._hostconverter(host))
+ for host in hosts if host and host.availability == 'available']
+
+ def getPserver(self, id) -> ocloudModel.StxGenericModel:
+ host = self.stxclient.ihost.get(id)
+ logger.debug('host:' + str(host.to_dict()))
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER, self._hostconverter(host))
+
+ def getK8sList(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ k8sclusters = self.stxclient.kube_cluster.list()
+ logger.debug('k8sresources[0]:' + str(k8sclusters[0].to_dict()))
+ return [ocloudModel.StxGenericModel(
+ ResourceTypeEnum.DMS,
+ self._k8sconverter(k8sres), self._k8shasher(k8sres))
+ for k8sres in k8sclusters if k8sres]
+
+ def getK8sDetail(self, name) -> ocloudModel.StxGenericModel:
+ if not name:
+ k8sclusters = self.stxclient.kube_cluster.list()
+ # logger.debug("k8sresources[0]:" + str(k8sclusters[0].to_dict()))
+ k8scluster = k8sclusters.pop()
+ else:
+ k8scluster = self.stxclient.kube_cluster.get(name)
+
+ if not k8scluster:
+ return None
+ logger.debug('k8sresource:' + str(k8scluster.to_dict()))
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.DMS,
+ self._k8sconverter(k8scluster), self._k8shasher(k8scluster))
+
+ def getCpuList(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ hostid = filters.get('hostid', None)
+ assert (hostid is not None), 'missing hostid to query icpu list'
+ cpulist = self.stxclient.icpu.list(hostid)
+ return [ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_CPU,
+ self._cpuconverter(cpures)) for cpures in cpulist if cpures]
+
+ def getCpu(self, id) -> ocloudModel.StxGenericModel:
+ cpuinfo = self.stxclient.icpu.get(id)
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_CPU, self._cpuconverter(cpuinfo))
+
+ def getMemList(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ hostid = filters.get('hostid', None)
+ assert (hostid is not None), 'missing hostid to query imem list'
+ memlist = self.stxclient.imemory.list(hostid)
+ return [ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_RAM,
+ self._memconverter(memories)) for memories in memlist if memories]
+
+ def getMem(self, id) -> ocloudModel.StxGenericModel:
+ meminfo = self.stxclient.imemory.get(id)
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_RAM, self._memconverter(meminfo))
+
+ def getEthernetList(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ hostid = filters.get('hostid', None)
+ assert (hostid is not None), 'missing hostid to query port list'
+ ethlist = self.stxclient.ethernet_port.list(hostid)
+ return [ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_ETH,
+ self._ethconverter(eth)) for eth in ethlist if eth]
+
+ def getEthernet(self, id) -> ocloudModel.StxGenericModel:
+ ethinfo = self.stxclient.ethernet_port.get(id)
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_ETH, self._ethconverter(ethinfo))
+
+ def getIfList(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ hostid = filters.get('hostid', None)
+ assert (hostid is not None), 'missing hostid to query iinterface list'
+ iflist = self.stxclient.iinterface.list(hostid)
+ return [ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_IF,
+ self._ifconverter(ifs)) for ifs in iflist if ifs]
+
+ def getIf(self, id) -> ocloudModel.StxGenericModel:
+ ifinfo = self.stxclient.iinterface.get(id)
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_IF, self._ifconverter(ifinfo))
+
+ def getPortList(self, **filters) -> List[ocloudModel.StxGenericModel]:
+ ifid = filters.get('interfaceid', None)
+ assert (ifid is not None), 'missing interface id to query port list'
+ portlist = self.stxclient.iinterface.list_ports(ifid)
+ return [ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_IF_PORT,
+ port) for port in portlist if port]
+
+ def getPort(self, id) -> ocloudModel.StxGenericModel:
+ portinfo = self.stxclient.port.get(id)
+ return ocloudModel.StxGenericModel(
+ ResourceTypeEnum.PSERVER_IF_PORT, portinfo)
+
+ def _getIsystems(self):
+ return self.stxclient.isystem.list()
+
+ def _getIsystem(self, id=None):
+ if id:
+ return self.stxclient.isystem.get(id)
+ else:
+ isystems = self.stxclient.isystem.list()
+ if len(isystems) != 1 and not id:
+ raise Exception('No system uuid was provided and '
+ 'more than one system exists in the account.')
+ return isystems[0]
+
+ @ staticmethod
+ def _hostconverter(host):
+ setattr(host, 'name', host.hostname)
+ return host
+
+ @ staticmethod
+ def _cpuconverter(cpu):
+ setattr(cpu, 'name', cpu.ihost_uuid.split(
+ '-', 1)[0] + '-cpu-'+str(cpu.cpu))
+ return cpu
+
+ @ staticmethod
+ def _memconverter(mem):
+ setattr(mem, 'name', mem.ihost_uuid.split('-', 1)[0] +
+ '-mem-node-'+str(mem.numa_node))
+ return mem
+
+ @ staticmethod
+ def _ethconverter(eth):
+ setattr(eth, 'name', eth.host_uuid.split('-', 1)[0] + '-'+eth.name)
+ setattr(eth, 'updated_at', None)
+ setattr(eth, 'created_at', None)
+ return eth
+
+ @ staticmethod
+ def _ifconverter(ifs):
+ setattr(ifs, 'name', ifs.ihost_uuid.split('-', 1)[0] + '-'+ifs.ifname)
+ setattr(ifs, 'updated_at', None)
+ setattr(ifs, 'created_at', None)
+ return ifs
+
+ @ staticmethod
+ def _k8sconverter(cluster):
+ setattr(cluster, 'name', cluster.cluster_name)
+ setattr(cluster, 'uuid',
+ uuid.uuid3(uuid.NAMESPACE_URL, cluster.cluster_name))
+ setattr(cluster, 'updated_at', None)
+ setattr(cluster, 'created_at', None)
+ setattr(cluster, 'events', [])
+ logger.debug('k8s cluster name/uuid:' +
+ cluster.name + '/' + str(cluster.uuid))
+ return cluster
+
+ @ staticmethod
+ def _k8shasher(cluster):
+ return str(hash((cluster.cluster_name,
+ cluster.cluster_api_endpoint, cluster.admin_user)))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# from datetime import datetime\r
-from sqlalchemy import (\r
- Table,\r
- MetaData,\r
- Column,\r
- # Integer,\r
- String,\r
- # Date,\r
- DateTime,\r
- # engine,\r
- # ForeignKey,\r
- # event,\r
- Enum\r
-)\r
-\r
-# from sqlalchemy.orm import mapper\r
-\r
-# from o2ims.domain import stx_object as ocloudModel\r
-\r
-from o2common.service.unit_of_work import AbstractUnitOfWork\r
-# from o2ims.adapter.unit_of_work import SqlAlchemyUnitOfWork\r
-from o2ims.domain.resource_type import ResourceTypeEnum\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-metadata = MetaData()\r
-\r
-stxobject = Table(\r
- "stxcache",\r
- metadata,\r
- Column("id", String(255), primary_key=True),\r
- Column("type", Enum(ResourceTypeEnum, native_enum=False)),\r
- Column("name", String(255)),\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("content", String)\r
-)\r
-\r
-\r
-def start_o2ims_stx_mappers(uow: AbstractUnitOfWork):\r
- return\r
- # logger.info("Starting O2 IMS Stx mappers")\r
- # mapper(ocloudModel.StxGenericModel, stxobject)\r
-\r
- # with uow:\r
- # engine1 = uow.session.get_bind()\r
- # metadata.create_all(engine1)\r
- # uow.commit()\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 datetime import datetime
+from sqlalchemy import (
+ Table,
+ MetaData,
+ Column,
+ # Integer,
+ String,
+ # Date,
+ DateTime,
+ # engine,
+ # ForeignKey,
+ # event,
+ Enum
+)
+
+# from sqlalchemy.orm import mapper
+
+# from o2ims.domain import stx_object as ocloudModel
+
+from o2common.service.unit_of_work import AbstractUnitOfWork
+# from o2ims.adapter.unit_of_work import SqlAlchemyUnitOfWork
+from o2ims.domain.resource_type import ResourceTypeEnum
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+metadata = MetaData()
+
+stxobject = Table(
+ "stxcache",
+ metadata,
+ Column("id", String(255), primary_key=True),
+ Column("type", Enum(ResourceTypeEnum, native_enum=False)),
+ Column("name", String(255)),
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("content", String)
+)
+
+
+def start_o2ims_stx_mappers(uow: AbstractUnitOfWork):
+ return
+ # logger.info("Starting O2 IMS Stx mappers")
+ # mapper(ocloudModel.StxGenericModel, stxobject)
+
+ # with uow:
+ # engine1 = uow.session.get_bind()
+ # metadata.create_all(engine1)
+ # uow.commit()
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# from typing_extensions import Required\r
-from retry import retry\r
-from sqlalchemy import (\r
- Table,\r
- MetaData,\r
- Column,\r
- Integer,\r
- String,\r
- Text,\r
- Enum,\r
- # Date,\r
- DateTime,\r
- ForeignKey,\r
- # Boolean,\r
- # engine,\r
- # event,\r
- exc,\r
-)\r
-\r
-from sqlalchemy.orm import mapper, relationship\r
-# from sqlalchemy.sql.sqltypes import Integer\r
-\r
-from o2ims.domain import ocloud as ocloudModel\r
-from o2ims.domain import subscription_obj as subModel\r
-from o2ims.domain import configuration_obj as confModel\r
-from o2ims.domain.resource_type import ResourceTypeEnum\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-metadata = MetaData()\r
-\r
-ocloud = Table(\r
- "ocloud",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("oCloudId", String(255), primary_key=True),\r
- Column("globalcloudId", String(255)),\r
- Column("name", String(255)),\r
- Column("description", String(255)),\r
- Column("infrastructureManagementServiceEndpoint", String(255))\r
- # Column("extensions", String(1024))\r
-)\r
-\r
-resourcetype = Table(\r
- "resourcetype",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
-\r
- Column("resourceTypeId", String(255), primary_key=True),\r
- Column("resourceTypeEnum", Enum(\r
- ResourceTypeEnum, native_enum=False), nullable=False),\r
- Column("oCloudId", ForeignKey("ocloud.oCloudId")),\r
- Column("name", String(255)),\r
- Column("vendor", String(255)),\r
- Column("model", String(255)),\r
- Column("version", String(255)),\r
- Column("description", String(255)),\r
- # Column("extensions", String(1024))\r
-)\r
-\r
-resourcepool = Table(\r
- "resourcepool",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("resourcePoolId", String(255), primary_key=True),\r
- Column("oCloudId", ForeignKey("ocloud.oCloudId")),\r
- Column("globalLocationId", String(255)),\r
- Column("name", String(255)),\r
- Column("location", String(255)),\r
- Column("description", String(255)),\r
- # Column("resources", String(1024))\r
- # Column("extensions", String(1024))\r
-)\r
-\r
-resource = Table(\r
- "resource",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("resourceId", String(255), primary_key=True),\r
- Column("resourceTypeId", ForeignKey("resourcetype.resourceTypeId")),\r
- Column("resourcePoolId", ForeignKey("resourcepool.resourcePoolId")),\r
- Column("name", String(255)),\r
- # Column("globalAssetId", String(255)),\r
- Column("parentId", String(255)),\r
- Column("description", String(255)),\r
- Column("elements", Text())\r
- # Column("extensions", String(1024))\r
-)\r
-\r
-deploymentmanager = Table(\r
- "deploymentmanager",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("deploymentManagerId", String(255), primary_key=True),\r
- Column("oCloudId", ForeignKey("ocloud.oCloudId")),\r
- Column("name", String(255)),\r
- Column("description", String(255)),\r
- Column("deploymentManagementServiceEndpoint", String(255)),\r
- Column("supportedLocations", String(255)),\r
- Column("capabilities", String(255)),\r
- Column("capacity", String(255)),\r
- # Column("extensions", String(1024))\r
-)\r
-\r
-subscription = Table(\r
- "subscription",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
- Column("hash", String(255)),\r
- Column("version_number", Integer),\r
-\r
- Column("subscriptionId", String(255), primary_key=True),\r
- Column("callback", String(255)),\r
- Column("consumerSubscriptionId", String(255)),\r
- Column("filter", String(255)),\r
-)\r
-\r
-configuration = Table(\r
- "configuration",\r
- metadata,\r
- Column("updatetime", DateTime),\r
- Column("createtime", DateTime),\r
-\r
- Column("configurationId", String(255), primary_key=True),\r
- Column("conftype", String(255)),\r
- Column("callback", String(255)),\r
- Column("status", String(255)),\r
- Column("comments", String(255)),\r
-)\r
-\r
-\r
-@retry((exc.IntegrityError), tries=3, delay=2)\r
-def wait_for_metadata_ready(engine):\r
- # wait for mapper ready\r
- metadata.create_all(engine, checkfirst=True)\r
- logger.info("metadata is ready")\r
-\r
-\r
-def start_o2ims_mappers(engine=None):\r
- logger.info("Starting O2 IMS mappers")\r
-\r
- dm_mapper = mapper(ocloudModel.DeploymentManager, deploymentmanager)\r
- resourcepool_mapper = mapper(ocloudModel.ResourcePool, resourcepool)\r
- resourcetype_mapper = mapper(ocloudModel.ResourceType, resourcetype)\r
- mapper(\r
- ocloudModel.Ocloud,\r
- ocloud,\r
- properties={\r
- "deploymentManagers": relationship(dm_mapper),\r
- "resourceTypes": relationship(resourcetype_mapper),\r
- "resourcePools": relationship(resourcepool_mapper)\r
- })\r
- mapper(\r
- ocloudModel.Resource,\r
- resource,\r
- properties={\r
- "resourceTypes": relationship(resourcetype_mapper),\r
- "resourcePools": relationship(resourcepool_mapper)\r
- }\r
- )\r
- mapper(subModel.Subscription, subscription)\r
- mapper(confModel.Configuration, configuration)\r
-\r
- if engine is not None:\r
- wait_for_metadata_ready(engine)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 typing_extensions import Required
+from retry import retry
+from sqlalchemy import (
+ Table,
+ MetaData,
+ Column,
+ Integer,
+ String,
+ Text,
+ Enum,
+ # Date,
+ DateTime,
+ ForeignKey,
+ # Boolean,
+ # engine,
+ # event,
+ exc,
+)
+
+from sqlalchemy.orm import mapper, relationship
+# from sqlalchemy.sql.sqltypes import Integer
+
+from o2ims.domain import ocloud as ocloudModel
+from o2ims.domain import subscription_obj as subModel
+from o2ims.domain import configuration_obj as confModel
+from o2ims.domain.resource_type import ResourceTypeEnum
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+metadata = MetaData()
+
+ocloud = Table(
+ "ocloud",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("oCloudId", String(255), primary_key=True),
+ Column("globalcloudId", String(255)),
+ Column("name", String(255)),
+ Column("description", String(255)),
+ Column("infrastructureManagementServiceEndpoint", String(255))
+ # Column("extensions", String(1024))
+)
+
+resourcetype = Table(
+ "resourcetype",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+
+ Column("resourceTypeId", String(255), primary_key=True),
+ Column("resourceTypeEnum", Enum(
+ ResourceTypeEnum, native_enum=False), nullable=False),
+ Column("oCloudId", ForeignKey("ocloud.oCloudId")),
+ Column("name", String(255)),
+ Column("vendor", String(255)),
+ Column("model", String(255)),
+ Column("version", String(255)),
+ Column("description", String(255)),
+ # Column("extensions", String(1024))
+)
+
+resourcepool = Table(
+ "resourcepool",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("resourcePoolId", String(255), primary_key=True),
+ Column("oCloudId", ForeignKey("ocloud.oCloudId")),
+ Column("globalLocationId", String(255)),
+ Column("name", String(255)),
+ Column("location", String(255)),
+ Column("description", String(255)),
+ # Column("resources", String(1024))
+ # Column("extensions", String(1024))
+)
+
+resource = Table(
+ "resource",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("resourceId", String(255), primary_key=True),
+ Column("resourceTypeId", ForeignKey("resourcetype.resourceTypeId")),
+ Column("resourcePoolId", ForeignKey("resourcepool.resourcePoolId")),
+ Column("name", String(255)),
+ # Column("globalAssetId", String(255)),
+ Column("parentId", String(255)),
+ Column("description", String(255)),
+ Column("elements", Text())
+ # Column("extensions", String(1024))
+)
+
+deploymentmanager = Table(
+ "deploymentmanager",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("deploymentManagerId", String(255), primary_key=True),
+ Column("oCloudId", ForeignKey("ocloud.oCloudId")),
+ Column("name", String(255)),
+ Column("description", String(255)),
+ Column("deploymentManagementServiceEndpoint", String(255)),
+ Column("supportedLocations", String(255)),
+ Column("capabilities", String(255)),
+ Column("capacity", String(255)),
+ # Column("extensions", String(1024))
+)
+
+subscription = Table(
+ "subscription",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+ Column("hash", String(255)),
+ Column("version_number", Integer),
+
+ Column("subscriptionId", String(255), primary_key=True),
+ Column("callback", String(255)),
+ Column("consumerSubscriptionId", String(255)),
+ Column("filter", String(255)),
+)
+
+configuration = Table(
+ "configuration",
+ metadata,
+ Column("updatetime", DateTime),
+ Column("createtime", DateTime),
+
+ Column("configurationId", String(255), primary_key=True),
+ Column("conftype", String(255)),
+ Column("callback", String(255)),
+ Column("status", String(255)),
+ Column("comments", String(255)),
+)
+
+
+@retry((exc.IntegrityError), tries=3, delay=2)
+def wait_for_metadata_ready(engine):
+ # wait for mapper ready
+ metadata.create_all(engine, checkfirst=True)
+ logger.info("metadata is ready")
+
+
+def start_o2ims_mappers(engine=None):
+ logger.info("Starting O2 IMS mappers")
+
+ dm_mapper = mapper(ocloudModel.DeploymentManager, deploymentmanager)
+ resourcepool_mapper = mapper(ocloudModel.ResourcePool, resourcepool)
+ resourcetype_mapper = mapper(ocloudModel.ResourceType, resourcetype)
+ mapper(
+ ocloudModel.Ocloud,
+ ocloud,
+ properties={
+ "deploymentManagers": relationship(dm_mapper),
+ "resourceTypes": relationship(resourcetype_mapper),
+ "resourcePools": relationship(resourcepool_mapper)
+ })
+ mapper(
+ ocloudModel.Resource,
+ resource,
+ properties={
+ "resourceTypes": relationship(resourcetype_mapper),
+ "resourcePools": relationship(resourcepool_mapper)
+ }
+ )
+ mapper(subModel.Subscription, subscription)
+ mapper(confModel.Configuration, configuration)
+
+ if engine is not None:
+ wait_for_metadata_ready(engine)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from __future__ import annotations\r
-import json\r
-\r
-from o2common.domain.base import AgRoot, Serializer\r
-# from dataclasses import dataclass\r
-# from datetime import date\r
-# from typing import Optional, List, Set\r
-from .resource_type import ResourceTypeEnum\r
-# from uuid import UUID\r
-\r
-\r
-class DeploymentManager(AgRoot, Serializer):\r
- def __init__(self, id: str, name: str, ocloudid: str,\r
- dmsendpoint: str, description: str = '',\r
- supportedLocations: str = '', capabilities: str = '',\r
- capacity: str = '') -> None:\r
- super().__init__()\r
- self.deploymentManagerId = id\r
- self.version_number = 0\r
- self.oCloudId = ocloudid\r
- self.name = name\r
- self.description = description\r
- self.deploymentManagementServiceEndpoint = dmsendpoint\r
- self.supportedLocations = supportedLocations\r
- self.capabilities = capabilities\r
- self.capacity = capacity\r
- self.extensions = []\r
-\r
-\r
-class ResourcePool(AgRoot, Serializer):\r
- def __init__(self, id: str, name: str, location: str,\r
- ocloudid: str, gLocationId: str = '',\r
- description: str = '') -> None:\r
- super().__init__()\r
- self.resourcePoolId = id\r
- self.version_number = 0\r
- self.oCloudId = ocloudid\r
- self.globalLocationId = gLocationId\r
- self.name = name\r
- self.location = location\r
- self.description = description\r
- self.extensions = []\r
-\r
-\r
-class ResourceType(AgRoot, Serializer):\r
- def __init__(self, typeid: str, name: str, typeEnum: ResourceTypeEnum,\r
- ocloudid: str, vender: str = '', model: str = '',\r
- version: str = '',\r
- description: str = '') -> None:\r
- super().__init__()\r
- self.resourceTypeId = typeid\r
- self.version_number = 0\r
- self.oCloudId = ocloudid\r
- self.resourceTypeEnum = typeEnum\r
- self.name = name\r
- self.vender = vender\r
- self.model = model\r
- self.version = version\r
- self.description = description\r
- self.extensions = []\r
-\r
-\r
-class Resource(AgRoot, Serializer):\r
- def __init__(self, resourceId: str, resourceTypeId: str,\r
- resourcePoolId: str, name: str, parentId: str = '',\r
- gAssetId: str = '', elements: str = '',\r
- description: str = '') -> None:\r
- super().__init__()\r
- self.resourceId = resourceId\r
- self.version_number = 0\r
- self.resourceTypeId = resourceTypeId\r
- self.resourcePoolId = resourcePoolId\r
- self.name = name\r
- self.globalAssetId = gAssetId\r
- self.parentId = parentId\r
- self.elements = elements\r
- self.description = description\r
- self.children = []\r
- self.extensions = []\r
-\r
- def set_children(self, children: list):\r
- self.children = children\r
-\r
- def set_resource_type_name(self, resource_type_name: str):\r
- self.resourceTypeName = resource_type_name\r
-\r
- def serialize(self):\r
- d = Serializer.serialize(self)\r
-\r
- if 'elements' in d and d['elements'] != '':\r
- d['elements'] = json.loads(d['elements'])\r
-\r
- if not hasattr(self, 'children') or len(self.children) == 0:\r
- return d\r
- else:\r
- d['children'] = []\r
-\r
- for child in self.children:\r
- d['children'].append(child.serialize())\r
- return d\r
-\r
-\r
-class Ocloud(AgRoot, Serializer):\r
- def __init__(self, ocloudid: str, name: str, imsendpoint: str,\r
- globalcloudId: str = '',\r
- description: str = '', version_number: int = 0) -> None:\r
- super().__init__()\r
- self.oCloudId = ocloudid\r
- self.globalcloudId = globalcloudId\r
- self.version_number = version_number\r
- self.name = name\r
- self.description = description\r
- self.infrastructureManagementServiceEndpoint = imsendpoint\r
- self.resourcePools = []\r
- self.deploymentManagers = []\r
- self.resourceTypes = []\r
- self.extensions = []\r
-\r
- # def addDeploymentManager(self,\r
- # deploymentManager: DeploymentManager):\r
-\r
- # deploymentManager.oCloudId = self.oCloudId\r
- # old = filter(\r
- # lambda x: x.deploymentManagerId ==\r
- # deploymentManager.deploymentManagerId,\r
- # self.deploymentManagers)\r
- # for o in old or []:\r
- # self.deploymentManagers.remove(o)\r
- # self.deploymentManagers.append(deploymentManager)\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 __future__ import annotations
+import json
+
+from o2common.domain.base import AgRoot, Serializer
+# from dataclasses import dataclass
+# from datetime import date
+# from typing import Optional, List, Set
+from .resource_type import ResourceTypeEnum
+# from uuid import UUID
+
+
+class DeploymentManager(AgRoot, Serializer):
+ def __init__(self, id: str, name: str, ocloudid: str,
+ dmsendpoint: str, description: str = '',
+ supportedLocations: str = '', capabilities: str = '',
+ capacity: str = '') -> None:
+ super().__init__()
+ self.deploymentManagerId = id
+ self.version_number = 0
+ self.oCloudId = ocloudid
+ self.name = name
+ self.description = description
+ self.deploymentManagementServiceEndpoint = dmsendpoint
+ self.supportedLocations = supportedLocations
+ self.capabilities = capabilities
+ self.capacity = capacity
+ self.extensions = []
+
+
+class ResourcePool(AgRoot, Serializer):
+ def __init__(self, id: str, name: str, location: str,
+ ocloudid: str, gLocationId: str = '',
+ description: str = '') -> None:
+ super().__init__()
+ self.resourcePoolId = id
+ self.version_number = 0
+ self.oCloudId = ocloudid
+ self.globalLocationId = gLocationId
+ self.name = name
+ self.location = location
+ self.description = description
+ self.extensions = []
+
+
+class ResourceType(AgRoot, Serializer):
+ def __init__(self, typeid: str, name: str, typeEnum: ResourceTypeEnum,
+ ocloudid: str, vender: str = '', model: str = '',
+ version: str = '',
+ description: str = '') -> None:
+ super().__init__()
+ self.resourceTypeId = typeid
+ self.version_number = 0
+ self.oCloudId = ocloudid
+ self.resourceTypeEnum = typeEnum
+ self.name = name
+ self.vender = vender
+ self.model = model
+ self.version = version
+ self.description = description
+ self.extensions = []
+
+
+class Resource(AgRoot, Serializer):
+ def __init__(self, resourceId: str, resourceTypeId: str,
+ resourcePoolId: str, name: str, parentId: str = '',
+ gAssetId: str = '', elements: str = '',
+ description: str = '') -> None:
+ super().__init__()
+ self.resourceId = resourceId
+ self.version_number = 0
+ self.resourceTypeId = resourceTypeId
+ self.resourcePoolId = resourcePoolId
+ self.name = name
+ self.globalAssetId = gAssetId
+ self.parentId = parentId
+ self.elements = elements
+ self.description = description
+ self.children = []
+ self.extensions = []
+
+ def set_children(self, children: list):
+ self.children = children
+
+ def set_resource_type_name(self, resource_type_name: str):
+ self.resourceTypeName = resource_type_name
+
+ def serialize(self):
+ d = Serializer.serialize(self)
+
+ if 'elements' in d and d['elements'] != '':
+ d['elements'] = json.loads(d['elements'])
+
+ if not hasattr(self, 'children') or len(self.children) == 0:
+ return d
+ else:
+ d['children'] = []
+
+ for child in self.children:
+ d['children'].append(child.serialize())
+ return d
+
+
+class Ocloud(AgRoot, Serializer):
+ def __init__(self, ocloudid: str, name: str, imsendpoint: str,
+ globalcloudId: str = '',
+ description: str = '', version_number: int = 0) -> None:
+ super().__init__()
+ self.oCloudId = ocloudid
+ self.globalcloudId = globalcloudId
+ self.version_number = version_number
+ self.name = name
+ self.description = description
+ self.infrastructureManagementServiceEndpoint = imsendpoint
+ self.resourcePools = []
+ self.deploymentManagers = []
+ self.resourceTypes = []
+ self.extensions = []
+
+ # def addDeploymentManager(self,
+ # deploymentManager: DeploymentManager):
+
+ # deploymentManager.oCloudId = self.oCloudId
+ # old = filter(
+ # lambda x: x.deploymentManagerId ==
+ # deploymentManager.deploymentManagerId,
+ # self.deploymentManagers)
+ # for o in old or []:
+ # self.deploymentManagers.remove(o)
+ # self.deploymentManagers.append(deploymentManager)
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import abc\r
-from typing import List, Set\r
-from o2ims.domain import ocloud\r
-\r
-\r
-class OcloudRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[ocloud.Ocloud]\r
-\r
- def add(self, ocloud: ocloud.Ocloud):\r
- self._add(ocloud)\r
- self.seen.add(ocloud)\r
-\r
- def get(self, ocloud_id) -> ocloud.Ocloud:\r
- ocloud = self._get(ocloud_id)\r
- if ocloud:\r
- self.seen.add(ocloud)\r
- return ocloud\r
-\r
- def list(self) -> List[ocloud.Ocloud]:\r
- return self._list()\r
-\r
- def update(self, ocloud: ocloud.Ocloud):\r
- self._update(ocloud)\r
- self.seen.add(ocloud)\r
-\r
- # def update_fields(self, ocloudid: str, updatefields: dict):\r
- # self._update(ocloudid, updatefields)\r
-\r
- @abc.abstractmethod\r
- def _add(self, ocloud: ocloud.Ocloud):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, ocloud_id) -> ocloud.Ocloud:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, ocloud: ocloud.Ocloud):\r
- raise NotImplementedError\r
-\r
-\r
-class ResourceTypeRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[ocloud.ResourceType]\r
-\r
- def add(self, resource_type: ocloud.ResourceType):\r
- self._add(resource_type)\r
- self.seen.add(resource_type)\r
-\r
- def get(self, resource_type_id) -> ocloud.ResourceType:\r
- resource_type = self._get(resource_type_id)\r
- if resource_type:\r
- self.seen.add(resource_type)\r
- return resource_type\r
-\r
- def get_by_name(self, resource_type_name) -> ocloud.ResourceType:\r
- resource_type = self._get_by_name(resource_type_name)\r
- if resource_type:\r
- self.seen.add(resource_type)\r
- return resource_type\r
-\r
- def list(self) -> List[ocloud.ResourceType]:\r
- return self._list()\r
-\r
- def update(self, resource_type: ocloud.ResourceType):\r
- self._update(resource_type)\r
- self.seen.add(resource_type)\r
-\r
- @abc.abstractmethod\r
- def _add(self, resource_type: ocloud.ResourceType):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, resource_type_id) -> ocloud.ResourceType:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get_by_name(self, resource_type_name) -> ocloud.ResourceType:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, resource_type: ocloud.ResourceType):\r
- raise NotImplementedError\r
-\r
-\r
-class ResourcePoolRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[ocloud.ResourcePool]\r
-\r
- def add(self, resource_pool: ocloud.ResourcePool):\r
- self._add(resource_pool)\r
- self.seen.add(resource_pool)\r
-\r
- def get(self, resource_pool_id) -> ocloud.ResourcePool:\r
- resource_pool = self._get(resource_pool_id)\r
- if resource_pool:\r
- self.seen.add(resource_pool)\r
- return resource_pool\r
-\r
- def list(self) -> List[ocloud.ResourcePool]:\r
- return self._list()\r
-\r
- def update(self, resource_pool: ocloud.ResourcePool):\r
- self._update(resource_pool)\r
- self.seen.add(resource_pool)\r
-\r
- @abc.abstractmethod\r
- def _add(self, resource_pool: ocloud.ResourcePool):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, resource_pool_id) -> ocloud.ResourcePool:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, resource_pool: ocloud.ResourcePool):\r
- raise NotImplementedError\r
-\r
-\r
-class ResourceRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[ocloud.Resource]\r
-\r
- def add(self, resource: ocloud.Resource):\r
- self._add(resource)\r
- self.seen.add(resource)\r
-\r
- def get(self, resource_id) -> ocloud.Resource:\r
- resource = self._get(resource_id)\r
- if resource:\r
- self.seen.add(resource)\r
- return resource\r
-\r
- def list(self, resourcepool_id, **kwargs) -> List[ocloud.Resource]:\r
- return self._list(resourcepool_id, **kwargs)\r
-\r
- def update(self, resource: ocloud.Resource):\r
- self._update(resource)\r
- self.seen.add(resource)\r
-\r
- @abc.abstractmethod\r
- def _add(self, resource: ocloud.Resource):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, resource_id) -> ocloud.Resource:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _list(self, resourcepool_id, **kwargs) -> ocloud.Resource:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, resource: ocloud.Resource):\r
- raise NotImplementedError\r
-\r
-\r
-class DeploymentManagerRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[ocloud.DeploymentManager]\r
-\r
- def add(self, deployment_manager: ocloud.DeploymentManager):\r
- self._add(deployment_manager)\r
- self.seen.add(deployment_manager)\r
-\r
- def get(self, deployment_manager_id) -> ocloud.DeploymentManager:\r
- deployment_manager = self._get(deployment_manager_id)\r
- if deployment_manager:\r
- self.seen.add(deployment_manager)\r
- return deployment_manager\r
-\r
- def list(self) -> List[ocloud.DeploymentManager]:\r
- return self._list()\r
-\r
- def update(self, deployment_manager: ocloud.DeploymentManager):\r
- self._update(deployment_manager)\r
-\r
- @abc.abstractmethod\r
- def _add(self, deployment_manager: ocloud.DeploymentManager):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, deployment_manager_id) -> ocloud.DeploymentManager:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, deployment_manager: ocloud.DeploymentManager):\r
- raise NotImplementedError\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 abc
+from typing import List, Set
+from o2ims.domain import ocloud
+
+
+class OcloudRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[ocloud.Ocloud]
+
+ def add(self, ocloud: ocloud.Ocloud):
+ self._add(ocloud)
+ self.seen.add(ocloud)
+
+ def get(self, ocloud_id) -> ocloud.Ocloud:
+ ocloud = self._get(ocloud_id)
+ if ocloud:
+ self.seen.add(ocloud)
+ return ocloud
+
+ def list(self) -> List[ocloud.Ocloud]:
+ return self._list()
+
+ def update(self, ocloud: ocloud.Ocloud):
+ self._update(ocloud)
+ self.seen.add(ocloud)
+
+ # def update_fields(self, ocloudid: str, updatefields: dict):
+ # self._update(ocloudid, updatefields)
+
+ @abc.abstractmethod
+ def _add(self, ocloud: ocloud.Ocloud):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, ocloud_id) -> ocloud.Ocloud:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, ocloud: ocloud.Ocloud):
+ raise NotImplementedError
+
+
+class ResourceTypeRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[ocloud.ResourceType]
+
+ def add(self, resource_type: ocloud.ResourceType):
+ self._add(resource_type)
+ self.seen.add(resource_type)
+
+ def get(self, resource_type_id) -> ocloud.ResourceType:
+ resource_type = self._get(resource_type_id)
+ if resource_type:
+ self.seen.add(resource_type)
+ return resource_type
+
+ def get_by_name(self, resource_type_name) -> ocloud.ResourceType:
+ resource_type = self._get_by_name(resource_type_name)
+ if resource_type:
+ self.seen.add(resource_type)
+ return resource_type
+
+ def list(self) -> List[ocloud.ResourceType]:
+ return self._list()
+
+ def update(self, resource_type: ocloud.ResourceType):
+ self._update(resource_type)
+ self.seen.add(resource_type)
+
+ @abc.abstractmethod
+ def _add(self, resource_type: ocloud.ResourceType):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, resource_type_id) -> ocloud.ResourceType:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get_by_name(self, resource_type_name) -> ocloud.ResourceType:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, resource_type: ocloud.ResourceType):
+ raise NotImplementedError
+
+
+class ResourcePoolRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[ocloud.ResourcePool]
+
+ def add(self, resource_pool: ocloud.ResourcePool):
+ self._add(resource_pool)
+ self.seen.add(resource_pool)
+
+ def get(self, resource_pool_id) -> ocloud.ResourcePool:
+ resource_pool = self._get(resource_pool_id)
+ if resource_pool:
+ self.seen.add(resource_pool)
+ return resource_pool
+
+ def list(self) -> List[ocloud.ResourcePool]:
+ return self._list()
+
+ def update(self, resource_pool: ocloud.ResourcePool):
+ self._update(resource_pool)
+ self.seen.add(resource_pool)
+
+ @abc.abstractmethod
+ def _add(self, resource_pool: ocloud.ResourcePool):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, resource_pool_id) -> ocloud.ResourcePool:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, resource_pool: ocloud.ResourcePool):
+ raise NotImplementedError
+
+
+class ResourceRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[ocloud.Resource]
+
+ def add(self, resource: ocloud.Resource):
+ self._add(resource)
+ self.seen.add(resource)
+
+ def get(self, resource_id) -> ocloud.Resource:
+ resource = self._get(resource_id)
+ if resource:
+ self.seen.add(resource)
+ return resource
+
+ def list(self, resourcepool_id, **kwargs) -> List[ocloud.Resource]:
+ return self._list(resourcepool_id, **kwargs)
+
+ def update(self, resource: ocloud.Resource):
+ self._update(resource)
+ self.seen.add(resource)
+
+ @abc.abstractmethod
+ def _add(self, resource: ocloud.Resource):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, resource_id) -> ocloud.Resource:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _list(self, resourcepool_id, **kwargs) -> ocloud.Resource:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, resource: ocloud.Resource):
+ raise NotImplementedError
+
+
+class DeploymentManagerRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[ocloud.DeploymentManager]
+
+ def add(self, deployment_manager: ocloud.DeploymentManager):
+ self._add(deployment_manager)
+ self.seen.add(deployment_manager)
+
+ def get(self, deployment_manager_id) -> ocloud.DeploymentManager:
+ deployment_manager = self._get(deployment_manager_id)
+ if deployment_manager:
+ self.seen.add(deployment_manager)
+ return deployment_manager
+
+ def list(self) -> List[ocloud.DeploymentManager]:
+ return self._list()
+
+ def update(self, deployment_manager: ocloud.DeploymentManager):
+ self._update(deployment_manager)
+
+ @abc.abstractmethod
+ def _add(self, deployment_manager: ocloud.DeploymentManager):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, deployment_manager_id) -> ocloud.DeploymentManager:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, deployment_manager: ocloud.DeploymentManager):
+ raise NotImplementedError
-from enum import Enum\r
-\r
-\r
-class ResourceTypeEnum(Enum):\r
- OCLOUD = 1\r
- RESOURCE_POOL = 2\r
- DMS = 3\r
- PSERVER = 11\r
- PSERVER_CPU = 12\r
- PSERVER_RAM = 13\r
- PSERVER_IF = 14\r
- PSERVER_IF_PORT = 15\r
- PSERVER_ETH = 16\r
-\r
-\r
-class InvalidOcloudState(Exception):\r
- pass\r
-\r
-\r
-class MismatchedModel(Exception):\r
- pass\r
+from enum import Enum
+
+
+class ResourceTypeEnum(Enum):
+ OCLOUD = 1
+ RESOURCE_POOL = 2
+ DMS = 3
+ PSERVER = 11
+ PSERVER_CPU = 12
+ PSERVER_RAM = 13
+ PSERVER_IF = 14
+ PSERVER_IF_PORT = 15
+ PSERVER_ETH = 16
+
+
+class InvalidOcloudState(Exception):
+ pass
+
+
+class MismatchedModel(Exception):
+ pass
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# from dataclasses import dataclass\r
-import datetime\r
-import json\r
-from o2common.domain.base import AgRoot\r
-\r
-from o2ims.domain.resource_type import ResourceTypeEnum, MismatchedModel\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class StxGenericModel(AgRoot):\r
- def __init__(self, type: ResourceTypeEnum,\r
- api_response: dict = None, content_hash=None) -> None:\r
- super().__init__()\r
- if api_response:\r
- self.id = str(api_response.uuid)\r
- self.type = type\r
- self.updatetime = datetime.datetime.strptime(\r
- api_response.updated_at.split('.')[0], "%Y-%m-%dT%H:%M:%S") \\r
- if api_response.updated_at else None\r
- self.createtime = datetime.datetime.strptime(\r
- api_response.created_at.split('.')[0], "%Y-%m-%dT%H:%M:%S") \\r
- if api_response.created_at else None\r
- self.name = api_response.name\r
- self.hash = content_hash if content_hash \\r
- else str(hash((self.id, self.updatetime)))\r
- self.content = json.dumps(api_response.to_dict())\r
-\r
- def is_outdated(self, newmodel) -> bool:\r
- # return self.updatetime < newmodel.updatetime\r
- # logger.warning("hash1: " + self.hash + " vs hash2: " + newmodel.hash)\r
- return self.hash != newmodel.hash\r
-\r
- def update_by(self, newmodel) -> None:\r
- if self.id != newmodel.id:\r
- raise MismatchedModel("Mismatched model")\r
- self.name = newmodel.name\r
- self.createtime = newmodel.createtime\r
- self.updatetime = newmodel.updatetime\r
- self.content = newmodel.content\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 dataclasses import dataclass
+import datetime
+import json
+from o2common.domain.base import AgRoot
+
+from o2ims.domain.resource_type import ResourceTypeEnum, MismatchedModel
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class StxGenericModel(AgRoot):
+ def __init__(self, type: ResourceTypeEnum,
+ api_response: dict = None, content_hash=None) -> None:
+ super().__init__()
+ if api_response:
+ self.id = str(api_response.uuid)
+ self.type = type
+ self.updatetime = datetime.datetime.strptime(
+ api_response.updated_at.split('.')[0], "%Y-%m-%dT%H:%M:%S") \
+ if api_response.updated_at else None
+ self.createtime = datetime.datetime.strptime(
+ api_response.created_at.split('.')[0], "%Y-%m-%dT%H:%M:%S") \
+ if api_response.created_at else None
+ self.name = api_response.name
+ self.hash = content_hash if content_hash \
+ else str(hash((self.id, self.updatetime)))
+ self.content = json.dumps(api_response.to_dict())
+
+ def is_outdated(self, newmodel) -> bool:
+ # return self.updatetime < newmodel.updatetime
+ # logger.warning("hash1: " + self.hash + " vs hash2: " + newmodel.hash)
+ return self.hash != newmodel.hash
+
+ def update_by(self, newmodel) -> None:
+ if self.id != newmodel.id:
+ raise MismatchedModel("Mismatched model")
+ self.name = newmodel.name
+ self.createtime = newmodel.createtime
+ self.updatetime = newmodel.updatetime
+ self.content = newmodel.content
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import abc\r
-from typing import List, Set\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2ims.domain.resource_type import ResourceTypeEnum\r
-\r
-\r
-class StxObjectRepository(abc.ABC):\r
- def __init__(self):\r
- self.seen = set() # type: Set[StxGenericModel]\r
-\r
- def add(self, stx_obj: StxGenericModel):\r
- self._add(stx_obj)\r
- self.seen.add(stx_obj)\r
-\r
- def get(self, stx_obj_id) -> StxGenericModel:\r
- stx_obj = self._get(stx_obj_id)\r
- if stx_obj:\r
- self.seen.add(stx_obj)\r
- return stx_obj\r
-\r
- def list(self, type: ResourceTypeEnum) -> List[StxGenericModel]:\r
- return self._list(type)\r
-\r
- def update(self, stx_obj: StxGenericModel):\r
- self._update(stx_obj)\r
- self.seen.add(stx_obj)\r
-\r
- # def update_fields(self, stx_obj_id: str, updatefields: dict):\r
- # self._update(stx_obj_id, updatefields)\r
-\r
- @abc.abstractmethod\r
- def _add(self, stx_obj: StxGenericModel):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _get(self, stx_obj_id) -> StxGenericModel:\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _update(self, stx_obj: StxGenericModel):\r
- raise NotImplementedError\r
-\r
- @abc.abstractmethod\r
- def _list(self, type: ResourceTypeEnum):\r
- raise NotImplementedError\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 abc
+from typing import List, Set
+from o2ims.domain.stx_object import StxGenericModel
+from o2ims.domain.resource_type import ResourceTypeEnum
+
+
+class StxObjectRepository(abc.ABC):
+ def __init__(self):
+ self.seen = set() # type: Set[StxGenericModel]
+
+ def add(self, stx_obj: StxGenericModel):
+ self._add(stx_obj)
+ self.seen.add(stx_obj)
+
+ def get(self, stx_obj_id) -> StxGenericModel:
+ stx_obj = self._get(stx_obj_id)
+ if stx_obj:
+ self.seen.add(stx_obj)
+ return stx_obj
+
+ def list(self, type: ResourceTypeEnum) -> List[StxGenericModel]:
+ return self._list(type)
+
+ def update(self, stx_obj: StxGenericModel):
+ self._update(stx_obj)
+ self.seen.add(stx_obj)
+
+ # def update_fields(self, stx_obj_id: str, updatefields: dict):
+ # self._update(stx_obj_id, updatefields)
+
+ @abc.abstractmethod
+ def _add(self, stx_obj: StxGenericModel):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _get(self, stx_obj_id) -> StxGenericModel:
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _update(self, stx_obj: StxGenericModel):
+ raise NotImplementedError
+
+ @abc.abstractmethod
+ def _list(self, type: ResourceTypeEnum):
+ raise NotImplementedError
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import json\r
-# import redis\r
-# import requests\r
-import http.client\r
-from urllib.parse import urlparse\r
-\r
-# from o2common.config import config\r
-from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2ims.domain import commands\r
-from o2ims.domain.subscription_obj import Subscription, Message2SMO\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-# # Maybe another MQ server\r
-# r = redis.Redis(**config.get_redis_host_and_port())\r
-\r
-\r
-def notify_change_to_smo(\r
- cmd: commands.PubMessage2SMO,\r
- uow: AbstractUnitOfWork,\r
-):\r
- logger.info('In notify_change_to_smo')\r
- data = cmd.data\r
- with uow:\r
- subs = uow.subscriptions.list()\r
- for sub in subs:\r
- sub_data = sub.serialize()\r
- logger.debug('Subscription: {}'.format(sub_data['subscriptionId']))\r
-\r
- try:\r
- resource_filter = json.loads(sub_data['filter'])\r
- if len(resource_filter) > 0:\r
- resource = uow.resources.get(data.id)\r
- logger.debug(type(resource))\r
- if resource: # TODO deal with resource is empty\r
- res_type_id = resource.serialize()['resourceTypeId']\r
- resourcetype = uow.resource_types.get(res_type_id)\r
- logger.debug(resourcetype.name)\r
- if resourcetype.name not in resource_filter:\r
- continue\r
- except json.decoder.JSONDecodeError as err:\r
- logger.warning(\r
- 'subscription filter decode json failed: {}'.format(err))\r
-\r
- callback_smo(sub, data)\r
-\r
-\r
-def callback_smo(sub: Subscription, msg: Message2SMO):\r
- sub_data = sub.serialize()\r
- callback_data = json.dumps({\r
- 'consumerSubscriptionId': sub_data['consumerSubscriptionId'],\r
- 'notificationEventType': msg.notificationEventType,\r
- 'objectRef': msg.objectRef,\r
- 'updateTime': msg.updatetime\r
- })\r
- logger.info('URL: {}, data: {}'.format(\r
- sub_data['callback'], callback_data))\r
- # r.publish(sub_data['subscriptionId'], json.dumps({\r
- # 'consumerSubscriptionId': sub_data['consumerSubscriptionId'],\r
- # 'notificationEventType': msg.notificationEventType,\r
- # 'objectRef': msg.objectRef\r
- # }))\r
- # try:\r
- # headers = {'User-Agent': 'Mozilla/5.0'}\r
- # resp = requests.post(sub_data['callback'], data=callback_data,\r
- # headers=headers)\r
- # if resp.status_code == 202 or resp.status_code == 200:\r
- # logger.info('Notify to SMO successed')\r
- # return\r
- # logger.error('Response code is: {}'.format(resp.status_code))\r
- # except requests.exceptions.HTTPError as err:\r
- # logger.error('request smo error: {}'.format(err))\r
- o = urlparse(sub_data['callback'])\r
- conn = http.client.HTTPConnection(o.netloc)\r
- headers = {'Content-type': 'application/json'}\r
- conn.request('POST', o.path, callback_data, headers)\r
- resp = conn.getresponse()\r
- data = resp.read().decode('utf-8')\r
- # json_data = json.loads(data)\r
- if resp.status == 202 or resp.status == 200:\r
- logger.info('Notify to SMO successed, response code {} {}, data {}'.\r
- format(resp.status, resp.reason, data))\r
- return\r
- logger.error('Response code is: {}'.format(resp.status))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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
+# import redis
+# import requests
+import http.client
+from urllib.parse import urlparse
+
+# from o2common.config import config
+from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2ims.domain import commands
+from o2ims.domain.subscription_obj import Subscription, Message2SMO
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+# # Maybe another MQ server
+# r = redis.Redis(**config.get_redis_host_and_port())
+
+
+def notify_change_to_smo(
+ cmd: commands.PubMessage2SMO,
+ uow: AbstractUnitOfWork,
+):
+ logger.info('In notify_change_to_smo')
+ data = cmd.data
+ with uow:
+ subs = uow.subscriptions.list()
+ for sub in subs:
+ sub_data = sub.serialize()
+ logger.debug('Subscription: {}'.format(sub_data['subscriptionId']))
+
+ try:
+ resource_filter = json.loads(sub_data['filter'])
+ if len(resource_filter) > 0:
+ resource = uow.resources.get(data.id)
+ logger.debug(type(resource))
+ if resource: # TODO deal with resource is empty
+ res_type_id = resource.serialize()['resourceTypeId']
+ resourcetype = uow.resource_types.get(res_type_id)
+ logger.debug(resourcetype.name)
+ if resourcetype.name not in resource_filter:
+ continue
+ except json.decoder.JSONDecodeError as err:
+ logger.warning(
+ 'subscription filter decode json failed: {}'.format(err))
+
+ callback_smo(sub, data)
+
+
+def callback_smo(sub: Subscription, msg: Message2SMO):
+ sub_data = sub.serialize()
+ callback_data = json.dumps({
+ 'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
+ 'notificationEventType': msg.notificationEventType,
+ 'objectRef': msg.objectRef,
+ 'updateTime': msg.updatetime
+ })
+ logger.info('URL: {}, data: {}'.format(
+ sub_data['callback'], callback_data))
+ # r.publish(sub_data['subscriptionId'], json.dumps({
+ # 'consumerSubscriptionId': sub_data['consumerSubscriptionId'],
+ # 'notificationEventType': msg.notificationEventType,
+ # 'objectRef': msg.objectRef
+ # }))
+ # try:
+ # headers = {'User-Agent': 'Mozilla/5.0'}
+ # resp = requests.post(sub_data['callback'], data=callback_data,
+ # headers=headers)
+ # if resp.status_code == 202 or resp.status_code == 200:
+ # logger.info('Notify to SMO successed')
+ # return
+ # logger.error('Response code is: {}'.format(resp.status_code))
+ # except requests.exceptions.HTTPError as err:
+ # logger.error('request smo error: {}'.format(err))
+ o = urlparse(sub_data['callback'])
+ conn = http.client.HTTPConnection(o.netloc)
+ headers = {'Content-type': 'application/json'}
+ conn.request('POST', o.path, callback_data, headers)
+ resp = conn.getresponse()
+ data = resp.read().decode('utf-8')
+ # json_data = json.loads(data)
+ if resp.status == 202 or resp.status == 200:
+ logger.info('Notify to SMO successed, response code {} {}, data {}'.
+ format(resp.status, resp.reason, data))
+ return
+ logger.error('Response code is: {}'.format(resp.status))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# import time\r
-import json\r
-# import asyncio\r
-# import requests\r
-import http.client\r
-from urllib.parse import urlparse\r
-from retry import retry\r
-\r
-from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2common.config import config\r
-from o2ims.domain import commands\r
-from o2ims.domain.configuration_obj import ConfigurationTypeEnum, \\r
- RegistrationStatusEnum\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def registry_to_smo(\r
- cmd: commands.Register2SMO,\r
- uow: AbstractUnitOfWork,\r
-):\r
- logger.info('In registry_to_smo')\r
- data = cmd.data\r
- logger.info('The Register2SMO all is {}'.format(data.all))\r
- if data.all:\r
- confs = uow.configrations.list()\r
- for conf in confs:\r
- if conf.conftype != ConfigurationTypeEnum.SMO:\r
- continue\r
- reg_data = conf.serialize()\r
- logger.debug('Configuration: {}'.format(\r
- reg_data['configurationId']))\r
-\r
- register_smo(uow, reg_data)\r
- else:\r
- with uow:\r
- conf = uow.configurations.get(data.id)\r
- if conf is None:\r
- return\r
- logger.debug('Configuration: {}'.format(conf.configurationId))\r
- conf_data = conf.serialize()\r
- register_smo(uow, conf_data)\r
-\r
-\r
-def register_smo(uow, reg_data):\r
- call_res = call_smo(reg_data)\r
- logger.debug('Call SMO response is {}'.format(call_res))\r
- if call_res:\r
- reg = uow.configurations.get(reg_data['configurationId'])\r
- if reg is None:\r
- return\r
- reg.status = RegistrationStatusEnum.NOTIFIED\r
- logger.debug('Updating Configurations: {}'.format(\r
- reg.configurationId))\r
- uow.configurations.update(reg)\r
- uow.commit()\r
-\r
-\r
-# def retry(fun, max_tries=2):\r
-# for i in range(max_tries):\r
-# try:\r
-# time.sleep(5*i)\r
-# # await asyncio.sleep(5*i)\r
-# res = fun()\r
-# logger.debug('retry function result: {}'.format(res))\r
-# return res\r
-# except Exception:\r
-# continue\r
-\r
-\r
-@retry((ConnectionRefusedError), tries=2, delay=2)\r
-def call_smo(reg_data: dict):\r
- callback_data = json.dumps({\r
- 'consumerSubscriptionId': reg_data['configurationId'],\r
- 'imsUrl': config.get_api_url()\r
- })\r
- logger.info('URL: {}, data: {}'.format(\r
- reg_data['callback'], callback_data))\r
-\r
- o = urlparse(reg_data['callback'])\r
- conn = http.client.HTTPConnection(o.netloc)\r
- headers = {'Content-type': 'application/json'}\r
- conn.request('POST', o.path, callback_data, headers)\r
- resp = conn.getresponse()\r
- data = resp.read().decode('utf-8')\r
- # json_data = json.loads(data)\r
- if resp.status == 202 or resp.status == 200:\r
- logger.info('Registrer to SMO successed, response code {} {}, data {}'.\r
- format(resp.status, resp.reason, data))\r
- return True\r
- logger.error('Response code is: {}'.format(resp.status))\r
- return False\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 time
+import json
+# import asyncio
+# import requests
+import http.client
+from urllib.parse import urlparse
+from retry import retry
+
+from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2common.config import config
+from o2ims.domain import commands
+from o2ims.domain.configuration_obj import ConfigurationTypeEnum, \
+ RegistrationStatusEnum
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def registry_to_smo(
+ cmd: commands.Register2SMO,
+ uow: AbstractUnitOfWork,
+):
+ logger.info('In registry_to_smo')
+ data = cmd.data
+ logger.info('The Register2SMO all is {}'.format(data.all))
+ if data.all:
+ confs = uow.configrations.list()
+ for conf in confs:
+ if conf.conftype != ConfigurationTypeEnum.SMO:
+ continue
+ reg_data = conf.serialize()
+ logger.debug('Configuration: {}'.format(
+ reg_data['configurationId']))
+
+ register_smo(uow, reg_data)
+ else:
+ with uow:
+ conf = uow.configurations.get(data.id)
+ if conf is None:
+ return
+ logger.debug('Configuration: {}'.format(conf.configurationId))
+ conf_data = conf.serialize()
+ register_smo(uow, conf_data)
+
+
+def register_smo(uow, reg_data):
+ call_res = call_smo(reg_data)
+ logger.debug('Call SMO response is {}'.format(call_res))
+ if call_res:
+ reg = uow.configurations.get(reg_data['configurationId'])
+ if reg is None:
+ return
+ reg.status = RegistrationStatusEnum.NOTIFIED
+ logger.debug('Updating Configurations: {}'.format(
+ reg.configurationId))
+ uow.configurations.update(reg)
+ uow.commit()
+
+
+# def retry(fun, max_tries=2):
+# for i in range(max_tries):
+# try:
+# time.sleep(5*i)
+# # await asyncio.sleep(5*i)
+# res = fun()
+# logger.debug('retry function result: {}'.format(res))
+# return res
+# except Exception:
+# continue
+
+
+@retry((ConnectionRefusedError), tries=2, delay=2)
+def call_smo(reg_data: dict):
+ callback_data = json.dumps({
+ 'consumerSubscriptionId': reg_data['configurationId'],
+ 'imsUrl': config.get_api_url()
+ })
+ logger.info('URL: {}, data: {}'.format(
+ reg_data['callback'], callback_data))
+
+ o = urlparse(reg_data['callback'])
+ conn = http.client.HTTPConnection(o.netloc)
+ headers = {'Content-type': 'application/json'}
+ conn.request('POST', o.path, callback_data, headers)
+ resp = conn.getresponse()
+ data = resp.read().decode('utf-8')
+ # json_data = json.loads(data)
+ if resp.status == 202 or resp.status == 200:
+ logger.info('Registrer to SMO successed, response code {} {}, data {}'.
+ format(resp.status, resp.reason, data))
+ return True
+ logger.error('Response code is: {}'.format(resp.status))
+ return False
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from typing import Callable\r
-\r
-from o2ims.domain import events\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def notify_configuration_change(\r
- event: events.ConfigurationChanged,\r
- publish: Callable,\r
-):\r
- logger.info('In notify_registration_change')\r
- publish("ConfigurationChanged", event)\r
- logger.debug("published Registration Changed: {}".format(\r
- event.id))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 typing import Callable
+
+from o2ims.domain import events
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def notify_configuration_change(
+ event: events.ConfigurationChanged,
+ publish: Callable,
+):
+ logger.info('In notify_registration_change')
+ publish("ConfigurationChanged", event)
+ logger.debug("published Registration Changed: {}".format(
+ event.id))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from typing import Callable\r
-\r
-from o2ims.domain import events\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def notify_ocloud_update(\r
- event: events.OcloudChanged,\r
- publish: Callable,\r
-):\r
- logger.info('In notify_ocloud_update')\r
- publish("OcloudChanged", event)\r
- logger.debug("published Ocloud Changed: {}".format(\r
- event.id))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 typing import Callable
+
+from o2ims.domain import events
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def notify_ocloud_update(
+ event: events.OcloudChanged,
+ publish: Callable,
+):
+ logger.info('In notify_ocloud_update')
+ publish("OcloudChanged", event)
+ logger.debug("published Ocloud Changed: {}".format(
+ event.id))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from typing import Callable\r
-\r
-from o2ims.domain import events\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def notify_resource_change(\r
- event: events.ResourceChanged,\r
- publish: Callable,\r
-):\r
- logger.info('In notify_resource_change')\r
- publish("ResourceChanged", event)\r
- logger.debug("published Resource Changed: {}".format(\r
- event.id))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 typing import Callable
+
+from o2ims.domain import events
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def notify_resource_change(
+ event: events.ResourceChanged,
+ publish: Callable,
+):
+ logger.info('In notify_resource_change')
+ publish("ResourceChanged", event)
+ logger.debug("published Resource Changed: {}".format(
+ event.id))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from typing import Callable\r
-\r
-from o2ims.domain import events\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def notify_resourcepool_change(\r
- event: events.ResourcePoolChanged,\r
- publish: Callable,\r
-):\r
- logger.info('In notify_resourcepool_change')\r
- publish("ResourcePoolChanged", event)\r
- logger.debug("published Resource Pool Changed: {}".format(\r
- event.id))\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 typing import Callable
+
+from o2ims.domain import events
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def notify_resourcepool_change(
+ event: events.ResourcePoolChanged,
+ publish: Callable,
+):
+ logger.info('In notify_resourcepool_change')
+ publish("ResourcePoolChanged", event)
+ logger.debug("published Resource Pool Changed: {}".format(
+ event.id))
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# from o2ims.domain.resource_type import ResourceTypeEnum\r
-from o2common.service.client.base_client import BaseClient\r
-from o2ims.domain.stx_object import StxGenericModel\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2common.service.watcher.base import BaseWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class OcloudWatcher(BaseWatcher):\r
- def __init__(self, ocloud_client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(ocloud_client, bus)\r
-\r
- def _targetname(self):\r
- return "ocloud"\r
-\r
- def _probe(self, parent: object = None):\r
- newmodel = self._client.get(None)\r
- if newmodel:\r
- logger.debug("found ocloud: " + newmodel.name)\r
- else:\r
- logger.warning("Failed to find out any ocloud")\r
- # self._compare_and_update(ocloudmodel)\r
- return [commands.UpdateOCloud(newmodel)] if newmodel else []\r
-\r
-# def _compare_and_update(self, ocloudmodel: StxGenericModel) -> bool:\r
-# with self._uow:\r
-# # localmodel = self._uow.stxobjects.get(str(ocloudmodel.id))\r
-# oclouds = self._uow.stxobjects.list(ResourceTypeEnum.OCLOUD)\r
-# if len(oclouds) > 1:\r
-# raise InvalidOcloudState("More than 1 ocloud is found")\r
-# if len(oclouds) == 0:\r
-# logger.info("add ocloud:" + ocloudmodel.name\r
-# + " update_at: " + str(ocloudmodel.updatetime)\r
-# + " id: " + str(ocloudmodel.id)\r
-# + " hash: " + str(ocloudmodel.hash))\r
-# self._uow.stxobjects.add(ocloudmodel)\r
-# else:\r
-# localmodel = oclouds.pop()\r
-# if localmodel.is_outdated(ocloudmodel):\r
-# logger.info("update ocloud:" + ocloudmodel.name\r
-# + " update_at: " + str(ocloudmodel.updatetime)\r
-# + " id: " + str(ocloudmodel.id)\r
-# + " hash: " + str(ocloudmodel.hash))\r
-# localmodel.update_by(ocloudmodel)\r
-# self._uow.stxobjects.update(localmodel)\r
-# self._uow.commit()\r
-\r
-\r
-class DmsWatcher(BaseWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "dms"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- ocloudid = parent.id\r
- newmodels = self._client.list(ocloudid=ocloudid)\r
- # for newmodel in newmodels:\r
- # super()._compare_and_update(newmodel)\r
- # return newmodels\r
- return [commands.UpdateDms(data=m, parentid=ocloudid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.resource_type import ResourceTypeEnum
+from o2common.service.client.base_client import BaseClient
+from o2ims.domain.stx_object import StxGenericModel
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2common.service.watcher.base import BaseWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class OcloudWatcher(BaseWatcher):
+ def __init__(self, ocloud_client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(ocloud_client, bus)
+
+ def _targetname(self):
+ return "ocloud"
+
+ def _probe(self, parent: object = None):
+ newmodel = self._client.get(None)
+ if newmodel:
+ logger.debug("found ocloud: " + newmodel.name)
+ else:
+ logger.warning("Failed to find out any ocloud")
+ # self._compare_and_update(ocloudmodel)
+ return [commands.UpdateOCloud(newmodel)] if newmodel else []
+
+# def _compare_and_update(self, ocloudmodel: StxGenericModel) -> bool:
+# with self._uow:
+# # localmodel = self._uow.stxobjects.get(str(ocloudmodel.id))
+# oclouds = self._uow.stxobjects.list(ResourceTypeEnum.OCLOUD)
+# if len(oclouds) > 1:
+# raise InvalidOcloudState("More than 1 ocloud is found")
+# if len(oclouds) == 0:
+# logger.info("add ocloud:" + ocloudmodel.name
+# + " update_at: " + str(ocloudmodel.updatetime)
+# + " id: " + str(ocloudmodel.id)
+# + " hash: " + str(ocloudmodel.hash))
+# self._uow.stxobjects.add(ocloudmodel)
+# else:
+# localmodel = oclouds.pop()
+# if localmodel.is_outdated(ocloudmodel):
+# logger.info("update ocloud:" + ocloudmodel.name
+# + " update_at: " + str(ocloudmodel.updatetime)
+# + " id: " + str(ocloudmodel.id)
+# + " hash: " + str(ocloudmodel.hash))
+# localmodel.update_by(ocloudmodel)
+# self._uow.stxobjects.update(localmodel)
+# self._uow.commit()
+
+
+class DmsWatcher(BaseWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "dms"
+
+ def _probe(self, parent: StxGenericModel):
+ ocloudid = parent.id
+ newmodels = self._client.list(ocloudid=ocloudid)
+ # for newmodel in newmodels:
+ # super()._compare_and_update(newmodel)
+ # return newmodels
+ return [commands.UpdateDms(data=m, parentid=ocloudid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2ims.service.watcher.resource_watcher import ResourceWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class PServerCpuWatcher(ResourceWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "pserver_cpu"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- hostid = parent.id\r
- newmodels = self._client.list(hostid=hostid)\r
- return [commands.UpdatePserverCpu(data=m, parentid=hostid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2ims.service.watcher.resource_watcher import ResourceWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class PServerCpuWatcher(ResourceWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "pserver_cpu"
+
+ def _probe(self, parent: StxGenericModel):
+ hostid = parent.id
+ newmodels = self._client.list(hostid=hostid)
+ return [commands.UpdatePserverCpu(data=m, parentid=hostid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2ims.service.watcher.resource_watcher import ResourceWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class PServerEthWatcher(ResourceWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "pserver_ethernet"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- hostid = parent.id\r
- newmodels = self._client.list(hostid=hostid)\r
- return [commands.UpdatePserverEth(data=m, parentid=hostid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2ims.service.watcher.resource_watcher import ResourceWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class PServerEthWatcher(ResourceWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "pserver_ethernet"
+
+ def _probe(self, parent: StxGenericModel):
+ hostid = parent.id
+ newmodels = self._client.list(hostid=hostid)
+ return [commands.UpdatePserverEth(data=m, parentid=hostid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2ims.service.watcher.resource_watcher import ResourceWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class PServerIfWatcher(ResourceWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "pserver_if"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- hostid = parent.id\r
- newmodels = self._client.list(hostid=hostid)\r
- return [commands.UpdatePserverIf(data=m, parentid=hostid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2ims.service.watcher.resource_watcher import ResourceWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class PServerIfWatcher(ResourceWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "pserver_if"
+
+ def _probe(self, parent: StxGenericModel):
+ hostid = parent.id
+ newmodels = self._client.list(hostid=hostid)
+ return [commands.UpdatePserverIf(data=m, parentid=hostid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2ims.service.watcher.resource_watcher import ResourceWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class PServerMemWatcher(ResourceWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "pserver_mem"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- hostid = parent.id\r
- newmodels = self._client.list(hostid=hostid)\r
- return [commands.UpdatePserverMem(data=m, parentid=hostid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2ims.service.watcher.resource_watcher import ResourceWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class PServerMemWatcher(ResourceWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "pserver_mem"
+
+ def _probe(self, parent: StxGenericModel):
+ hostid = parent.id
+ newmodels = self._client.list(hostid=hostid)
+ return [commands.UpdatePserverMem(data=m, parentid=hostid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2ims.service.watcher.resource_watcher import ResourceWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class PServerIfPortWatcher(ResourceWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "pserver_if_port"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- interfaceid = parent.id\r
- newmodels = self._client.list(interfaceid=interfaceid)\r
- return [commands.UpdatePserverIfPort(data=m, parentid=interfaceid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2ims.service.watcher.resource_watcher import ResourceWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class PServerIfPortWatcher(ResourceWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "pserver_if_port"
+
+ def _probe(self, parent: StxGenericModel):
+ interfaceid = parent.id
+ newmodels = self._client.list(interfaceid=interfaceid)
+ return [commands.UpdatePserverIfPort(data=m, parentid=interfaceid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2ims.service.watcher.resource_watcher import ResourceWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class PServerWatcher(ResourceWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "pserver"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- resourcepoolid = parent.id\r
- newmodels = self._client.list(resourcepoolid=resourcepoolid)\r
- return [commands.UpdatePserver(data=m, parentid=resourcepoolid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2ims.service.watcher.resource_watcher import ResourceWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class PServerWatcher(ResourceWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "pserver"
+
+ def _probe(self, parent: StxGenericModel):
+ resourcepoolid = parent.id
+ newmodels = self._client.list(resourcepoolid=resourcepoolid)
+ return [commands.UpdatePserver(data=m, parentid=resourcepoolid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2common.service.watcher.base import BaseWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class ResourceWatcher(BaseWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "resource"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- parentid = parent.id\r
- newmodels = self._client.get(parentid=parentid)\r
- return [commands.UpdateResource(data=m, parentid=parentid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2common.service.watcher.base import BaseWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class ResourceWatcher(BaseWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "resource"
+
+ def _probe(self, parent: StxGenericModel):
+ parentid = parent.id
+ newmodels = self._client.get(parentid=parentid)
+ return [commands.UpdateResource(data=m, parentid=parentid)
+ for m in newmodels]
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from o2ims.domain.stx_object import StxGenericModel\r
-from o2common.service.client.base_client import BaseClient\r
-# from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2common.service.watcher.base import BaseWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.messagebus import MessageBus\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-class ResourcePoolWatcher(BaseWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: MessageBus) -> None:\r
- super().__init__(client, bus)\r
-\r
- def _targetname(self):\r
- return "resourcepool"\r
-\r
- def _probe(self, parent: StxGenericModel):\r
- ocloudid = parent.id\r
- newmodels = self._client.list(ocloudid=ocloudid)\r
- # for newmodel in newmodels:\r
- # logger.info("detect ocloudmodel:" + newmodel.name)\r
- # super()._compare_and_update(newmodel)\r
- # return newmodels\r
- return [commands.UpdateResourcePool(data=m, parentid=ocloudid)\r
- for m in newmodels]\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 o2ims.domain.stx_object import StxGenericModel
+from o2common.service.client.base_client import BaseClient
+# from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2common.service.watcher.base import BaseWatcher
+from o2ims.domain import commands
+from o2common.service.messagebus import MessageBus
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+class ResourcePoolWatcher(BaseWatcher):
+ def __init__(self, client: BaseClient,
+ bus: MessageBus) -> None:
+ super().__init__(client, bus)
+
+ def _targetname(self):
+ return "resourcepool"
+
+ def _probe(self, parent: StxGenericModel):
+ ocloudid = parent.id
+ newmodels = self._client.list(ocloudid=ocloudid)
+ # for newmodel in newmodels:
+ # logger.info("detect ocloudmodel:" + newmodel.name)
+ # super()._compare_and_update(newmodel)
+ # return newmodels
+ return [commands.UpdateResourcePool(data=m, parentid=ocloudid)
+ for m in newmodels]
-from flask_restx import Namespace\r
-\r
-\r
-api_ims_inventory_v1 = Namespace(\r
- "O2IMS_Inventory",\r
- description='IMS Inventory related operations.')\r
-\r
-api_provision_v1 = Namespace(\r
- "PROVISION",\r
- description='Provision related operations.')\r
+from flask_restx import Namespace
+
+
+api_ims_inventory_v1 = Namespace(
+ "O2IMS_Inventory",
+ description='IMS Inventory related operations.')
+
+api_provision_v1 = Namespace(
+ "PROVISION",
+ description='Provision related operations.')
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import uuid\r
-\r
-from o2common.service import unit_of_work\r
-from o2ims.views.ocloud_dto import SubscriptionDTO\r
-from o2ims.domain.subscription_obj import Subscription\r
-\r
-from o2common.helper import o2logging\r
-logger = o2logging.get_logger(__name__)\r
-\r
-\r
-def oclouds(uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- li = uow.oclouds.list()\r
- return [r.serialize() for r in li]\r
-\r
-\r
-def ocloud_one(ocloudid: str, uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- first = uow.oclouds.get(ocloudid)\r
- return first.serialize() if first is not None else None\r
-\r
-\r
-def resource_types(uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- li = uow.resource_types.list()\r
- return [r.serialize() for r in li]\r
-\r
-\r
-def resource_type_one(resourceTypeId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- first = uow.resource_types.get(resourceTypeId)\r
- return first.serialize() if first is not None else None\r
-\r
-\r
-def resource_pools(uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- li = uow.resource_pools.list()\r
- return [r.serialize() for r in li]\r
-\r
-\r
-def resource_pool_one(resourcePoolId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- first = uow.resource_pools.get(resourcePoolId)\r
- return first.serialize() if first is not None else None\r
-\r
-\r
-def resources(resourcePoolId: str, uow: unit_of_work.AbstractUnitOfWork,\r
- **kwargs):\r
-\r
- filter_kwargs = {} # filter key should be the same with database name\r
- if 'resourceTypeName' in kwargs:\r
- resource_type_name = kwargs['resourceTypeName']\r
- with uow:\r
- # res_types = uow.resource_types.list()\r
- # restype_ids = [\r
- # restype.resourceTypeId for restype in res_types\r
- # if resourceTypeName == restype.name]\r
- # restype_id = '' if len(restype_ids) == 0 else restype_ids[0]\r
- res_type = uow.resource_types.get_by_name(resource_type_name)\r
- restype_id = '' if res_type is None else res_type.resourceTypeId\r
- filter_kwargs['resourceTypeId'] = restype_id\r
-\r
- # li = uow.resources.list(resourcePoolId)\r
- # return [r.serialize() for r in li if r.resourceTypeId == restype_id]\r
- if 'parentId' in kwargs:\r
- filter_kwargs['parentId'] = kwargs['parentId']\r
-\r
- with uow:\r
- li = uow.resources.list(resourcePoolId, **filter_kwargs)\r
- return [r.serialize() for r in li]\r
-\r
-\r
-def resource_one(resourceId: str, uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- first = uow.resources.get(resourceId)\r
- return first.serialize() if first is not None else None\r
-\r
-\r
-def deployment_managers(uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- li = uow.deployment_managers.list()\r
- return [r.serialize() for r in li]\r
-\r
-\r
-def deployment_manager_one(deploymentManagerId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- first = uow.deployment_managers.get(deploymentManagerId)\r
- return first.serialize() if first is not None else None\r
-\r
-\r
-def subscriptions(uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- li = uow.subscriptions.list()\r
- return [r.serialize() for r in li]\r
-\r
-\r
-def subscription_one(subscriptionId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- first = uow.subscriptions.get(subscriptionId)\r
- return first.serialize() if first is not None else None\r
-\r
-\r
-def subscription_create(subscriptionDto: SubscriptionDTO.subscription,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
-\r
- sub_uuid = str(uuid.uuid4())\r
- subscription = Subscription(\r
- sub_uuid, subscriptionDto['callback'],\r
- subscriptionDto['consumerSubscriptionId'],\r
- subscriptionDto['filter'])\r
- with uow:\r
- uow.subscriptions.add(subscription)\r
- uow.commit()\r
- return {"subscriptionId": sub_uuid}\r
-\r
-\r
-def subscription_delete(subscriptionId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- uow.subscriptions.delete(subscriptionId)\r
- uow.commit()\r
- return True\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 uuid
+
+from o2common.service import unit_of_work
+from o2ims.views.ocloud_dto import SubscriptionDTO
+from o2ims.domain.subscription_obj import Subscription
+
+from o2common.helper import o2logging
+logger = o2logging.get_logger(__name__)
+
+
+def oclouds(uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ li = uow.oclouds.list()
+ return [r.serialize() for r in li]
+
+
+def ocloud_one(ocloudid: str, uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ first = uow.oclouds.get(ocloudid)
+ return first.serialize() if first is not None else None
+
+
+def resource_types(uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ li = uow.resource_types.list()
+ return [r.serialize() for r in li]
+
+
+def resource_type_one(resourceTypeId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ first = uow.resource_types.get(resourceTypeId)
+ return first.serialize() if first is not None else None
+
+
+def resource_pools(uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ li = uow.resource_pools.list()
+ return [r.serialize() for r in li]
+
+
+def resource_pool_one(resourcePoolId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ first = uow.resource_pools.get(resourcePoolId)
+ return first.serialize() if first is not None else None
+
+
+def resources(resourcePoolId: str, uow: unit_of_work.AbstractUnitOfWork,
+ **kwargs):
+
+ filter_kwargs = {} # filter key should be the same with database name
+ if 'resourceTypeName' in kwargs:
+ resource_type_name = kwargs['resourceTypeName']
+ with uow:
+ # res_types = uow.resource_types.list()
+ # restype_ids = [
+ # restype.resourceTypeId for restype in res_types
+ # if resourceTypeName == restype.name]
+ # restype_id = '' if len(restype_ids) == 0 else restype_ids[0]
+ res_type = uow.resource_types.get_by_name(resource_type_name)
+ restype_id = '' if res_type is None else res_type.resourceTypeId
+ filter_kwargs['resourceTypeId'] = restype_id
+
+ # li = uow.resources.list(resourcePoolId)
+ # return [r.serialize() for r in li if r.resourceTypeId == restype_id]
+ if 'parentId' in kwargs:
+ filter_kwargs['parentId'] = kwargs['parentId']
+
+ with uow:
+ li = uow.resources.list(resourcePoolId, **filter_kwargs)
+ return [r.serialize() for r in li]
+
+
+def resource_one(resourceId: str, uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ first = uow.resources.get(resourceId)
+ return first.serialize() if first is not None else None
+
+
+def deployment_managers(uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ li = uow.deployment_managers.list()
+ return [r.serialize() for r in li]
+
+
+def deployment_manager_one(deploymentManagerId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ first = uow.deployment_managers.get(deploymentManagerId)
+ return first.serialize() if first is not None else None
+
+
+def subscriptions(uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ li = uow.subscriptions.list()
+ return [r.serialize() for r in li]
+
+
+def subscription_one(subscriptionId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ first = uow.subscriptions.get(subscriptionId)
+ return first.serialize() if first is not None else None
+
+
+def subscription_create(subscriptionDto: SubscriptionDTO.subscription,
+ uow: unit_of_work.AbstractUnitOfWork):
+
+ sub_uuid = str(uuid.uuid4())
+ subscription = Subscription(
+ sub_uuid, subscriptionDto['callback'],
+ subscriptionDto['consumerSubscriptionId'],
+ subscriptionDto['filter'])
+ with uow:
+ uow.subscriptions.add(subscription)
+ uow.commit()
+ return {"subscriptionId": sub_uuid}
+
+
+def subscription_delete(subscriptionId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ uow.subscriptions.delete(subscriptionId)
+ uow.commit()
+ return True
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import logging\r
-import uuid\r
-from datetime import datetime\r
-\r
-from o2common.service import unit_of_work, messagebus\r
-from o2ims.domain import events\r
-from o2ims.views.provision_dto import SmoEndpointDTO\r
-from o2ims.domain.configuration_obj import Configuration, ConfigurationTypeEnum\r
-\r
-\r
-def configurations(uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- li = uow.configurations.list()\r
- return [r.serialize_smo() for r in li]\r
-\r
-\r
-def configuration_one(configurationId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- first = uow.configurations.get(configurationId)\r
- return first.serialize_smo() if first is not None else None\r
-\r
-\r
-def configuration_create(configurationDto: SmoEndpointDTO.endpoint,\r
- bus: messagebus.MessageBus):\r
-\r
- conf_uuid = str(uuid.uuid4())\r
- configuration = Configuration(\r
- conf_uuid, configurationDto['endpoint'], ConfigurationTypeEnum.SMO)\r
- with bus.uow as uow:\r
- uow.configurations.add(configuration)\r
- logging.debug('before event length {}'.format(\r
- len(configuration.events)))\r
- configuration.events.append(events.ConfigurationChanged(\r
- conf_uuid,\r
- datetime.now()))\r
- logging.debug('after event length {}'.format(\r
- len(configuration.events)))\r
- uow.commit()\r
- _handle_events(bus)\r
- return {"id": conf_uuid}\r
-\r
-\r
-def configuration_delete(configurationId: str,\r
- uow: unit_of_work.AbstractUnitOfWork):\r
- with uow:\r
- uow.configurations.delete(configurationId)\r
- uow.commit()\r
- return True\r
-\r
-\r
-def _handle_events(bus: messagebus.MessageBus):\r
- # handle events\r
- events = bus.uow.collect_new_events()\r
- for event in events:\r
- bus.handle(event)\r
- return True\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 logging
+import uuid
+from datetime import datetime
+
+from o2common.service import unit_of_work, messagebus
+from o2ims.domain import events
+from o2ims.views.provision_dto import SmoEndpointDTO
+from o2ims.domain.configuration_obj import Configuration, ConfigurationTypeEnum
+
+
+def configurations(uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ li = uow.configurations.list()
+ return [r.serialize_smo() for r in li]
+
+
+def configuration_one(configurationId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ first = uow.configurations.get(configurationId)
+ return first.serialize_smo() if first is not None else None
+
+
+def configuration_create(configurationDto: SmoEndpointDTO.endpoint,
+ bus: messagebus.MessageBus):
+
+ conf_uuid = str(uuid.uuid4())
+ configuration = Configuration(
+ conf_uuid, configurationDto['endpoint'], ConfigurationTypeEnum.SMO)
+ with bus.uow as uow:
+ uow.configurations.add(configuration)
+ logging.debug('before event length {}'.format(
+ len(configuration.events)))
+ configuration.events.append(events.ConfigurationChanged(
+ conf_uuid,
+ datetime.now()))
+ logging.debug('after event length {}'.format(
+ len(configuration.events)))
+ uow.commit()
+ _handle_events(bus)
+ return {"id": conf_uuid}
+
+
+def configuration_delete(configurationId: str,
+ uow: unit_of_work.AbstractUnitOfWork):
+ with uow:
+ uow.configurations.delete(configurationId)
+ uow.commit()
+ return True
+
+
+def _handle_events(bus: messagebus.MessageBus):
+ # handle events
+ events = bus.uow.collect_new_events()
+ for event in events:
+ bus.handle(event)
+ return True
----\r
-\r
-distribution_type: container\r
-container_release_tag: 1.0.0\r
-container_pull_registry: nexus3.o-ran-sc.org:10004\r
-container_push_registry: nexus3.o-ran-sc.org:10002\r
-project: pti-o2\r
-ref: f3ce354b2e6c538b50ed990ba359d3af2283c901\r
-containers:\r
- - name: pti-o2imsdms\r
- version: 1.0.0\r
+---
+
+distribution_type: container
+container_release_tag: 1.0.0
+container_pull_registry: nexus3.o-ran-sc.org:10004
+container_push_registry: nexus3.o-ran-sc.org:10002
+project: pti-o2
+ref: f3ce354b2e6c538b50ed990ba359d3af2283c901
+containers:
+ - name: pti-o2imsdms
+ version: 1.0.0
--e git+https://opendev.org/starlingx/distcloud-client.git@master#egg=distributedcloud-client&subdirectory=distributedcloud-client\r
--e git+https://opendev.org/starlingx/config.git@master#egg=cgtsclient&subdirectory=sysinv/cgts-client/cgts-client#\r
-# -e git+https://github.com/cloudify-incubator/cloudify-helm-plugin.git@master#egg=helmsdk&subdirectory=helm_sdk\r
+-e git+https://opendev.org/starlingx/distcloud-client.git@master#egg=distributedcloud-client&subdirectory=distributedcloud-client
+-e git+https://opendev.org/starlingx/config.git@master#egg=cgtsclient&subdirectory=sysinv/cgts-client/cgts-client#
+# -e git+https://github.com/cloudify-incubator/cloudify-helm-plugin.git@master#egg=helmsdk&subdirectory=helm_sdk
-flake8\r
-pylint\r
-mypy\r
-requests\r
-tox\r
-\r
-pytest\r
-pytest-cov\r
-pytest-icdiff\r
-mock\r
-\r
-tenacity\r
-\r
-# -e git+https://opendev.org/starlingx/distcloud-client.git@master#egg=distributedcloud-client&subdirectory=distributedcloud-client\r
-# -e git+https://opendev.org/starlingx/config.git@master#egg=cgtsclient&subdirectory=sysinv/cgts-client/cgts-client\r
+flake8
+pylint
+mypy
+requests
+tox
+
+pytest
+pytest-cov
+pytest-icdiff
+mock
+
+tenacity
+
+# -e git+https://opendev.org/starlingx/distcloud-client.git@master#egg=distributedcloud-client&subdirectory=distributedcloud-client
+# -e git+https://opendev.org/starlingx/config.git@master#egg=cgtsclient&subdirectory=sysinv/cgts-client/cgts-client
-flask\r
-flask-restx\r
-sqlalchemy\r
-redis\r
-psycopg2-binary\r
-cotyledon\r
-PyYAML>=5.4.1\r
-\r
-Cython>=3.0a1\r
-\r
-\r
-httplib2\r
-babel\r
-PrettyTable<0.8,>=0.7.2\r
-\r
-retry\r
+flask
+flask-restx
+sqlalchemy
+redis
+psycopg2-binary
+cotyledon
+PyYAML>=5.4.1
+
+Cython>=3.0a1
+
+
+httplib2
+babel
+PrettyTable<0.8,>=0.7.2
+
+retry
ruamel.yaml==0.17.17
\ No newline at end of file
-from setuptools import setup\r
-from setuptools import find_packages\r
-\r
-setup(\r
- name="o2imsdms",\r
- version="1.0",\r
- packages=find_packages(),\r
- license="LICENSE",\r
- description="Represent O2 IMS and O2 DMS",\r
- install_requires=[\r
- 'httplib2',\r
- # 'distributedcloud-client',\r
- # 'cgtsclient',\r
- 'babel', # Required by distributedcloud-client\r
- 'PrettyTable<0.8,>=0.7.2', # Required by distributedcloud-client\r
- ]\r
-)\r
+from setuptools import setup
+from setuptools import find_packages
+
+setup(
+ name="o2imsdms",
+ version="1.0",
+ packages=find_packages(),
+ license="LICENSE",
+ description="Represent O2 IMS and O2 DMS",
+ install_requires=[
+ 'httplib2',
+ # 'distributedcloud-client',
+ # 'cgtsclient',
+ 'babel', # Required by distributedcloud-client
+ 'PrettyTable<0.8,>=0.7.2', # Required by distributedcloud-client
+ ]
+)
-# The Jenkins job requires a tag to build the Docker image.\r
-# By default this file is in the docker build directory,\r
-# but the location can configured in the JJB template.\r
----\r
-tag: "1.0.0"\r
+# The Jenkins job requires a tag to build the Docker image.
+# By default this file is in the docker build directory,
+# but the location can configured in the JJB template.
+---
+tag: "1.0.0"
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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.
-# pylint: disable=redefined-outer-name\r
-import shutil\r
-import subprocess\r
-import time\r
-from pathlib import Path\r
-\r
-import pytest\r
-import redis\r
-import requests\r
-from flask import Flask\r
-from flask_restx import Api\r
-from sqlalchemy import create_engine\r
-from sqlalchemy.orm import sessionmaker, clear_mappers\r
-from tenacity import retry, stop_after_delay\r
-from unittest.mock import MagicMock\r
-\r
-from o2common.config import config\r
-\r
-from o2ims.adapter.orm import metadata, start_o2ims_mappers\r
-# from o2ims.adapter.clients.orm_stx import start_o2ims_stx_mappers\r
-\r
-from o2app.adapter import unit_of_work\r
-from o2ims.views import configure_namespace\r
-\r
-from o2app.bootstrap import bootstrap\r
-\r
-\r
-@pytest.fixture\r
-def mock_uow():\r
- session = MagicMock()\r
- uow = unit_of_work.SqlAlchemyUnitOfWork(session_factory=session)\r
- return session, uow\r
-\r
-\r
-@pytest.fixture\r
-def mock_flask_uow(mock_uow):\r
- session, uow = mock_uow\r
- app = Flask(__name__)\r
- app.config["TESTING"] = True\r
- api = Api(app)\r
- bootstrap(False, uow)\r
- configure_namespace(api)\r
- return session, app\r
-\r
-\r
-@pytest.fixture\r
-def in_memory_sqlite_db():\r
- engine = create_engine("sqlite:///:memory:")\r
- # engine = create_engine("sqlite:///:memory:", echo=True)\r
- metadata.create_all(engine)\r
- return engine\r
-\r
-\r
-@pytest.fixture\r
-def sqlite_session_factory(in_memory_sqlite_db):\r
- yield sessionmaker(bind=in_memory_sqlite_db)\r
-\r
-\r
-@pytest.fixture\r
-def sqlite_uow(sqlite_session_factory):\r
- uow = unit_of_work.SqlAlchemyUnitOfWork(\r
- session_factory=sqlite_session_factory)\r
- # with uow:\r
- # start_o2ims_mappers(uow.session.get_bind())\r
- # uow.commit()\r
- yield uow\r
- # clear_mappers()\r
- with uow:\r
- engine = uow.session.get_bind()\r
- metadata.drop_all(engine)\r
-\r
-\r
-@pytest.fixture\r
-def sqlite_flask_uow(sqlite_uow):\r
- app = Flask(__name__)\r
- app.config["TESTING"] = True\r
- api = Api(app)\r
- bootstrap(False, sqlite_uow)\r
- configure_namespace(api)\r
- yield sqlite_uow, app\r
-\r
-\r
-@pytest.fixture\r
-def mappers():\r
- start_o2ims_mappers()\r
- # start_o2ims_stx_mappers()\r
- yield\r
- clear_mappers()\r
-\r
-\r
-@retry(stop=stop_after_delay(10))\r
-def wait_for_postgres_to_come_up(engine):\r
- return engine.connect()\r
-\r
-\r
-@retry(stop=stop_after_delay(10))\r
-def wait_for_webapp_to_come_up():\r
- return requests.get(config.get_api_url())\r
-\r
-\r
-@retry(stop=stop_after_delay(10))\r
-def wait_for_redis_to_come_up():\r
- r = redis.Redis(**config.get_redis_host_and_port())\r
- return r.ping()\r
-\r
-\r
-@pytest.fixture(scope="session")\r
-def postgres_db():\r
- engine = create_engine(config.get_postgres_uri(),\r
- isolation_level="SERIALIZABLE")\r
- wait_for_postgres_to_come_up(engine)\r
- metadata.create_all(engine)\r
- return engine\r
-\r
-\r
-@pytest.fixture\r
-def postgres_session_factory(postgres_db):\r
- yield sessionmaker(bind=postgres_db)\r
-\r
-\r
-@pytest.fixture\r
-def postgres_session(postgres_session_factory):\r
- return postgres_session_factory()\r
-\r
-\r
-@pytest.fixture\r
-def postgres_uow(postgres_session_factory):\r
- uow = unit_of_work.SqlAlchemyUnitOfWork(\r
- session_factory=postgres_session_factory)\r
- yield uow\r
-\r
-\r
-@pytest.fixture\r
-def postgres_flask_uow(postgres_uow):\r
- app = Flask(__name__)\r
- app.config["TESTING"] = True\r
- api = Api(app)\r
- bootstrap(False, postgres_uow)\r
- configure_namespace(api)\r
- yield postgres_uow, app\r
-\r
-\r
-@pytest.fixture\r
-def restart_api():\r
- (Path(__file__).parent / "../src/o2ims/entrypoints/flask_application.py")\\r
- .touch()\r
- time.sleep(0.5)\r
- wait_for_webapp_to_come_up()\r
-\r
-\r
-@pytest.fixture\r
-def restart_redis_pubsub():\r
- wait_for_redis_to_come_up()\r
- if not shutil.which("docker-compose"):\r
- print("skipping restart, assumes running in container")\r
- return\r
- subprocess.run(\r
- ["docker-compose", "restart", "-t", "0", "redis_pubsub"],\r
- check=True,\r
- )\r
+# pylint: disable=redefined-outer-name
+import shutil
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+import redis
+import requests
+from flask import Flask
+from flask_restx import Api
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker, clear_mappers
+from tenacity import retry, stop_after_delay
+from unittest.mock import MagicMock
+
+from o2common.config import config
+
+from o2ims.adapter.orm import metadata, start_o2ims_mappers
+# from o2ims.adapter.clients.orm_stx import start_o2ims_stx_mappers
+
+from o2app.adapter import unit_of_work
+from o2ims.views import configure_namespace
+
+from o2app.bootstrap import bootstrap
+
+
+@pytest.fixture
+def mock_uow():
+ session = MagicMock()
+ uow = unit_of_work.SqlAlchemyUnitOfWork(session_factory=session)
+ return session, uow
+
+
+@pytest.fixture
+def mock_flask_uow(mock_uow):
+ session, uow = mock_uow
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ api = Api(app)
+ bootstrap(False, uow)
+ configure_namespace(api)
+ return session, app
+
+
+@pytest.fixture
+def in_memory_sqlite_db():
+ engine = create_engine("sqlite:///:memory:")
+ # engine = create_engine("sqlite:///:memory:", echo=True)
+ metadata.create_all(engine)
+ return engine
+
+
+@pytest.fixture
+def sqlite_session_factory(in_memory_sqlite_db):
+ yield sessionmaker(bind=in_memory_sqlite_db)
+
+
+@pytest.fixture
+def sqlite_uow(sqlite_session_factory):
+ uow = unit_of_work.SqlAlchemyUnitOfWork(
+ session_factory=sqlite_session_factory)
+ # with uow:
+ # start_o2ims_mappers(uow.session.get_bind())
+ # uow.commit()
+ yield uow
+ # clear_mappers()
+ with uow:
+ engine = uow.session.get_bind()
+ metadata.drop_all(engine)
+
+
+@pytest.fixture
+def sqlite_flask_uow(sqlite_uow):
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ api = Api(app)
+ bootstrap(False, sqlite_uow)
+ configure_namespace(api)
+ yield sqlite_uow, app
+
+
+@pytest.fixture
+def mappers():
+ start_o2ims_mappers()
+ # start_o2ims_stx_mappers()
+ yield
+ clear_mappers()
+
+
+@retry(stop=stop_after_delay(10))
+def wait_for_postgres_to_come_up(engine):
+ return engine.connect()
+
+
+@retry(stop=stop_after_delay(10))
+def wait_for_webapp_to_come_up():
+ return requests.get(config.get_api_url())
+
+
+@retry(stop=stop_after_delay(10))
+def wait_for_redis_to_come_up():
+ r = redis.Redis(**config.get_redis_host_and_port())
+ return r.ping()
+
+
+@pytest.fixture(scope="session")
+def postgres_db():
+ engine = create_engine(config.get_postgres_uri(),
+ isolation_level="SERIALIZABLE")
+ wait_for_postgres_to_come_up(engine)
+ metadata.create_all(engine)
+ return engine
+
+
+@pytest.fixture
+def postgres_session_factory(postgres_db):
+ yield sessionmaker(bind=postgres_db)
+
+
+@pytest.fixture
+def postgres_session(postgres_session_factory):
+ return postgres_session_factory()
+
+
+@pytest.fixture
+def postgres_uow(postgres_session_factory):
+ uow = unit_of_work.SqlAlchemyUnitOfWork(
+ session_factory=postgres_session_factory)
+ yield uow
+
+
+@pytest.fixture
+def postgres_flask_uow(postgres_uow):
+ app = Flask(__name__)
+ app.config["TESTING"] = True
+ api = Api(app)
+ bootstrap(False, postgres_uow)
+ configure_namespace(api)
+ yield postgres_uow, app
+
+
+@pytest.fixture
+def restart_api():
+ (Path(__file__).parent / "../src/o2ims/entrypoints/flask_application.py")\
+ .touch()
+ time.sleep(0.5)
+ wait_for_webapp_to_come_up()
+
+
+@pytest.fixture
+def restart_redis_pubsub():
+ wait_for_redis_to_come_up()
+ if not shutil.which("docker-compose"):
+ print("skipping restart, assumes running in container")
+ return
+ subprocess.run(
+ ["docker-compose", "restart", "-t", "0", "redis_pubsub"],
+ check=True,
+ )
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-# import sys\r
-# import logging\r
-import pytest\r
-\r
-from o2common.config import config\r
-from o2ims.adapter.clients.ocloud_sa_client import StxSaClientImp\r
-from cgtsclient.client import get_client\r
-\r
-\r
-@pytest.fixture\r
-def real_stx_aio_client():\r
- os_client_args = config.get_stx_access_info()\r
- config_client = get_client(**os_client_args)\r
- yield config_client\r
-\r
-# pytestmark = pytest.mark.usefixtures("mappers")\r
-\r
-\r
-def test_get_instanceinfo(real_stx_aio_client):\r
- # logger = logging.getLogger(__name__)\r
- stxclientimp = StxSaClientImp(real_stx_aio_client)\r
- assert stxclientimp is not None\r
- systeminfo = stxclientimp.getInstanceInfo()\r
- assert systeminfo is not None\r
- assert systeminfo.id is not None\r
- assert systeminfo.name is not None\r
- assert systeminfo.content is not None\r
-\r
-\r
-def test_get_pserverlist(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- hosts = stxSaClientImp.getPserverList()\r
- assert hosts is not None\r
- assert len(hosts) > 0\r
-\r
-\r
-def test_get_pserver(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- hosts = stxSaClientImp.getPserverList()\r
- assert hosts is not None\r
- assert len(hosts) > 0\r
- host1 = hosts[0]\r
- host2 = stxSaClientImp.getPserver(host1.id)\r
- assert host1 != host2\r
- assert host1.id == host2.id\r
-\r
-\r
-def test_get_k8s_list(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- k8slist = stxSaClientImp.getK8sList()\r
- assert k8slist is not None\r
- assert len(k8slist) > 0\r
- k8s1 = k8slist[0]\r
- k8s2 = stxSaClientImp.getK8sDetail(k8s1.name)\r
- assert k8s1 != k8s2\r
- assert k8s1.name == k8s2.name\r
- assert k8s1.id == k8s2.id\r
-\r
-\r
-def test_get_cpu_list(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- hostlist = stxSaClientImp.getPserverList()\r
- assert len(hostlist) > 0\r
-\r
- cpulist = stxSaClientImp.getCpuList(hostid=hostlist[0].id)\r
- assert len(cpulist) > 0\r
- cpu1 = cpulist[0]\r
- cpu2 = stxSaClientImp.getCpu(cpu1.id)\r
- assert cpu1 != cpu2\r
- assert cpu1.id == cpu2.id\r
-\r
-\r
-def test_get_mem_list(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- hostlist = stxSaClientImp.getPserverList()\r
- assert len(hostlist) > 0\r
-\r
- memlist = stxSaClientImp.getMemList(hostid=hostlist[0].id)\r
- assert len(memlist) > 0\r
- mem1 = memlist[0]\r
- mem2 = stxSaClientImp.getMem(mem1.id)\r
- assert mem1 != mem2\r
- assert mem1.id == mem2.id\r
-\r
-\r
-def test_get_eth_list(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- hostlist = stxSaClientImp.getPserverList()\r
- assert len(hostlist) > 0\r
-\r
- ethlist = stxSaClientImp.getEthernetList(hostid=hostlist[0].id)\r
- assert len(ethlist) > 0\r
- eth1 = ethlist[0]\r
- eth2 = stxSaClientImp.getEthernet(eth1.id)\r
- assert eth1 != eth2\r
- assert eth1.id == eth2.id\r
-\r
-\r
-def test_get_if_list(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- hostlist = stxSaClientImp.getPserverList()\r
- assert len(hostlist) > 0\r
-\r
- iflist = stxSaClientImp.getIfList(hostid=hostlist[0].id)\r
- assert len(iflist) > 0\r
- if1 = iflist[0]\r
- if2 = stxSaClientImp.getIf(if1.id)\r
- assert if1 != if2\r
- assert if1.id == if2.id\r
-\r
-\r
-def test_get_if_port_list(real_stx_aio_client):\r
- stxSaClientImp = StxSaClientImp(real_stx_aio_client)\r
- assert stxSaClientImp is not None\r
- hostlist = stxSaClientImp.getPserverList()\r
- assert len(hostlist) > 0\r
-\r
- iflist = stxSaClientImp.getIfList(hostid=hostlist[0].id)\r
- assert len(iflist) > 0\r
-\r
- portlist = stxSaClientImp.getPortList(interfaceid=iflist[0].id)\r
- assert len(portlist) > 0\r
- port1 = portlist[0]\r
- port2 = stxSaClientImp.getPort(port1.id)\r
- assert port1 != port2\r
- assert port1.id == port2.id\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 sys
+# import logging
+import pytest
+
+from o2common.config import config
+from o2ims.adapter.clients.ocloud_sa_client import StxSaClientImp
+from cgtsclient.client import get_client
+
+
+@pytest.fixture
+def real_stx_aio_client():
+ os_client_args = config.get_stx_access_info()
+ config_client = get_client(**os_client_args)
+ yield config_client
+
+# pytestmark = pytest.mark.usefixtures("mappers")
+
+
+def test_get_instanceinfo(real_stx_aio_client):
+ # logger = logging.getLogger(__name__)
+ stxclientimp = StxSaClientImp(real_stx_aio_client)
+ assert stxclientimp is not None
+ systeminfo = stxclientimp.getInstanceInfo()
+ assert systeminfo is not None
+ assert systeminfo.id is not None
+ assert systeminfo.name is not None
+ assert systeminfo.content is not None
+
+
+def test_get_pserverlist(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ hosts = stxSaClientImp.getPserverList()
+ assert hosts is not None
+ assert len(hosts) > 0
+
+
+def test_get_pserver(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ hosts = stxSaClientImp.getPserverList()
+ assert hosts is not None
+ assert len(hosts) > 0
+ host1 = hosts[0]
+ host2 = stxSaClientImp.getPserver(host1.id)
+ assert host1 != host2
+ assert host1.id == host2.id
+
+
+def test_get_k8s_list(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ k8slist = stxSaClientImp.getK8sList()
+ assert k8slist is not None
+ assert len(k8slist) > 0
+ k8s1 = k8slist[0]
+ k8s2 = stxSaClientImp.getK8sDetail(k8s1.name)
+ assert k8s1 != k8s2
+ assert k8s1.name == k8s2.name
+ assert k8s1.id == k8s2.id
+
+
+def test_get_cpu_list(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ hostlist = stxSaClientImp.getPserverList()
+ assert len(hostlist) > 0
+
+ cpulist = stxSaClientImp.getCpuList(hostid=hostlist[0].id)
+ assert len(cpulist) > 0
+ cpu1 = cpulist[0]
+ cpu2 = stxSaClientImp.getCpu(cpu1.id)
+ assert cpu1 != cpu2
+ assert cpu1.id == cpu2.id
+
+
+def test_get_mem_list(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ hostlist = stxSaClientImp.getPserverList()
+ assert len(hostlist) > 0
+
+ memlist = stxSaClientImp.getMemList(hostid=hostlist[0].id)
+ assert len(memlist) > 0
+ mem1 = memlist[0]
+ mem2 = stxSaClientImp.getMem(mem1.id)
+ assert mem1 != mem2
+ assert mem1.id == mem2.id
+
+
+def test_get_eth_list(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ hostlist = stxSaClientImp.getPserverList()
+ assert len(hostlist) > 0
+
+ ethlist = stxSaClientImp.getEthernetList(hostid=hostlist[0].id)
+ assert len(ethlist) > 0
+ eth1 = ethlist[0]
+ eth2 = stxSaClientImp.getEthernet(eth1.id)
+ assert eth1 != eth2
+ assert eth1.id == eth2.id
+
+
+def test_get_if_list(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ hostlist = stxSaClientImp.getPserverList()
+ assert len(hostlist) > 0
+
+ iflist = stxSaClientImp.getIfList(hostid=hostlist[0].id)
+ assert len(iflist) > 0
+ if1 = iflist[0]
+ if2 = stxSaClientImp.getIf(if1.id)
+ assert if1 != if2
+ assert if1.id == if2.id
+
+
+def test_get_if_port_list(real_stx_aio_client):
+ stxSaClientImp = StxSaClientImp(real_stx_aio_client)
+ assert stxSaClientImp is not None
+ hostlist = stxSaClientImp.getPserverList()
+ assert len(hostlist) > 0
+
+ iflist = stxSaClientImp.getIfList(hostid=hostlist[0].id)
+ assert len(iflist) > 0
+
+ portlist = stxSaClientImp.getPortList(interfaceid=iflist[0].id)
+ assert len(portlist) > 0
+ port1 = portlist[0]
+ port2 = stxSaClientImp.getPort(port1.id)
+ assert port1 != port2
+ assert port1.id == port2.id
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from multiprocessing.queues import Queue\r
-import pytest\r
-from o2app.entrypoints.resource_watcher import start_watchers\r
-from multiprocessing import Process\r
-from multiprocessing import Pipe\r
-# pipe = Pipe()\r
-# q = Queue()\r
-import time\r
-# pytestmark = pytest.mark.usefixtures("mappers")\r
-\r
-\r
-def test_watcher_service():\r
- testedprocess = Process(target=start_watchers, args=())\r
- testedprocess.start()\r
- time.sleep(10)\r
- testedprocess.terminate()\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 multiprocessing.queues import Queue
+import pytest
+from o2app.entrypoints.resource_watcher import start_watchers
+from multiprocessing import Process
+from multiprocessing import Pipe
+# pipe = Pipe()
+# q = Queue()
+import time
+# pytestmark = pytest.mark.usefixtures("mappers")
+
+
+def test_watcher_service():
+ testedprocess = Process(target=start_watchers, args=())
+ testedprocess.start()
+ time.sleep(10)
+ testedprocess.terminate()
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-from datetime import date, datetime\r
-import sys\r
-import pytest\r
-from o2ims.adapter import ocloud_repository as repository\r
-from o2ims.domain import ocloud\r
-from o2common.config import config\r
-import logging\r
-import uuid\r
-import json\r
-from o2ims.adapter.clients.ocloud_sa_client import StxSaOcloudClient\r
-from o2ims.domain import stx_object as ocloudModel\r
-from o2ims.domain.resource_type import ResourceTypeEnum\r
-\r
-# pytestmark = pytest.mark.usefixtures("mappers")\r
-\r
-\r
-class FakeStxSaClientImp(object):\r
- def __init__(self):\r
- super().__init__()\r
-\r
- def getInstanceInfo(self) -> ocloudModel.StxGenericModel:\r
- model = ocloudModel.StxGenericModel(ResourceTypeEnum.OCLOUD)\r
- model.id = uuid.uuid4()\r
- model.name = "stx1"\r
- model.updatetime = datetime.now\r
- model.createtime = datetime.now\r
- model.content = json.dumps({})\r
- return model\r
-\r
-\r
-@pytest.fixture\r
-def fake_driver_imp():\r
- fakedriver = FakeStxSaClientImp()\r
- yield fakedriver\r
-\r
-\r
-def test_get_instanceinfo(fake_driver_imp):\r
- logger = logging.getLogger(__name__)\r
- stxclientimp = StxSaOcloudClient(fake_driver_imp)\r
- assert stxclientimp is not None\r
- systeminfo = stxclientimp.get(None)\r
- assert systeminfo is not None\r
- assert systeminfo.id is not None\r
- assert systeminfo.name == "stx1"\r
- assert systeminfo.content == json.dumps({})\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 datetime import date, datetime
+import sys
+import pytest
+from o2ims.adapter import ocloud_repository as repository
+from o2ims.domain import ocloud
+from o2common.config import config
+import logging
+import uuid
+import json
+from o2ims.adapter.clients.ocloud_sa_client import StxSaOcloudClient
+from o2ims.domain import stx_object as ocloudModel
+from o2ims.domain.resource_type import ResourceTypeEnum
+
+# pytestmark = pytest.mark.usefixtures("mappers")
+
+
+class FakeStxSaClientImp(object):
+ def __init__(self):
+ super().__init__()
+
+ def getInstanceInfo(self) -> ocloudModel.StxGenericModel:
+ model = ocloudModel.StxGenericModel(ResourceTypeEnum.OCLOUD)
+ model.id = uuid.uuid4()
+ model.name = "stx1"
+ model.updatetime = datetime.now
+ model.createtime = datetime.now
+ model.content = json.dumps({})
+ return model
+
+
+@pytest.fixture
+def fake_driver_imp():
+ fakedriver = FakeStxSaClientImp()
+ yield fakedriver
+
+
+def test_get_instanceinfo(fake_driver_imp):
+ logger = logging.getLogger(__name__)
+ stxclientimp = StxSaOcloudClient(fake_driver_imp)
+ assert stxclientimp is not None
+ systeminfo = stxclientimp.get(None)
+ assert systeminfo is not None
+ assert systeminfo.id is not None
+ assert systeminfo.name == "stx1"
+ assert systeminfo.content == json.dumps({})
-# Copyright (C) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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) 2021 Wind River Systems, Inc.\r
-#\r
-# Licensed under the Apache License, Version 2.0 (the "License");\r
-# you may not use this file except in compliance with the License.\r
-# You may obtain a copy of the License at\r
-#\r
-# http://www.apache.org/licenses/LICENSE-2.0\r
-#\r
-# Unless required by applicable law or agreed to in writing, software\r
-# distributed under the License is distributed on an "AS IS" BASIS,\r
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
-# See the License for the specific language governing permissions and\r
-# limitations under the License.\r
-\r
-import time\r
-from datetime import datetime\r
-import json\r
-from typing import Callable, List\r
-# from o2common.config import config\r
-import uuid\r
-from o2common.service.watcher.base import BaseWatcher, WatcherTree\r
-from o2common.service.watcher import worker\r
-from o2common.service.unit_of_work import AbstractUnitOfWork\r
-from o2common.service import messagebus\r
-\r
-from o2ims.domain.resource_type import ResourceTypeEnum\r
-from o2ims.domain import stx_object as ocloudModel\r
-from o2ims.adapter.ocloud_repository import OcloudRepository\r
-from o2ims.domain.stx_repo import StxObjectRepository\r
-from o2ims.service.watcher.ocloud_watcher import OcloudWatcher\r
-from o2ims.domain import commands\r
-from o2common.service.client.base_client import BaseClient\r
-from o2ims.domain import ocloud\r
-\r
-from o2app.service import handlers\r
-from o2app import bootstrap\r
-\r
-\r
-class FakeOcloudClient(BaseClient):\r
- def __init__(self):\r
- super().__init__()\r
- fakeCloud = ocloudModel.StxGenericModel(ResourceTypeEnum.OCLOUD)\r
- fakeCloud.id = uuid.uuid4()\r
- fakeCloud.name = 'stx1'\r
- fakeCloud.content = json.dumps({})\r
- fakeCloud.createtime = datetime.now()\r
- fakeCloud.updatetime = datetime.now()\r
- fakeCloud.hash = str(hash((fakeCloud.id, fakeCloud.updatetime)))\r
- self.fakeCloud = fakeCloud\r
-\r
- def _get(self, id) -> ocloudModel.StxGenericModel:\r
- return self.fakeCloud\r
-\r
- def _list(self):\r
- return [self.fakeCloud]\r
-\r
-\r
-class FakeOcloudRepo(OcloudRepository):\r
- def __init__(self):\r
- super().__init__()\r
- self.oclouds = []\r
-\r
- def _add(self, ocloud: ocloud.Ocloud):\r
- self.oclouds.append(ocloud)\r
-\r
- def _get(self, ocloudid) -> ocloud.Ocloud:\r
- filtered = [o for o in self.oclouds if o.id == ocloudid]\r
- return filtered.pop()\r
-\r
- def _list(self) -> List[ocloud.Ocloud]:\r
- return [x for x in self.oclouds]\r
-\r
- def _update(self, ocloud: ocloud.Ocloud):\r
- filtered = [o for o in self.oclouds if o.id == ocloud.id]\r
- assert len(filtered) == 1\r
- ocloud1 = filtered.pop()\r
- ocloud1.update_by(ocloud)\r
-\r
-\r
-class FakeStxObjRepo(StxObjectRepository):\r
- def __init__(self):\r
- super().__init__()\r
- self.oclouds = []\r
-\r
- def _add(self, ocloud: ocloud.Ocloud):\r
- self.oclouds.append(ocloud)\r
-\r
- def _get(self, ocloudid) -> ocloud.Ocloud:\r
- filtered = [o for o in self.oclouds if o.id == ocloudid]\r
- return filtered.pop()\r
-\r
- def _list(self, type: ResourceTypeEnum) -> List[ocloud.Ocloud]:\r
- return [x for x in self.oclouds]\r
-\r
- def _update(self, ocloud: ocloud.Ocloud):\r
- filtered = [o for o in self.oclouds if o.id == ocloud.id]\r
- assert len(filtered) == 1\r
- ocloud1 = filtered.pop()\r
- ocloud1.update_by(ocloud)\r
-\r
-\r
-class FakeUnitOfWork(AbstractUnitOfWork):\r
- def __init__(self):\r
- pass\r
-\r
- def __enter__(self):\r
- # self.session = self.session_factory() # type: Session\r
- # self.oclouds = OcloudSqlAlchemyRepository(self.session)\r
- self.stxobjects = FakeStxObjRepo()\r
- return super().__enter__()\r
-\r
- def __exit__(self, *args):\r
- super().__exit__(*args)\r
- # self.session.close()\r
-\r
- def _commit(self):\r
- pass\r
- # self.session.commit()\r
-\r
- def rollback(self):\r
- pass\r
- # self.session.rollback()\r
-\r
- def collect_new_events(self):\r
- yield\r
- # return super().collect_new_events()\r
-\r
-\r
-def create_fake_bus(uow):\r
- def update_ocloud(\r
- cmd: commands.UpdateOCloud,\r
- uow: AbstractUnitOfWork,\r
- publish: Callable):\r
- return\r
-\r
- fakeuow = FakeUnitOfWork()\r
- handlers.EVENT_HANDLERS = {}\r
- handlers.COMMAND_HANDLERS = {\r
- commands.UpdateOCloud: update_ocloud,\r
- }\r
- bus = bootstrap.bootstrap(False, fakeuow)\r
- return bus\r
-\r
-\r
-def test_probe_new_ocloud():\r
- fakeuow = FakeUnitOfWork()\r
- bus = create_fake_bus(fakeuow)\r
- fakeClient = FakeOcloudClient()\r
- ocloudwatcher = OcloudWatcher(fakeClient, bus)\r
- cmds = ocloudwatcher.probe()\r
- assert cmds is not None\r
- assert len(cmds) == 1\r
- assert cmds[0].data.name == "stx1"\r
- # assert len(fakeuow.stxobjects.oclouds) == 1\r
- # assert fakeuow.stxobjects.oclouds[0].name == "stx1"\r
-\r
-\r
-def test_watchers_worker():\r
- testedworker = worker.PollWorker()\r
-\r
- class FakeOCloudWatcher(BaseWatcher):\r
- def __init__(self, client: BaseClient,\r
- bus: messagebus) -> None:\r
- super().__init__(client, None)\r
- self.fakeOcloudWatcherCounter = 0\r
- self._client = client\r
- self._bus = bus\r
-\r
- def _targetname(self):\r
- return "fakeocloudwatcher"\r
-\r
- def _probe(self, parent: object = None):\r
- # import pdb; pdb.set_trace()\r
- self.fakeOcloudWatcherCounter += 1\r
- # hacking to stop the blocking sched task\r
- if self.fakeOcloudWatcherCounter > 2:\r
- testedworker.stop()\r
- return []\r
-\r
- # fakeRepo = FakeOcloudRepo()\r
- fakeuow = FakeUnitOfWork()\r
- bus = create_fake_bus(fakeuow)\r
-\r
- fakeClient = FakeOcloudClient()\r
- fakewatcher = FakeOCloudWatcher(fakeClient, bus)\r
-\r
- root = WatcherTree(fakewatcher)\r
-\r
- testedworker.set_interval(1)\r
- testedworker.add_watcher(root)\r
- assert fakewatcher.fakeOcloudWatcherCounter == 0\r
-\r
- count1 = fakewatcher.fakeOcloudWatcherCounter\r
- testedworker.start()\r
- time.sleep(20)\r
- assert fakewatcher.fakeOcloudWatcherCounter > count1\r
-\r
- # assumed hacking: probe has stopped the sched task\r
- count3 = fakewatcher.fakeOcloudWatcherCounter\r
- time.sleep(3)\r
- assert fakewatcher.fakeOcloudWatcherCounter == count3\r
+# Copyright (C) 2021 Wind River Systems, Inc.
+#
+# 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 time
+from datetime import datetime
+import json
+from typing import Callable, List
+# from o2common.config import config
+import uuid
+from o2common.service.watcher.base import BaseWatcher, WatcherTree
+from o2common.service.watcher import worker
+from o2common.service.unit_of_work import AbstractUnitOfWork
+from o2common.service import messagebus
+
+from o2ims.domain.resource_type import ResourceTypeEnum
+from o2ims.domain import stx_object as ocloudModel
+from o2ims.adapter.ocloud_repository import OcloudRepository
+from o2ims.domain.stx_repo import StxObjectRepository
+from o2ims.service.watcher.ocloud_watcher import OcloudWatcher
+from o2ims.domain import commands
+from o2common.service.client.base_client import BaseClient
+from o2ims.domain import ocloud
+
+from o2app.service import handlers
+from o2app import bootstrap
+
+
+class FakeOcloudClient(BaseClient):
+ def __init__(self):
+ super().__init__()
+ fakeCloud = ocloudModel.StxGenericModel(ResourceTypeEnum.OCLOUD)
+ fakeCloud.id = uuid.uuid4()
+ fakeCloud.name = 'stx1'
+ fakeCloud.content = json.dumps({})
+ fakeCloud.createtime = datetime.now()
+ fakeCloud.updatetime = datetime.now()
+ fakeCloud.hash = str(hash((fakeCloud.id, fakeCloud.updatetime)))
+ self.fakeCloud = fakeCloud
+
+ def _get(self, id) -> ocloudModel.StxGenericModel:
+ return self.fakeCloud
+
+ def _list(self):
+ return [self.fakeCloud]
+
+
+class FakeOcloudRepo(OcloudRepository):
+ def __init__(self):
+ super().__init__()
+ self.oclouds = []
+
+ def _add(self, ocloud: ocloud.Ocloud):
+ self.oclouds.append(ocloud)
+
+ def _get(self, ocloudid) -> ocloud.Ocloud:
+ filtered = [o for o in self.oclouds if o.id == ocloudid]
+ return filtered.pop()
+
+ def _list(self) -> List[ocloud.Ocloud]:
+ return [x for x in self.oclouds]
+
+ def _update(self, ocloud: ocloud.Ocloud):
+ filtered = [o for o in self.oclouds if o.id == ocloud.id]
+ assert len(filtered) == 1
+ ocloud1 = filtered.pop()
+ ocloud1.update_by(ocloud)
+
+
+class FakeStxObjRepo(StxObjectRepository):
+ def __init__(self):
+ super().__init__()
+ self.oclouds = []
+
+ def _add(self, ocloud: ocloud.Ocloud):
+ self.oclouds.append(ocloud)
+
+ def _get(self, ocloudid) -> ocloud.Ocloud:
+ filtered = [o for o in self.oclouds if o.id == ocloudid]
+ return filtered.pop()
+
+ def _list(self, type: ResourceTypeEnum) -> List[ocloud.Ocloud]:
+ return [x for x in self.oclouds]
+
+ def _update(self, ocloud: ocloud.Ocloud):
+ filtered = [o for o in self.oclouds if o.id == ocloud.id]
+ assert len(filtered) == 1
+ ocloud1 = filtered.pop()
+ ocloud1.update_by(ocloud)
+
+
+class FakeUnitOfWork(AbstractUnitOfWork):
+ def __init__(self):
+ pass
+
+ def __enter__(self):
+ # self.session = self.session_factory() # type: Session
+ # self.oclouds = OcloudSqlAlchemyRepository(self.session)
+ self.stxobjects = FakeStxObjRepo()
+ return super().__enter__()
+
+ def __exit__(self, *args):
+ super().__exit__(*args)
+ # self.session.close()
+
+ def _commit(self):
+ pass
+ # self.session.commit()
+
+ def rollback(self):
+ pass
+ # self.session.rollback()
+
+ def collect_new_events(self):
+ yield
+ # return super().collect_new_events()
+
+
+def create_fake_bus(uow):
+ def update_ocloud(
+ cmd: commands.UpdateOCloud,
+ uow: AbstractUnitOfWork,
+ publish: Callable):
+ return
+
+ fakeuow = FakeUnitOfWork()
+ handlers.EVENT_HANDLERS = {}
+ handlers.COMMAND_HANDLERS = {
+ commands.UpdateOCloud: update_ocloud,
+ }
+ bus = bootstrap.bootstrap(False, fakeuow)
+ return bus
+
+
+def test_probe_new_ocloud():
+ fakeuow = FakeUnitOfWork()
+ bus = create_fake_bus(fakeuow)
+ fakeClient = FakeOcloudClient()
+ ocloudwatcher = OcloudWatcher(fakeClient, bus)
+ cmds = ocloudwatcher.probe()
+ assert cmds is not None
+ assert len(cmds) == 1
+ assert cmds[0].data.name == "stx1"
+ # assert len(fakeuow.stxobjects.oclouds) == 1
+ # assert fakeuow.stxobjects.oclouds[0].name == "stx1"
+
+
+def test_watchers_worker():
+ testedworker = worker.PollWorker()
+
+ class FakeOCloudWatcher(BaseWatcher):
+ def __init__(self, client: BaseClient,
+ bus: messagebus) -> None:
+ super().__init__(client, None)
+ self.fakeOcloudWatcherCounter = 0
+ self._client = client
+ self._bus = bus
+
+ def _targetname(self):
+ return "fakeocloudwatcher"
+
+ def _probe(self, parent: object = None):
+ # import pdb; pdb.set_trace()
+ self.fakeOcloudWatcherCounter += 1
+ # hacking to stop the blocking sched task
+ if self.fakeOcloudWatcherCounter > 2:
+ testedworker.stop()
+ return []
+
+ # fakeRepo = FakeOcloudRepo()
+ fakeuow = FakeUnitOfWork()
+ bus = create_fake_bus(fakeuow)
+
+ fakeClient = FakeOcloudClient()
+ fakewatcher = FakeOCloudWatcher(fakeClient, bus)
+
+ root = WatcherTree(fakewatcher)
+
+ testedworker.set_interval(1)
+ testedworker.add_watcher(root)
+ assert fakewatcher.fakeOcloudWatcherCounter == 0
+
+ count1 = fakewatcher.fakeOcloudWatcherCounter
+ testedworker.start()
+ time.sleep(20)
+ assert fakewatcher.fakeOcloudWatcherCounter > count1
+
+ # assumed hacking: probe has stopped the sched task
+ count3 = fakewatcher.fakeOcloudWatcherCounter
+ time.sleep(3)
+ assert fakewatcher.fakeOcloudWatcherCounter == count3
-# content of: tox.ini , put in same dir as setup.py\r
-[tox]\r
-envlist=\r
- flake8,\r
- code,\r
- docs,\r
- docs-linkcheck,\r
-\r
-minversion = 2.0\r
-skipsdist = True\r
-\r
-[testenv]\r
-basepython =\r
- code: python3.8\r
- flake8: python3.8\r
-setenv =\r
- VIRTUAL_ENV={envdir}\r
-\r
-# NOTE: relative paths were used due to '-w' flag for nosetests util\r
-\r
-usedevelop = True\r
-install_command = pip install -U {opts} {packages}\r
-deps = -r{toxinidir}/requirements.txt\r
- -r{toxinidir}/requirements-test.txt\r
-whitelist_externals = bash, flake8, pytest\r
-\r
-[testenv:flake8]\r
-commands =\r
- flake8 o2ims\r
- flake8 o2dms\r
- flake8 o2common\r
-\r
-[testenv:code]\r
-commands =\r
- pytest tests/unit\r
-\r
-[testenv:nosetests]\r
-commands =\r
- pytest tests/unit\r
-\r
-\r
-[testenv:docs]\r
-basepython = python3\r
-deps =\r
- sphinx\r
- sphinx-rtd-theme\r
- sphinxcontrib-httpdomain\r
- recommonmark\r
- lfdocs-conf\r
-\r
-commands =\r
- sphinx-build -W -b html -n -d {envtmpdir}/doctrees ./docs/ {toxinidir}/docs/_build/html\r
-\r
- echo "Generated docs available in {toxinidir}/docs/_build/html"\r
-\r
-whitelist_externals = echo\r
-\r
-[testenv:docs-linkcheck]\r
-basepython = python3\r
-deps = sphinx\r
- sphinx-rtd-theme\r
- sphinxcontrib-httpdomain\r
- recommonmark\r
- lfdocs-conf\r
-commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees ./docs/ {toxinidir}/docs/_build/linkcheck\r
+# content of: tox.ini , put in same dir as setup.py
+[tox]
+envlist=
+ flake8,
+ code,
+ docs,
+ docs-linkcheck,
+
+minversion = 2.0
+skipsdist = True
+
+[testenv]
+basepython =
+ code: python3.8
+ flake8: python3.8
+setenv =
+ VIRTUAL_ENV={envdir}
+
+# NOTE: relative paths were used due to '-w' flag for nosetests util
+
+usedevelop = True
+install_command = pip install -U {opts} {packages}
+deps = -r{toxinidir}/requirements.txt
+ -r{toxinidir}/requirements-test.txt
+whitelist_externals = bash, flake8, pytest
+
+[testenv:flake8]
+commands =
+ flake8 o2ims
+ flake8 o2dms
+ flake8 o2common
+
+[testenv:code]
+commands =
+ pytest tests/unit
+
+[testenv:nosetests]
+commands =
+ pytest tests/unit
+
+
+[testenv:docs]
+basepython = python3
+deps =
+ sphinx
+ sphinx-rtd-theme
+ sphinxcontrib-httpdomain
+ recommonmark
+ lfdocs-conf
+
+commands =
+ sphinx-build -W -b html -n -d {envtmpdir}/doctrees ./docs/ {toxinidir}/docs/_build/html
+
+ echo "Generated docs available in {toxinidir}/docs/_build/html"
+
+whitelist_externals = echo
+
+[testenv:docs-linkcheck]
+basepython = python3
+deps = sphinx
+ sphinx-rtd-theme
+ sphinxcontrib-httpdomain
+ recommonmark
+ lfdocs-conf
+commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees ./docs/ {toxinidir}/docs/_build/linkcheck