Skip to content
Snippets Groups Projects
Commit fc59f26b authored by famelis's avatar famelis
Browse files

backup

parent f1931d1c
No related branches found
No related tags found
2 merge requests!235Release TeraFlowSDN 3.0,!164Merge 3rd hackfest material to develop
Showing
with 1577 additions and 10 deletions
......@@ -29,7 +29,7 @@ export TFS_COMPONENTS="${TFS_COMPONENTS} monitoring"
export TFS_COMPONENTS="${TFS_COMPONENTS} policy"
# Uncomment to activate Automation Manager
export TFS_COMPONENTS="${TFS_COMPONENTS} automation"
#export TFS_COMPONENTS="${TFS_COMPONENTS} automation"
# Uncomment to activate Optical CyberSecurity
#export TFS_COMPONENTS="${TFS_COMPONENTS} dbscanserving opticalattackmitigator opticalattackdetector opticalattackmanager"
......
......@@ -198,7 +198,9 @@ public class PolicyServiceImpl implements PolicyService {
return policyRuleState;
}
contextService.setPolicyRule(policyRule).subscribe().with(x -> {});
LOGGER.infof("THIS IS A TEST! 1");
setPolicyRuleServiceToContext(policyRuleService, VALIDATED_POLICYRULE_STATE);
LOGGER.infof("THIS IS A TEST! 2");
noAlarms = 0;
// Create an alarmIds list that contains the promised ids returned from setKpiAlarm
......@@ -208,7 +210,8 @@ public class PolicyServiceImpl implements PolicyService {
LOGGER.infof(alarmDescriptor.toString());
alarmIds.add(monitoringService.setKpiAlarm(alarmDescriptor));
}
LOGGER.infof("THIS IS A TEST!");
LOGGER.infof("%s", alarmIds);
// Transform the alarmIds into promised alarms returned from the
// getAlarmResponseStream
List<Multi<AlarmResponse>> alarmResponseStreamList = new ArrayList<>();
......@@ -725,7 +728,8 @@ public class PolicyServiceImpl implements PolicyService {
// TODO: Temp fix for AlarmDescriptor object
AlarmDescriptor alarmDescriptor =
new AlarmDescriptor(
"alarmId-" + gen(),
//"alarmId-" + gen(),
null,
"alarmDescription",
"alarmName-" + gen(),
policyRuleCondition.getKpiId(),
......@@ -770,6 +774,7 @@ public class PolicyServiceImpl implements PolicyService {
final var kpiValueRange = convertPolicyRuleConditionToKpiValueRange(policyRuleCondition);
return new AlarmDescriptor(
//"alarmId-" + gen(),
"alarmId-" + gen(),
"alarmDescription",
"alarmName-" + gen(),
......@@ -800,6 +805,7 @@ public class PolicyServiceImpl implements PolicyService {
}
return new AlarmDescriptor(
//"alarmId-" + gen(),
"alarmId-" + gen(),
"alarmDescription",
"alarmName-" + gen(),
......
......@@ -23,6 +23,9 @@ quarkus:
context:
host: ${quarkus.kubernetes.env.vars.context-service-host}
port: 1010
context_policy:
host: ${quarkus.kubernetes.env.vars.context-service-host}
port: 1010
monitoring:
host: ${quarkus.kubernetes.env.vars.monitoring-service-host}
port: 7070
......@@ -60,11 +63,11 @@ quarkus:
context-service-host: "contextservice"
monitoring-service-host: "monitoringservice"
service-service-host: "serviceservice"
resources:
requests:
cpu: 50m
memory: 512Mi
limits:
cpu: 500m
memory: 2048Mi
# resources:
# requests:
# cpu: 50m
# memory: 512Mi
# limits:
# cpu: 500m
# memory: 2048Mi
# Tests for P4 functionality of TeraFlowSDN
This directory contains the necessary scripts and configurations to run tests for the P4 functionality of TFS.
## Basic scripts
To run the experiments you should use the five scripts in the following order:
```
setup.sh
run_test_01_bootstrap.sh
run_test_02_create_service.sh
run_test_03_delete_service.sh
run_test_04_cleanup.sh
```
The setup script copies the necessary artifacts to the SBI service pod. It should be run just once, after a fresh install of TFS.
The bootstrap script registers the context, topology, links and, devices to TFS.
The create service scripts establishes a service between two endpoints.
The delete service script delete the aforementioned service.
Cleanup script deletes all the objects (context, topology, links, devices) from TFS.
## Objects file
The above bash scripts make use of the corresponding python scripts found under `./tests/` directory.
More important is the `./tests/Objects.py` file, which contains the definition of the Context, Topology, Devices, Links, Services. **This is the file that need changes in case of a new topology.**
Check the `./tests/Objects.py` file before running the experiment to make sure that the switches details are correct (ip address, port, etc.)
## Mininet topologies
In the `./mininet/` directory there are different mininet topology examples. The current `./tests/Objects.py` file corresponds to the `./mininet/4switch2path.py` topology. For more topologies please refer to `../p4`.
## P4 artifacts
In the `./p4/` directory there are the compiled p4 artifacts that contain the pipeline that will be pushed to the p4 switch, along with the p4-runtime definitions.
The `./setup.sh` script copies from this directory. So if you need to change p4 program, make sure to put the compiled artifacts here.
## Latency probe
In the `./probe/` directory there is a little program which calculates latency between two hosts in mininet and sends them to the Monitoring component. For specific instructions, refer to the corresponding `./probe/README.md` file.
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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.
#!/bin/bash
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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.
# ----- TeraFlowSDN ------------------------------------------------------------
# Set the URL of the internal MicroK8s Docker registry where the images will be uploaded to.
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 pathcomp service slice compute webui load_generator"
# Uncomment to activate Monitoring
export TFS_COMPONENTS="${TFS_COMPONENTS} monitoring"
# Uncomment to activate Policy Manager
export TFS_COMPONENTS="${TFS_COMPONENTS} policy"
# Uncomment to activate Automation Manager
export TFS_COMPONENTS="${TFS_COMPONENTS} automation"
# Uncomment to activate Optical CyberSecurity
#export TFS_COMPONENTS="${TFS_COMPONENTS} dbscanserving opticalattackmitigator opticalattackdetector opticalattackmanager"
# Uncomment to activate L3 CyberSecurity
#export TFS_COMPONENTS="${TFS_COMPONENTS} l3_attackmitigator l3_centralizedattackdetector"
# Uncomment to activate TE
#export TFS_COMPONENTS="${TFS_COMPONENTS} te"
# Set the tag you want to use for your images.
export TFS_IMAGE_TAG="dev"
# Set the name of the Kubernetes namespace to deploy TFS to.
export TFS_K8S_NAMESPACE="tfs"
# Set additional manifest files to be applied after the deployment
export TFS_EXTRA_MANIFESTS="manifests/nginx_ingress_http.yaml"
# Uncomment to monitor performance of components
export TFS_EXTRA_MANIFESTS="${TFS_EXTRA_MANIFESTS} manifests/servicemonitors.yaml"
# Uncomment when deploying Optical CyberSecurity
#export TFS_EXTRA_MANIFESTS="${TFS_EXTRA_MANIFESTS} manifests/cachingservice.yaml"
# Set the new Grafana admin password
export TFS_GRAFANA_PASSWORD="admin123+"
# Disable skip-build flag to rebuild the Docker images.
export TFS_SKIP_BUILD=""
# ----- CockroachDB ------------------------------------------------------------
# Set the namespace where CockroackDB will be deployed.
export CRDB_NAMESPACE="crdb"
# Set the external port CockroackDB Postgre SQL interface will be exposed to.
export CRDB_EXT_PORT_SQL="26257"
# Set the external port CockroackDB HTTP Mgmt GUI interface will be exposed to.
export CRDB_EXT_PORT_HTTP="8081"
# Set the database username to be used by Context.
export CRDB_USERNAME="tfs"
# Set the database user's password to be used by Context.
export CRDB_PASSWORD="tfs123"
# Set the database name to be used by Context.
export CRDB_DATABASE="tfs"
# Set CockroachDB installation mode to 'single'. This option is convenient for development and testing.
# See ./deploy/all.sh or ./deploy/crdb.sh for additional details
export CRDB_DEPLOY_MODE="single"
# Disable flag for dropping database, if it exists.
export CRDB_DROP_DATABASE_IF_EXISTS="YES"
# Disable flag for re-deploying CockroachDB from scratch.
export CRDB_REDEPLOY="YES"
# ----- NATS -------------------------------------------------------------------
# Set the namespace where NATS will be deployed.
export NATS_NAMESPACE="nats"
# Set the external port NATS Client interface will be exposed to.
export NATS_EXT_PORT_CLIENT="4222"
# Set the external port NATS HTTP Mgmt GUI interface will be exposed to.
export NATS_EXT_PORT_HTTP="8222"
# Disable flag for re-deploying NATS from scratch.
export NATS_REDEPLOY="YES"
# ----- QuestDB ----------------------------------------------------------------
# Set the namespace where QuestDB will be deployed.
export QDB_NAMESPACE="qdb"
# Set the external port QuestDB Postgre SQL interface will be exposed to.
export QDB_EXT_PORT_SQL="8812"
# Set the external port QuestDB Influx Line Protocol interface will be exposed to.
export QDB_EXT_PORT_ILP="9009"
# Set the external port QuestDB HTTP Mgmt GUI interface will be exposed to.
export QDB_EXT_PORT_HTTP="9000"
# Set the database username to be used for QuestDB.
export QDB_USERNAME="admin"
# Set the database user's password to be used for QuestDB.
export QDB_PASSWORD="quest"
# Set the table name to be used by Monitoring for KPIs.
export QDB_TABLE_MONITORING_KPIS="tfs_monitoring_kpis"
# Set the table name to be used by Slice for plotting groups.
export QDB_TABLE_SLICE_GROUPS="tfs_slice_groups"
# Disable flag for dropping tables if they exist.
export QDB_DROP_TABLES_IF_EXIST=""
# Disable flag for re-deploying QuestDB from scratch.
export QDB_REDEPLOY="YES"
# ----- K8s Observability ------------------------------------------------------
# Set the external port Prometheus Mgmt HTTP GUI interface will be exposed to.
export PROM_EXT_PORT_HTTP="9090"
# Set the external port Grafana HTTP Dashboards will be exposed to.
export GRAF_EXT_PORT_HTTP="3000"
#!/usr/bin/python
# Copyright 2019-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.net import Mininet
from mininet.node import Host
from mininet.topo import Topo
from stratum import StratumBmv2Switch
CPU_PORT = 255
class IPv4Host(Host):
"""Host that can be configured with an IPv4 gateway (default route).
"""
def config(self, mac=None, ip=None, defaultRoute=None, lo='up', gw=None,
**_params):
super(IPv4Host, self).config(mac, ip, defaultRoute, lo, **_params)
self.cmd('ip -4 addr flush dev %s' % self.defaultIntf())
self.cmd('ip -6 addr flush dev %s' % self.defaultIntf())
self.cmd('ip -4 link set up %s' % self.defaultIntf())
self.cmd('ip -4 addr add %s dev %s' % (ip, self.defaultIntf()))
if gw:
self.cmd('ip -4 route add default via %s' % gw)
# Disable offload
for attr in ["rx", "tx", "sg"]:
cmd = "/sbin/ethtool --offload %s %s off" % (
self.defaultIntf(), attr)
self.cmd(cmd)
def updateIP():
return ip.split('/')[0]
self.defaultIntf().updateIP = updateIP
class TutorialTopo(Topo):
"""Basic Server-Client topology with IPv4 hosts"""
def __init__(self, *args, **kwargs):
Topo.__init__(self, *args, **kwargs)
# Switches
# gRPC port 50001
switch1 = self.addSwitch('switch1', cls=StratumBmv2Switch, cpuport=CPU_PORT)
# gRPC port 50002
switch2 = self.addSwitch('switch2', cls=StratumBmv2Switch, cpuport=CPU_PORT)
# gRPC port 50003
switch3 = self.addSwitch('switch3', cls=StratumBmv2Switch, cpuport=CPU_PORT)
# gRPC port 50004
switch4 = self.addSwitch('switch4', cls=StratumBmv2Switch, cpuport=CPU_PORT)
# Hosts
client = self.addHost('client', cls=IPv4Host, mac="aa:bb:cc:dd:ee:11",
ip='10.0.0.1/24', gw='10.0.0.100')
server = self.addHost('server', cls=IPv4Host, mac="aa:bb:cc:dd:ee:22",
ip='10.0.0.2/24', gw='10.0.0.100')
# Switch links
self.addLink(switch1, switch2) # Switch1:port 1, Switch2:port 1
self.addLink(switch1, switch3) # Switch1:port 2, Switch3:port 1
self.addLink(switch2, switch4) # Switch2:port 2, Switch4:port 1
self.addLink(switch3, switch4) # Switch3:port 2, Switch4:port 2
# Host links
self.addLink(client, switch1) # Switch 1: port 3
self.addLink(server, switch4) # Switch 4: port 3
def main():
net = Mininet(topo=TutorialTopo(), controller=None)
net.start()
client = net.hosts[0]
client.setARP('10.0.0.2', 'aa:bb:cc:dd:ee:22')
server = net.hosts[1]
server.setARP('10.0.0.1', 'aa:bb:cc:dd:ee:11')
CLI(net)
net.stop()
print '#' * 80
print 'ATTENTION: Mininet was stopped! Perhaps accidentally?'
print 'No worries, it will restart automatically in a few seconds...'
print 'To access again the Mininet CLI, use `make mn-cli`'
print 'To detach from the CLI (without stopping), press Ctrl-D'
print 'To permanently quit Mininet, use `make stop`'
print '#' * 80
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Mininet topology script for 2x2 fabric with stratum_bmv2 and IPv4 hosts')
args = parser.parse_args()
setLogLevel('info')
main()
{
"header_types" : [
{
"name" : "scalars_0",
"id" : 0,
"fields" : [
["local_metadata_t.is_multicast", 1, false],
["_padding_0", 7, false]
]
},
{
"name" : "standard_metadata",
"id" : 1,
"fields" : [
["ingress_port", 9, false],
["egress_spec", 9, false],
["egress_port", 9, false],
["clone_spec", 32, false],
["instance_type", 32, false],
["drop", 1, false],
["recirculate_port", 16, false],
["packet_length", 32, false],
["enq_timestamp", 32, false],
["enq_qdepth", 19, false],
["deq_timedelta", 32, false],
["deq_qdepth", 19, false],
["ingress_global_timestamp", 48, false],
["egress_global_timestamp", 48, false],
["lf_field_list", 32, false],
["mcast_grp", 16, false],
["resubmit_flag", 32, false],
["egress_rid", 16, false],
["recirculate_flag", 32, false],
["checksum_error", 1, false],
["parser_error", 32, false],
["priority", 3, false],
["_padding", 2, false]
]
},
{
"name" : "ethernet_t",
"id" : 2,
"fields" : [
["dst_addr", 48, false],
["src_addr", 48, false],
["ether_type", 16, false]
]
}
],
"headers" : [
{
"name" : "scalars",
"id" : 0,
"header_type" : "scalars_0",
"metadata" : true,
"pi_omit" : true
},
{
"name" : "standard_metadata",
"id" : 1,
"header_type" : "standard_metadata",
"metadata" : true,
"pi_omit" : true
},
{
"name" : "ethernet",
"id" : 2,
"header_type" : "ethernet_t",
"metadata" : false,
"pi_omit" : true
}
],
"header_stacks" : [],
"header_union_types" : [],
"header_unions" : [],
"header_union_stacks" : [],
"field_lists" : [],
"errors" : [
["NoError", 1],
["PacketTooShort", 2],
["NoMatch", 3],
["StackOutOfBounds", 4],
["HeaderTooShort", 5],
["ParserTimeout", 6],
["ParserInvalidArgument", 7]
],
"enums" : [],
"parsers" : [
{
"name" : "parser",
"id" : 0,
"init_state" : "start",
"parse_states" : [
{
"name" : "start",
"id" : 0,
"parser_ops" : [
{
"parameters" : [
{
"type" : "regular",
"value" : "ethernet"
}
],
"op" : "extract"
}
],
"transitions" : [
{
"value" : "default",
"mask" : null,
"next_state" : null
}
],
"transition_key" : []
}
]
}
],
"parse_vsets" : [],
"deparsers" : [
{
"name" : "deparser",
"id" : 0,
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 130,
"column" : 8,
"source_fragment" : "DeparserImpl"
},
"order" : ["ethernet"]
}
],
"meter_arrays" : [],
"counter_arrays" : [],
"register_arrays" : [],
"calculations" : [],
"learn_lists" : [],
"actions" : [
{
"name" : "IngressPipeImpl.drop",
"id" : 0,
"runtime_data" : [],
"primitives" : [
{
"op" : "mark_to_drop",
"parameters" : [
{
"type" : "header",
"value" : "standard_metadata"
}
],
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 77,
"column" : 8,
"source_fragment" : "mark_to_drop(standard_metadata)"
}
}
]
},
{
"name" : "IngressPipeImpl.set_egress_port",
"id" : 1,
"runtime_data" : [
{
"name" : "port",
"bitwidth" : 9
}
],
"primitives" : [
{
"op" : "assign",
"parameters" : [
{
"type" : "field",
"value" : ["standard_metadata", "egress_spec"]
},
{
"type" : "runtime_data",
"value" : 0
}
],
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 81,
"column" : 8,
"source_fragment" : "standard_metadata.egress_spec = port"
}
}
]
},
{
"name" : "IngressPipeImpl.set_multicast_group",
"id" : 2,
"runtime_data" : [
{
"name" : "gid",
"bitwidth" : 16
}
],
"primitives" : [
{
"op" : "assign",
"parameters" : [
{
"type" : "field",
"value" : ["standard_metadata", "mcast_grp"]
},
{
"type" : "runtime_data",
"value" : 0
}
],
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 89,
"column" : 8,
"source_fragment" : "standard_metadata.mcast_grp = gid"
}
},
{
"op" : "assign",
"parameters" : [
{
"type" : "field",
"value" : ["scalars", "local_metadata_t.is_multicast"]
},
{
"type" : "expression",
"value" : {
"type" : "expression",
"value" : {
"op" : "b2d",
"left" : null,
"right" : {
"type" : "bool",
"value" : true
}
}
}
}
],
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 90,
"column" : 8,
"source_fragment" : "local_metadata.is_multicast = true"
}
}
]
}
],
"pipelines" : [
{
"name" : "ingress",
"id" : 0,
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 71,
"column" : 8,
"source_fragment" : "IngressPipeImpl"
},
"init_table" : "IngressPipeImpl.l2_exact_table",
"tables" : [
{
"name" : "IngressPipeImpl.l2_exact_table",
"id" : 0,
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 95,
"column" : 10,
"source_fragment" : "l2_exact_table"
},
"key" : [
{
"match_type" : "exact",
"name" : "standard_metadata.ingress_port",
"target" : ["standard_metadata", "ingress_port"],
"mask" : null
}
],
"match_type" : "exact",
"type" : "simple",
"max_size" : 1024,
"with_counters" : false,
"support_timeout" : false,
"direct_meters" : null,
"action_ids" : [1, 2, 0],
"actions" : ["IngressPipeImpl.set_egress_port", "IngressPipeImpl.set_multicast_group", "IngressPipeImpl.drop"],
"base_default_next" : null,
"next_tables" : {
"IngressPipeImpl.set_egress_port" : null,
"IngressPipeImpl.set_multicast_group" : null,
"IngressPipeImpl.drop" : null
},
"default_entry" : {
"action_id" : 0,
"action_const" : true,
"action_data" : [],
"action_entry_const" : true
}
}
],
"action_profiles" : [],
"conditionals" : []
},
{
"name" : "egress",
"id" : 1,
"source_info" : {
"filename" : "p4src/main.p4",
"line" : 116,
"column" : 8,
"source_fragment" : "EgressPipeImpl"
},
"init_table" : null,
"tables" : [],
"action_profiles" : [],
"conditionals" : []
}
],
"checksums" : [],
"force_arith" : [],
"extern_instances" : [],
"field_aliases" : [
[
"queueing_metadata.enq_timestamp",
["standard_metadata", "enq_timestamp"]
],
[
"queueing_metadata.enq_qdepth",
["standard_metadata", "enq_qdepth"]
],
[
"queueing_metadata.deq_timedelta",
["standard_metadata", "deq_timedelta"]
],
[
"queueing_metadata.deq_qdepth",
["standard_metadata", "deq_qdepth"]
],
[
"intrinsic_metadata.ingress_global_timestamp",
["standard_metadata", "ingress_global_timestamp"]
],
[
"intrinsic_metadata.egress_global_timestamp",
["standard_metadata", "egress_global_timestamp"]
],
[
"intrinsic_metadata.lf_field_list",
["standard_metadata", "lf_field_list"]
],
[
"intrinsic_metadata.mcast_grp",
["standard_metadata", "mcast_grp"]
],
[
"intrinsic_metadata.resubmit_flag",
["standard_metadata", "resubmit_flag"]
],
[
"intrinsic_metadata.egress_rid",
["standard_metadata", "egress_rid"]
],
[
"intrinsic_metadata.recirculate_flag",
["standard_metadata", "recirculate_flag"]
],
[
"intrinsic_metadata.priority",
["standard_metadata", "priority"]
]
],
"program" : "p4src/main.p4",
"__meta__" : {
"version" : [2, 18],
"compiler" : "https://github.com/p4lang/p4c"
}
}
\ No newline at end of file
/*
* Copyright 2019-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core.p4>
#include <v1model.p4>
typedef bit<9> port_num_t;
typedef bit<48> mac_addr_t;
typedef bit<16> mcast_group_id_t;
//------------------------------------------------------------------------------
// HEADER DEFINITIONS
//------------------------------------------------------------------------------
header ethernet_t {
mac_addr_t dst_addr;
mac_addr_t src_addr;
bit<16> ether_type;
}
struct parsed_headers_t {
ethernet_t ethernet;
}
struct local_metadata_t {
bool is_multicast;
}
//------------------------------------------------------------------------------
// INGRESS PIPELINE
//------------------------------------------------------------------------------
parser ParserImpl (packet_in packet,
out parsed_headers_t hdr,
inout local_metadata_t local_metadata,
inout standard_metadata_t standard_metadata)
{
state start {
transition parse_ethernet;
}
state parse_ethernet {
packet.extract(hdr.ethernet);
transition accept;
}
}
control VerifyChecksumImpl(inout parsed_headers_t hdr,
inout local_metadata_t meta)
{
apply { /* EMPTY */ }
}
control IngressPipeImpl (inout parsed_headers_t hdr,
inout local_metadata_t local_metadata,
inout standard_metadata_t standard_metadata) {
// Drop action shared by many tables.
action drop() {
mark_to_drop(standard_metadata);
}
action set_egress_port(port_num_t port) {
standard_metadata.egress_spec = port;
}
action set_multicast_group(mcast_group_id_t gid) {
// gid will be used by the Packet Replication Engine (PRE) in the
// Traffic Manager--located right after the ingress pipeline, to
// replicate a packet to multiple egress ports, specified by the control
// plane by means of P4Runtime MulticastGroupEntry messages.
standard_metadata.mcast_grp = gid;
local_metadata.is_multicast = true;
}
// --- l2_exact_table ------------------
table l2_exact_table {
key = {
standard_metadata.ingress_port: exact;
}
actions = {
set_egress_port;
set_multicast_group;
@defaultonly drop;
}
const default_action = drop;
}
apply {
l2_exact_table.apply();
}
}
//------------------------------------------------------------------------------
// EGRESS PIPELINE
//------------------------------------------------------------------------------
control EgressPipeImpl (inout parsed_headers_t hdr,
inout local_metadata_t local_metadata,
inout standard_metadata_t standard_metadata) {
apply { /* EMPTY */ }
}
control ComputeChecksumImpl(inout parsed_headers_t hdr,
inout local_metadata_t local_metadata)
{
apply { /* EMPTY */ }
}
control DeparserImpl(packet_out packet, in parsed_headers_t hdr) {
apply {
packet.emit(hdr.ethernet);
}
}
V1Switch(
ParserImpl(),
VerifyChecksumImpl(),
IngressPipeImpl(),
EgressPipeImpl(),
ComputeChecksumImpl(),
DeparserImpl()
) main;
pkg_info {
arch: "v1model"
}
tables {
preamble {
id: 33605373
name: "IngressPipeImpl.l2_exact_table"
alias: "l2_exact_table"
}
match_fields {
id: 1
name: "standard_metadata.ingress_port"
bitwidth: 9
match_type: EXACT
}
action_refs {
id: 16812802
}
action_refs {
id: 16841371
}
action_refs {
id: 16796182
annotations: "@defaultonly"
scope: DEFAULT_ONLY
}
const_default_action_id: 16796182
size: 1024
}
actions {
preamble {
id: 16796182
name: "IngressPipeImpl.drop"
alias: "drop"
}
}
actions {
preamble {
id: 16812802
name: "IngressPipeImpl.set_egress_port"
alias: "set_egress_port"
}
params {
id: 1
name: "port"
bitwidth: 9
}
}
actions {
preamble {
id: 16841371
name: "IngressPipeImpl.set_multicast_group"
alias: "set_multicast_group"
}
params {
id: 1
name: "gid"
bitwidth: 16
}
}
type_info {
}
# Probe for P4 mininet devices
Step 1:
To copy the necessary files, run:
```
probe-tfs/deploy.sh
```
Step 2:
To connect to the mininet docker, run:
```
probe-tfs/connect-to-mininet.sh
```
Step 3:
From inside the mininet docker, run:
```
./tfsagent
```
Step 4 (on another terminal):
Establish the service:
```
src/tests/p4/run_test_02_create_service.sh
```
Step 5:
From inside mininet (make mn-cli):
```
client ./tfsping
```
Step 6 (on another terminal):
To check the latest monitoring samples, run
```
python src/tests/p4/probe/monitoring_kpis.py
```
%% Cell type:markdown id: tags:
# Checking the monitoring component
%% Cell type:code id: tags:
``` python
import time
import datetime
import uuid
import random
from dotenv import load_dotenv
from IPython.display import clear_output, display, HTML
from common.tools.timestamp.Converters import timestamp_utcnow_to_float, timestamp_float_to_string
from common.tools.grpc.Tools import grpc_message_to_json_string
from common.proto.kpi_sample_types_pb2 import KpiSampleType
from common.proto.monitoring_pb2 import KpiDescriptor, KpiId, KpiQuery, Kpi
from monitoring.client.MonitoringClient import MonitoringClient
```
%% Cell type:code id: tags:
``` python
load_dotenv()
monitoring_client = MonitoringClient()
uuid.uuid4().hex
```
%% Output
'0abfb00117d4461b9fa5085bee4be58f'
%% Cell type:code id: tags:
``` python
kpi_description: KpiDescriptor = KpiDescriptor()
kpi_description.kpi_description = "Security status of service {}".format(uuid.uuid4().hex)
kpi_description.service_id.service_uuid.uuid = "608df176-90b8-5950-b50d-1810c6eaaa5d"
kpi_description.kpi_sample_type = KpiSampleType.KPISAMPLETYPE_UNKNOWN
new_kpi = monitoring_client.SetKpi(kpi_description)
print("Created KPI {}: ".format(grpc_message_to_json_string(new_kpi)))
```
%% Output
Created KPI {"kpi_id": {"uuid": "1"}}:
%% Cell type:code id: tags:
``` python
kpi_id = input("What is the KPI ID?")
query = KpiQuery()
query.kpi_ids.append(KpiId(**{"kpi_id": {"uuid": kpi_id}}))
query.last_n_samples = 10
while True:
kpi = Kpi()
kpi.kpi_id.kpi_id.uuid = new_kpi.kpi_id.uuid
kpi.timestamp.timestamp = timestamp_utcnow_to_float()
kpi.kpi_value.int32Val = random.randint(10, 4000)
# monitoring_client.IncludeKpi(kpi)
response = monitoring_client.QueryKpiData(query)
# print(response)
table = f"""<table>
<thead>
<tr><th colspan=3>{datetime.datetime.now()}</th></tr>
<tr><th>KPI ID</th><th>Timestamp</th><th>Value</th></tr>
<thead>
<tbody>"""
for kpi in response.raw_kpi_lists:
cur_kpi_id = kpi.kpi_id.kpi_id.uuid
for i, raw_kpi in enumerate(kpi.raw_kpis):
# print(cur_kpi_id, raw_kpi.timestamp.timestamp, raw_kpi.kpi_value)
table += "<tr><td>{} - {}</td><td>{}</td><td>{}</td></tr>".format(
i, cur_kpi_id, timestamp_float_to_string(raw_kpi.timestamp.timestamp), raw_kpi.kpi_value
)
table += "</tbody></table>"
display(HTML(table))
time.sleep(5)
clear_output(wait=True)
```
%% Output
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
Cell In [4], line 31
29 table += "</tbody></table>"
30 display(HTML(table))
---> 31 time.sleep(5)
32 clear_output(wait=True)
KeyboardInterrupt:
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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.
# File to monitor the latest *n* samples from the KPI ID *id*
# and updates it every *i* seconds
#
# Author: Carlos Natalino <carlos.natalino@chalmers.se>
import argparse
import datetime
import time
from common.proto.kpi_sample_types_pb2 import KpiSampleType
from common.proto.monitoring_pb2 import KpiDescriptor, KpiId, KpiQuery
from common.tools.grpc.Tools import grpc_message_to_json_string
from common.tools.timestamp.Converters import timestamp_float_to_string
from monitoring.client.MonitoringClient import MonitoringClient
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-n",
"--last-n-samples",
default=10,
type=int,
help="Number of latest samples of the KPI to show.",
)
parser.add_argument(
"-s",
"--sleep",
default=5,
type=int,
help="Seconds between consecutive refreshes.",
)
parser.add_argument("-id", "--kpi-id", help="KPI ID, if known.")
args = parser.parse_args()
monitoring_client = MonitoringClient()
if args.kpi_id is None:
service_uuid = "608df176-90b8-5950-b50d-1810c6eaaa5d"
kpi_description: KpiDescriptor = KpiDescriptor()
kpi_description.kpi_description = "Security status of service {}".format(
service_uuid
)
kpi_description.service_id.service_uuid.uuid = service_uuid
kpi_description.kpi_sample_type = KpiSampleType.KPISAMPLETYPE_UNKNOWN
new_kpi = monitoring_client.SetKpi(kpi_description)
print("Created KPI {}: ".format(grpc_message_to_json_string(new_kpi)))
kpi_id = new_kpi.kpi_id.uuid
else:
kpi_id = args.kpi_id
query = KpiQuery()
query.kpi_ids.append(KpiId(**{"kpi_id": {"uuid": kpi_id}}))
query.last_n_samples = args.last_n_samples
while True:
print(chr(27) + "[2J")
response = monitoring_client.QueryKpiData(query)
print("{}\t{}\t{:<20}\t{}".format("Index", "KPI ID", "Timestamp", "Value"))
for kpi in response.raw_kpi_lists:
cur_kpi_id = kpi.kpi_id.kpi_id.uuid
for i, raw_kpi in enumerate(kpi.raw_kpis):
print(
"{}\t{}\t{}\t{}".format(
i,
cur_kpi_id,
timestamp_float_to_string(raw_kpi.timestamp.timestamp),
raw_kpi.kpi_value.floatVal,
)
)
print("Last update:", datetime.datetime.now().strftime("%H:%M:%S"))
time.sleep(args.sleep)
# Generated by Cargo
# will have compiled files and executables
/target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
# Added by cargo
/target
.env_bkp
.env
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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.
[package]
name = "rust-tfs"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
dotenv = "0.15.0"
futures = "0.3.26"
prost = "0.11.6"
surge-ping = "0.7.3"
tokio = { version = "1.25", features = ["macros", "rt-multi-thread"] }
tonic = "0.8.3"
[[bin]]
name = "tfsping"
path = "src/ping.rs"
[[bin]]
name = "tfsagent"
path = "src/agent.rs"
[build-dependencies]
tonic-build = "0.8.3"
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
# rust-tfs
Client for TFS functionalities written in Rust.
/**
* Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
*
* 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 script that generates Rust code for the protobuffers.
*
* Author: Carlos Natalino <carlos.natalino@chalmers.se>
*/
fn main() {
tonic_build::configure()
.build_server(false)
.compile(
&[
"proto/context.proto",
"proto/acl.proto",
"proto/kpi_sample_types.proto",
"proto/monitoring.proto",
],
&["proto"],
)
.unwrap_or_else(|e| panic!("Failed to compile protos {:?}", e));
}
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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.
CONTAINER=`docker ps | grep mininet | cut -f1 -d" "`
docker exec -it $CONTAINER /bin/bash
# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# 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 the software
# uncomment the line below if you want to build it
# cargo build --release --target=x86_64-unknown-linux-musl
# build a .env file with the info from context and monitoring services
if [ -z "${CONTEXTSERVICE_SERVICE_HOST}" ] || [ -z "${CONTEXTSERVICE_SERVICE_PORT_GRPC}" ] || \
[ -z "${MONITORINGSERVICE_SERVICE_HOST}" ] || [ -z "${MONITORINGSERVICE_SERVICE_PORT_GRPC}" ]
then
echo "TFS_ENV_VARS are not loaded."
exit 1
fi
echo "CONTEXTSERVICE_SERVICE_HOST=${CONTEXTSERVICE_SERVICE_HOST}" > .env
echo "CONTEXTSERVICE_SERVICE_PORT_GRPC=${CONTEXTSERVICE_SERVICE_PORT_GRPC}" >> .env
echo "MONITORINGSERVICE_SERVICE_HOST=${MONITORINGSERVICE_SERVICE_HOST}" >> .env
echo "MONITORINGSERVICE_SERVICE_PORT_GRPC=${MONITORINGSERVICE_SERVICE_PORT_GRPC}" >> .env
# get container id
CONTAINER=`docker ps | grep mininet | cut -f1 -d" "`
docker cp target/x86_64-unknown-linux-musl/release/tfsping $CONTAINER:/root
docker cp target/x86_64-unknown-linux-musl/release/tfsagent $CONTAINER:/root
docker cp .env $CONTAINER:/root
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