Skip to content
Snippets Groups Projects
Commit 3b3afa9e authored by Carlos Natalino Da Silva's avatar Carlos Natalino Da Silva
Browse files

Including the optical attack manager.

parent 5d8b9352
No related branches found
No related tags found
2 merge requests!142Release TeraFlowSDN 2.1,!97Optical cybersecurity scenario
Showing
with 1205 additions and 4 deletions
......@@ -169,11 +169,17 @@ kubectl create secret generic qdb-data --namespace ${TFS_K8S_NAMESPACE} --type='
--from-literal=METRICSDB_PASSWORD=${QDB_PASSWORD}
printf "\n"
echo "Create Redis secret..."
REDIS_PASSWORD=`uuidgen`
kubectl create secret generic redis-secrets --namespace=$TFS_K8S_NAMESPACE \
--from-literal=REDIS_PASSWORD=$REDIS_PASSWORD
echo "Deploying components and collecting environment variables..."
ENV_VARS_SCRIPT=tfs_runtime_env_vars.sh
echo "# Environment variables for TeraFlowSDN deployment" > $ENV_VARS_SCRIPT
PYTHONPATH=$(pwd)/src
echo "export PYTHONPATH=${PYTHONPATH}" >> $ENV_VARS_SCRIPT
echo "export REDIS_PASSWORD=${REDIS_PASSWORD}" >> $ENV_VARS_SCRIPT
for COMPONENT in $TFS_COMPONENTS; do
echo "Processing '$COMPONENT' component..."
......
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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: opticalattackmanagerservice
spec:
selector:
matchLabels:
app: opticalattackmanagerservice
template:
metadata:
labels:
app: opticalattackmanagerservice
spec:
terminationGracePeriodSeconds: 5
containers:
- name: server
image: labs.etsi.org:5050/tfs/controller/opticalattackmanager:latest
imagePullPolicy: Always
ports:
- containerPort: 10005
- containerPort: 9192
env:
- name: LOG_LEVEL
value: "DEBUG"
- name: MONITORING_INTERVAL
value: "30"
- name: OPTICALATTACKMANAGERSERVICE_LOOP_MIN_WORKERS
value: "2" # remember to align this with the resource limits
- name: OPTICALATTACKMANAGERSERVICE_LOOP_MAX_WORKERS
value: "10" # remember to align this with the resource limits
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: redis-secrets
key: REDIS_PASSWORD
resources:
requests:
cpu: 250m
memory: 128Mi
limits:
cpu: 10000m
memory: 10240Mi
---
apiVersion: v1
kind: Service
metadata:
name: opticalattackmanagerservice
labels:
app: opticalattackmanagerservice
spec:
type: ClusterIP
selector:
app: opticalattackmanagerservice
ports:
- name: grpc
port: 10005
targetPort: 10005
- name: metrics
port: 9192
targetPort: 9192
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: opticalattackdetectorservice-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: opticalattackdetectorservice
minReplicas: 1
maxReplicas: 1
......@@ -22,6 +22,9 @@ export TFS_REGISTRY_IMAGES="http://localhost:32000/tfs/"
# Set the list of components, separated by spaces, you want to build images for, and deploy.
export TFS_COMPONENTS="context device automation monitoring pathcomp service slice compute webui load_generator"
# addition for the optical cybersecurity component
export TFS_COMPONENTS="${TFS_COMPONENTS} dbscanserving opticalattackmitigator opticalattackdetector opticalattackmanager"
# Set the tag you want to use for your images.
export TFS_IMAGE_TAG="dev"
......@@ -29,7 +32,7 @@ export TFS_IMAGE_TAG="dev"
export TFS_K8S_NAMESPACE="tfs"
# Set additional manifest files to be applied after the deployment
export TFS_EXTRA_MANIFESTS="manifests/nginx_ingress_http.yaml manifests/servicemonitors.yaml"
export TFS_EXTRA_MANIFESTS="manifests/nginx_ingress_http.yaml manifests/servicemonitors.yaml manifests/cachingservice.yaml"
# Set the new Grafana admin password
export TFS_GRAFANA_PASSWORD="admin123+"
......@@ -63,7 +66,7 @@ export CRDB_DATABASE="tfs"
export CRDB_DEPLOY_MODE="single"
# Disable flag for dropping database, if it exists.
export CRDB_DROP_DATABASE_IF_EXISTS=""
export CRDB_DROP_DATABASE_IF_EXISTS="YES"
# Disable flag for re-deploying CockroachDB from scratch.
export CRDB_REDEPLOY=""
......@@ -111,7 +114,7 @@ export QDB_TABLE_MONITORING_KPIS="tfs_monitoring_kpis"
export QDB_TABLE_SLICE_GROUPS="tfs_slice_groups"
# Disable flag for dropping tables if they exist.
export QDB_DROP_TABLES_IF_EXIST=""
export QDB_DROP_TABLES_IF_EXIST="YES"
# Disable flag for re-deploying QuestDB from scratch.
export QDB_REDEPLOY=""
......
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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.
# Build, tag, and push the Docker image to the GitLab Docker registry
build opticalattackmanager:
variables:
IMAGE_NAME: 'opticalattackmanager' # name of the microservice
IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
stage: build
before_script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
script:
- docker build -t "$IMAGE_NAME:$IMAGE_TAG" -f ./src/$IMAGE_NAME/Dockerfile .
- docker tag "$IMAGE_NAME:$IMAGE_TAG" "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
- docker push "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
after_script:
- docker images --filter="dangling=true" --quiet | xargs -r docker rmi
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)'
- if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "develop"'
- changes:
- src/common/**/*.py
- proto/*.proto
- src/$IMAGE_NAME/**/*.{py,in,yml}
- src/$IMAGE_NAME/Dockerfile
- src/$IMAGE_NAME/tests/*.py
- manifests/${IMAGE_NAME}service.yaml
- .gitlab-ci.yml
# Apply unit test to the component
unit test opticalattackmanager:
variables:
IMAGE_NAME: 'opticalattackmanager' # name of the microservice
IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
stage: unit_test
needs:
- build opticalattackmanager
before_script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
- if docker network list | grep teraflowbridge; then echo "teraflowbridge is already created"; else docker network create -d bridge teraflowbridge; fi
- if docker container ls | grep $IMAGE_NAME; then docker rm -f $IMAGE_NAME; else echo "$IMAGE_NAME image is not in the system"; fi
script:
- docker pull "$CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG"
- docker run --name $IMAGE_NAME -d -p 10005:10005 -v "$PWD/src/$IMAGE_NAME/tests:/home/teraflow/$IMAGE_NAME/results" --network=teraflowbridge $CI_REGISTRY_IMAGE/$IMAGE_NAME:$IMAGE_TAG
- docker ps -a
- docker logs $IMAGE_NAME
- docker exec -i $IMAGE_NAME bash -c "coverage run -m pytest --log-level=INFO --verbose $IMAGE_NAME/tests/test_unitary.py --junitxml=/home/teraflow/$IMAGE_NAME/results/${IMAGE_NAME}_report.xml"
- docker exec -i $IMAGE_NAME bash -c "coverage report --include='${IMAGE_NAME}/*' --show-missing"
coverage: '/TOTAL\s+\d+\s+\d+\s+(\d+%)/'
after_script:
- docker rm -f $IMAGE_NAME
- docker network rm teraflowbridge
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)'
- if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "develop"'
- changes:
- src/common/**/*.py
- proto/*.proto
- src/$IMAGE_NAME/**/*.{py,in,yml}
- src/$IMAGE_NAME/Dockerfile
- src/$IMAGE_NAME/tests/*.py
- src/$IMAGE_NAME/tests/Dockerfile
- manifests/${IMAGE_NAME}service.yaml
- .gitlab-ci.yml
artifacts:
when: always
reports:
junit: src/$IMAGE_NAME/tests/${IMAGE_NAME}_report.xml
# Deployment of the service in Kubernetes Cluster
deploy opticalattackmanager:
variables:
IMAGE_NAME: 'opticalattackmanager' # name of the microservice
IMAGE_TAG: 'latest' # tag of the container image (production, development, etc)
stage: deploy
needs:
- unit test opticalattackmanager
# - integ_test execute
script:
- 'sed -i "s/$IMAGE_NAME:.*/$IMAGE_NAME:$IMAGE_TAG/" manifests/${IMAGE_NAME}service.yaml'
- kubectl version
- kubectl get all
- kubectl apply -f "manifests/${IMAGE_NAME}service.yaml"
- kubectl get all
# environment:
# name: test
# url: https://example.com
# kubernetes:
# namespace: test
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "develop" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH)'
when: manual
- if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "develop"'
when: manual
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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
# General settings
LOG_LEVEL = logging.DEBUG
# service settings
MONITORING_INTERVAL = 10 # monitoring interval in seconds
# Prometheus settings
METRICS_PORT = 9192
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FROM python:3.9-slim
# Install dependencies
RUN apt-get --yes --quiet --quiet update && \
apt-get --yes --quiet --quiet install wget g++ nano && \
rm -rf /var/lib/apt/lists/*
# TODO: remove nano from installation
# Set Python to show logs as they occur
ENV PYTHONUNBUFFERED=0
ENV PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
# Download the gRPC health probe
RUN GRPC_HEALTH_PROBE_VERSION=v0.2.0 && \
wget -qO/bin/grpc_health_probe https://github.com/grpc-ecosystem/grpc-health-probe/releases/download/${GRPC_HEALTH_PROBE_VERSION}/grpc_health_probe-linux-amd64 && \
chmod +x /bin/grpc_health_probe
# Creating a user for security reasons
RUN groupadd -r teraflow && useradd -u 1001 --no-log-init -r -m -g teraflow teraflow
USER teraflow
# set working directory
RUN mkdir -p /home/teraflow/controller/common/
WORKDIR /home/teraflow/controller
# Get Python packages per module
ENV VIRTUAL_ENV=/home/teraflow/venv
RUN python3 -m venv ${VIRTUAL_ENV}
ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"
# Get generic Python packages
RUN python3 -m pip install --upgrade pip
RUN python3 -m pip install --upgrade setuptools wheel
RUN python3 -m pip install --upgrade pip-tools
# Get common Python packages
# Note: this step enables sharing the previous Docker build steps among all the Python components
COPY --chown=teraflow:teraflow common_requirements.in common_requirements.in
COPY --chown=teraflow:teraflow src/opticalattackmanager/requirements.in opticalattackmanager/requirements.in
RUN sed -i '/protobuf/d' common_requirements.in && sed -i '/grpc/d' common_requirements.in
RUN pip-compile --output-file=common_requirements.txt common_requirements.in opticalattackmanager/requirements.in
RUN python3 -m pip install -r common_requirements.txt
# Get Python packages per module
# COPY --chown=opticalattackmanager:opticalattackmanager src/opticalattackmanager/requirements.in opticalattackmanager/requirements.in
# RUN pip-compile --quiet --output-file=opticalattackmanager/requirements.txt opticalattackmanager/requirements.in
# RUN python3 -m pip install -r opticalattackmanager/requirements.txt
# Add common files into working directory
WORKDIR /home/teraflow/controller/common
COPY --chown=teraflow:teraflow src/common/. ./
# Create proto sub-folder, copy .proto files, and generate Python code
WORKDIR /home/teraflow/controller/common/proto
RUN touch __init__.py
RUN mkdir -p /home/teraflow/controller/common/proto/asyncio
RUN touch asyncio/__init__.py
COPY --chown=teraflow:teraflow proto/*.proto ./
RUN python3 -m grpc_tools.protoc -I=. --python_out=. --grpc_python_out=. *.proto
# new line added to generate protobuf for the `grpclib` library
RUN python3 -m grpc_tools.protoc -I=./ --python_out=./asyncio --grpclib_python_out=./asyncio *.proto
RUN rm *.proto
RUN find . -type f -exec sed -i -E 's/(import\ .*)_pb2/from . \1_pb2/g' {} \;
# Create module sub-folders
RUN mkdir -p /home/teraflow/controller/opticalattackmanager
WORKDIR /home/teraflow/controller
# Add files into working directory
COPY --chown=teraflow:teraflow src/context/. context
COPY --chown=teraflow:teraflow src/monitoring/. monitoring
COPY --chown=teraflow:teraflow src/dbscanserving/. dbscanserving
COPY --chown=teraflow:teraflow src/opticalattackdetector/. opticalattackdetector
COPY --chown=teraflow:teraflow src/opticalattackmitigator/. opticalattackmitigator
COPY --chown=teraflow:teraflow src/opticalattackmanager/. opticalattackmanager
# Start opticalattackmanager service
ENTRYPOINT ["python", "-m", "opticalattackmanager.service"]
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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.
grpcio==1.49.*
grpcio-health-checking==1.49.*
grpcio-tools==1.49.*
grpclib[protobuf]
redis
\ No newline at end of file
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
This diff is collapsed.
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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 os
from unittest.mock import patch
import pytest
from common.Constants import (DEFAULT_GRPC_GRACE_PERIOD,
DEFAULT_GRPC_MAX_WORKERS,
DEFAULT_SERVICE_GRPC_PORTS, ServiceNameEnum)
from common.proto import dbscanserving_pb2 as dbscan
from common.proto.optical_attack_detector_pb2 import DetectionRequest
from opticalattackdetector.client.OpticalAttackDetectorClient import \
OpticalAttackDetectorClient
from opticalattackdetector.Config import GRPC_SERVICE_PORT
from opticalattackdetector.service.OpticalAttackDetectorService import \
OpticalAttackDetectorService
# from .example_objects import CONTEXT_ID, CONTEXT_ID_2, SERVICE_DEV1_DEV2
port = 10000 + GRPC_SERVICE_PORT # avoid privileged ports
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
@pytest.fixture(scope="session")
def optical_attack_detector_service():
with patch.dict(
os.environ,
{
"OPTICALATTACKDETECTORSERVICE_SERVICE_HOST": "127.0.0.1",
"OPTICALATTACKDETECTORSERVICE_SERVICE_PORT_GRPC": str(
1000
+ DEFAULT_SERVICE_GRPC_PORTS.get(
ServiceNameEnum.OPTICALATTACKDETECTOR.value
)
),
"OPTICALATTACKMITIGATORSERVICE_SERVICE_HOST": "127.0.0.1",
"OPTICALATTACKMITIGATORSERVICE_SERVICE_PORT_GRPC": str(
1000
+ DEFAULT_SERVICE_GRPC_PORTS.get(
ServiceNameEnum.OPTICALATTACKMITIGATOR.value
)
),
"DBSCANSERVINGSERVICE_SERVICE_HOST": "127.0.0.1",
"DBSCANSERVINGSERVICE_SERVICE_PORT_GRPC": str(
1000
+ DEFAULT_SERVICE_GRPC_PORTS.get(ServiceNameEnum.DBSCANSERVING.value)
),
},
clear=True,
):
_service = OpticalAttackDetectorService(
port=port,
max_workers=DEFAULT_GRPC_MAX_WORKERS,
grace_period=DEFAULT_GRPC_GRACE_PERIOD,
)
# mocker_context_client = mock.patch('opticalattackdetector.service.OpticalAttackDetectorServiceServicerImpl.context_client')
# mocker_context_client.start()
# mocker_influx_db = mock.patch('opticalattackdetector.service.OpticalAttackDetectorServiceServicerImpl.influxdb_client')
# mocker_influx_db.start()
_service.start()
yield _service
_service.stop()
# mocker_context_client.stop()
# mocker_influx_db.stop()
@pytest.fixture(scope="session")
def optical_attack_detector_client(optical_attack_detector_service):
with patch.dict(
os.environ,
{
"OPTICALATTACKDETECTORSERVICE_SERVICE_HOST": "127.0.0.1",
"OPTICALATTACKDETECTORSERVICE_SERVICE_PORT_GRPC": str(
1000
+ DEFAULT_SERVICE_GRPC_PORTS.get(
ServiceNameEnum.OPTICALATTACKDETECTOR.value
)
),
"OPTICALATTACKMITIGATORSERVICE_SERVICE_HOST": "127.0.0.1",
"OPTICALATTACKMITIGATORSERVICE_SERVICE_PORT_GRPC": str(
1000
+ DEFAULT_SERVICE_GRPC_PORTS.get(
ServiceNameEnum.OPTICALATTACKMITIGATOR.value
)
),
"DBSCANSERVINGSERVICE_SERVICE_HOST": "127.0.0.1",
"DBSCANSERVINGSERVICE_SERVICE_PORT_GRPC": str(
1000
+ DEFAULT_SERVICE_GRPC_PORTS.get(ServiceNameEnum.DBSCANSERVING.value)
),
},
clear=True,
):
_client = OpticalAttackDetectorClient()
yield _client
_client.close()
def test_detect_attack(
optical_attack_detector_client: OpticalAttackDetectorClient,
):
LOGGER.info("placeholder")
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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 queue
import threading
import grpc
from common.proto.context_pb2 import Empty
from common.tools.grpc.Tools import grpc_message_to_json_string
from context.client.ContextClient import ContextClient
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)
class EventsCollector:
def __init__(
self, context_client_grpc: ContextClient, log_events_received=False
) -> None:
self._events_queue = queue.Queue()
self._log_events_received = log_events_received
self._service_stream = context_client_grpc.GetServiceEvents(Empty())
self._service_thread = threading.Thread(
target=self._collect, args=(self._service_stream,), daemon=False
)
def _collect(self, events_stream) -> None:
try:
for event in events_stream:
if self._log_events_received:
LOGGER.info(
"[_collect] event: {:s}".format(
grpc_message_to_json_string(event)
)
)
self._events_queue.put_nowait(event)
except grpc.RpcError as e:
if e.code() != grpc.StatusCode.CANCELLED: # pylint: disable=no-member
raise # pragma: no cover
def start(self):
self._service_thread.start()
def get_event(self, block: bool = True, timeout: float = 0.1):
try:
return self._events_queue.get(block=block, timeout=timeout)
except queue.Empty: # pylint: disable=catching-non-exception
return None
def get_events(self, block: bool = True, timeout: float = 0.1, count: int = None):
events = []
if count is None:
while True:
event = self.get_event(block=block, timeout=timeout)
if event is None:
break
events.append(event)
else:
for _ in range(count):
event = self.get_event(block=block, timeout=timeout)
if event is None:
continue
events.append(event)
return sorted(events, key=lambda e: e.event.timestamp.timestamp)
def stop(self):
self._service_stream.cancel()
self._service_thread.join()
# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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 time
from typing import List
from grpclib.client import Channel
from prometheus_client import Counter
from common.proto.asyncio.optical_attack_detector_grpc import \
OpticalAttackDetectorServiceStub
from common.proto.asyncio.optical_attack_detector_pb2 import DetectionRequest
from common.Settings import get_log_level, get_setting
DROP_COUNTER = Counter(
"optical_security_dropped_assessments",
"Dropped assessments due to detector timeout",
)
log_level = get_log_level()
logging.basicConfig(level=log_level)
LOGGER = logging.getLogger(__name__)
async def detect_attack(
host: str,
port: int,
context_id: str,
service_id: str,
kpi_id: str,
timeout: float = 20.0,
) -> None:
try:
LOGGER.debug("Sending request for {}...".format(service_id))
async with Channel(host, port) as channel:
stub = OpticalAttackDetectorServiceStub(channel)
request: DetectionRequest = DetectionRequest()
request.service_id.context_id.context_uuid.uuid = context_id
request.service_id.service_uuid.uuid = str(service_id)
request.kpi_id.kpi_id.uuid = kpi_id
await stub.DetectAttack(request, timeout=timeout)
LOGGER.debug("Monitoring finished for {}/{}".format(service_id, kpi_id))
except Exception as e:
LOGGER.warning(
"Exception while processing service_id {}/{}".format(service_id, kpi_id)
)
LOGGER.exception(e)
DROP_COUNTER.inc()
......@@ -32,7 +32,7 @@ RUN groupadd -r teraflow && useradd -u 1001 --no-log-init -r -m -g teraflow tera
USER teraflow
# set working directory
RUN mkdir -p /home/teraflow/controller/common/proto
RUN mkdir -p /home/teraflow/controller/common/
WORKDIR /home/teraflow/controller
# Get Python packages per module
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment