Commit 629e05d1 authored by garciadav's avatar garciadav
Browse files

Merge branch 'add-oai-charms' into 'master'

Add OAI charms

See merge request !188
parents e5490ca8 99df54fa
Pipeline #5246 failed with stage
in 1 minute and 52 seconds
.vscode
oai.zip
logs/
*.charm
build/
\ No newline at end of file
# OPENAIR-CN-5G: An implementation of the 5G Core network by the OpenAirInterface community.
This bundle deploys the OPENAIR-CN-5G charm operators.
## Deployment
```bash
juju add-model oai
juju deploy ch:oai --channel edge --trust
```
Verify the deployment has been successfully deployed:
```bash
$ juju status
Model Controller Cloud/Region Version SLA Timestamp
oa osm-vca microk8s/localhost 2.9.9 unsupported 14:59:42+02:00
App Version Status Scale Charm Store Channel Rev OS Address Message
amf active 1 oai-amf charmhub edge 2 kubernetes 10.152.183.250
db active 1 oai-db charmhub edge 2 kubernetes 10.152.183.21
gnb active 1 oai-gnb charmhub edge 2 kubernetes 10.152.183.108
nr-ue active 1 oai-nr-ue charmhub edge 2 kubernetes 10.152.183.16
nrf active 1 oai-nrf charmhub edge 2 kubernetes 10.152.183.105
smf active 1 oai-smf charmhub edge 2 kubernetes 10.152.183.73
spgwu-tiny active 1 oai-spgwu-tiny charmhub edge 2 kubernetes 10.152.183.243
Unit Workload Agent Address Ports Message
amf/0* active idle 10.1.245.70
db/0* active idle 10.1.245.109
gnb/0* active idle 10.1.245.85 registered
nr-ue/0* active idle 10.1.245.107 registered
nrf/0* active idle 10.1.245.80
smf/0* active idle 10.1.245.125
spgwu-tiny/0* active idle 10.1.245.118
```
## Test network connectivity from UE
```bash
$ kubectl -n oai exec -it nr-ue-0 -c nr-ue -- ping -I oaitun_ue1 google.fr -c 1
PING google.fr (142.250.201.67) from 12.1.1.129 oaitun_ue1: 56(84) bytes of data.
64 bytes from mad07s25-in-f3.1e100.net (142.250.201.67): icmp_seq=1 ttl=115 time=23.2 ms
--- google.fr ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 23.250/23.250/23.250/0.000 ms
```
## Scale the GNB
```bash
juju scale-application gnb 3
```
## Start and stop UE
Stop:
```bash
$ juju run-action nr-ue/0 stop --wait
unit-nr-ue-0:
UnitId: nr-ue/0
id: "2"
results:
output: service has been stopped successfully
status: completed
timing:
completed: 2021-09-28 13:02:34 +0000 UTC
enqueued: 2021-09-28 13:02:29 +0000 UTC
started: 2021-09-28 13:02:32 +0000 UTC
$ kubectl -n oai exec -it nr-ue-0 -c nr-ue -- ping -I oaitun_ue1 google.fr -c 1
ping: SO_BINDTODEVICE: Invalid argument
command terminated with exit code 2
```
Start:
```bash
$ juju run-action nr-ue/0 start --wait
unit-nr-ue-0:
UnitId: nr-ue/0
id: "4"
results:
output: service has been started successfully
status: completed
timing:
completed: 2021-09-28 13:03:38 +0000 UTC
enqueued: 2021-09-28 13:03:32 +0000 UTC
started: 2021-09-28 13:03:36 +0000 UTC
$ kubectl -n oai exec -it nr-ue-0 -c nr-ue -- ping -I oaitun_ue1 google.fr -c 1
PING google.fr (142.250.185.3) from 12.1.1.130 oaitun_ue1: 56(84) bytes of data.
64 bytes from mad41s11-in-f3.1e100.net (142.250.185.3): icmp_seq=1 ttl=115 time=25.2 ms
--- google.fr ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 25.205/25.205/25.205/0.000 ms
```
# Reference links
- https://gitlab.eurecom.fr/oai/cn5g/oai-cn5g-fed
#!/bin/bash
function build() {
charm=$1
cd oai-$charm-operator/
# charmcraft clean
charmcraft build
mv oai-${charm}_ubuntu-20.04-amd64.charm $charm.charm
cd ..
}
charms="nrf amf smf spgwu-tiny db gnb nr-ue"
for charm in $charms; do
build $charm &
done
wait
bundle: kubernetes
name: oai
applications:
db:
charm: ch:oai-db
scale: 1
channel: edge
trust: true
nrf:
charm: ch:oai-nrf
scale: 1
channel: edge
trust: true
options:
start-tcpdump: false
amf:
charm: ch:oai-amf
trust: true
options:
start-tcpdump: false
scale: 1
channel: edge
smf:
charm: ch:oai-smf
scale: 1
channel: edge
trust: true
options:
start-tcpdump: false
spgwu-tiny:
charm: ch:oai-spgwu-tiny
scale: 1
channel: edge
trust: true
options:
start-tcpdump: false
gnb:
charm: ch:oai-gnb
scale: 1
channel: edge
trust: true
nr-ue:
charm: ch:oai-nr-ue
scale: 1
channel: edge
trust: true
relations:
- - db:db
- amf:db
- - nrf:nrf
- amf:nrf
- - nrf:nrf
- smf:nrf
- - smf:amf
- amf:amf
- - nrf:nrf
- spgwu-tiny:nrf
- - spgwu-tiny:smf
- smf:smf
- - gnb:amf
- amf:amf
- - spgwu-tiny:spgwu
- gnb:spgwu
- - nr-ue:gnb
- gnb:gnb
#!/bin/bash
juju deploy ./bundle.yaml --trust
\ No newline at end of file
[flake8]
max-line-length = 99
select: E,W,F,C,N
exclude:
venv
.git
build
dist
*.egg_info
venv/
build/
*.charm
.coverage
__pycache__/
*.py[cod]
/venv
*.py[cod]
*.charm
# oai-amf
## Developing
Create and activate a virtualenv with the development requirements:
virtualenv -p python3 venv
source venv/bin/activate
pip install -r requirements-dev.txt
## Code overview
TEMPLATE-TODO:
One of the most important things a consumer of your charm (or library)
needs to know is what set of functionality it provides. Which categories
does it fit into? Which events do you listen to? Which libraries do you
consume? Which ones do you export and how are they used?
## Intended use case
TEMPLATE-TODO:
Why were these decisions made? What's the scope of your charm?
## Roadmap
If this Charm doesn't fulfill all of the initial functionality you were
hoping for or planning on, please add a Roadmap or TODO here
## Testing
The Python operator framework includes a very nice harness for testing
operator behaviour without full deployment. Just `run_tests`:
./run_tests
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.
# Learn more about charmcraft.yaml configuration at:
# https://juju.is/docs/sdk/charmcraft-config
type: "charm"
bases:
- build-on:
- name: "ubuntu"
channel: "20.04"
run-on:
- name: "ubuntu"
channel: "20.04"
# Copyright 2021 David Garcia
# See LICENSE file for licensing details.
#
# Learn more about config at: https://juju.is/docs/sdk/config
options:
start-tcpdump:
default: False
description: |
start tcpdump collection to analyse but beware
it will take a lot of space in the container/persistent volume.
type: boolean
# Copyright 2021 David Garcia
# See LICENSE file for licensing details.
# For a complete list of supported options, see:
# https://discourse.charmhub.io/t/charm-metadata-v2/3674/15
name: oai-amf
display-name: OAI amf
description: OAI amf
summary: OAI amf
containers:
amf:
resource: oai-amf-image
tcpdump:
resource: tcpdump-image
resources:
oai-amf-image:
type: oci-image
description: OCI image for oai-amf (rdefosseoai/oai-amf:v1.1.0)
tcpdump-image:
type: oci-image
description: OCI image for tcpdump (corfr/tcpdump:latest)
requires:
nrf:
interface: nrf
db:
interface: mysql
provides:
amf:
interface: amf
-r requirements.txt
coverage
flake8
#!/bin/sh -e
# Copyright 2021 David Garcia
# See LICENSE file for licensing details.
if [ -z "$VIRTUAL_ENV" -a -d venv/ ]; then
. venv/bin/activate
fi
if [ -z "$PYTHONPATH" ]; then
export PYTHONPATH="lib:src"
else
export PYTHONPATH="lib:src:$PYTHONPATH"
fi
flake8
coverage run --branch --source=src -m unittest -v "$@"
coverage report -m
#!/usr/bin/env python3
# Copyright 2021 David Garcia
# See LICENSE file for licensing details.
#
# Learn more at: https://juju.is/docs/sdk
"""Charm the service.
Refer to the following post for a quick-start guide that will help you
develop a new k8s charm using the Operator Framework:
https://discourse.charmhub.io/t/4208
"""
import logging
import time
from ops.main import main
from ops.model import ActiveStatus, BlockedStatus, WaitingStatus
from ops.pebble import ConnectionError
from utils import OaiCharm
logger = logging.getLogger(__name__)
SCTP_PORT = 38412
HTTP1_PORT = 80
HTTP2_PORT = 9090
class OaiAmfCharm(OaiCharm):
"""Charm the service."""
def __init__(self, *args):
super().__init__(
*args,
tcpdump=True,
ports=[
("oai-amf", SCTP_PORT, SCTP_PORT, "SCTP"),
("http1", HTTP1_PORT, HTTP1_PORT, "TCP"),
("http2", HTTP2_PORT, HTTP2_PORT, "TCP"),
],
privileged=True,
container_name="amf",
service_name="oai_amf",
)
# Observe charm events
event_observer_mapping = {
self.on.amf_pebble_ready: self._on_oai_amf_pebble_ready,
# self.on.stop: self._on_stop,
self.on.config_changed: self._on_config_changed,
self.on.amf_relation_joined: self._on_amf_relation_joined,
self.on.amf_relation_changed: self._on_amf_relation_changed,
self.on.nrf_relation_changed: self._update_service,
self.on.nrf_relation_broken: self._update_service,
self.on.db_relation_changed: self._update_service,
self.on.db_relation_broken: self._update_service,
}
for event, observer in event_observer_mapping.items():
self.framework.observe(event, observer)
# Set defaults in Stored State for the relation data
self._stored.set_default(
nrf_host=None,
nrf_port=None,
nrf_api_version=None,
db_host=None,
db_port=None,
db_user=None,
db_password=None,
db_database=None,
)
####################################
# Charm events handlers
####################################
def _on_oai_amf_pebble_ready(self, event):
try:
container = event.workload
self._add_oai_amf_layer(container)
self._update_service(event)
except ConnectionError:
logger.info("pebble socket not available, deferring config-changed")
event.defer()
# def _on_stop(self, event):
# if self.unit.is_leader():
# self._clear_service_info()
def _on_config_changed(self, event):
self.update_tcpdump_service(event)
def _on_amf_relation_joined(self, event):
try:
if self.unit.is_leader() and self.is_service_running():
self._provide_service_info()
except ConnectionError:
logger.info("pebble socket not available, deferring config-changed")
event.defer()
def _on_amf_relation_changed(self, event):
if event.unit in event.relation.data and all(
key in event.relation.data[event.unit] for key in ("gnb-name", "gnb-status")
):
gnb_name = event.relation.data[event.unit]["gnb-name"]
gnb_status = event.relation.data[event.unit]["gnb-status"]
if gnb_status == "started":
self._wait_gnb_is_registered(gnb_name)
event.relation.data[self.app][gnb_name] = "registered"
if event.app in event.relation.data and all(
key in event.relation.data[event.app] for key in ("ue-imsi", "ue-status")
):
ue_imsi = event.relation.data[event.app]["ue-imsi"]
ue_status = event.relation.data[event.app]["ue-status"]
if ue_status == "started":
self._wait_ue_is_registered(ue_imsi)
event.relation.data[self.app][ue_imsi] = "registered"
def _update_service(self, event):
try:
logger.info("Updating service...")
if not self.service_exists():
logger.warning("service does not exist")
return
# Load data from dependent relations
self._load_nrf_data()
self._load_db_data()
relations_ready = self.is_nrf_ready and self.is_db_ready
if not relations_ready:
self.unit.status = BlockedStatus("need nrf and db relations")
if self.is_service_running():
self.stop_service()
elif not self.is_service_running():
self._configure_service()
self.start_service()
self._wait_until_service_is_active()
if self.unit.is_leader():
self._provide_service_info()
except ConnectionError:
logger.info("pebble socket not available, deferring config-changed")
event.defer()
####################################
# Utils - Services and configuration
####################################
def _provide_service_info(self):
if pod_ip := self.pod_ip:
for relation in self.framework.model.relations["amf"]:
logger.debug(f"Found relation {relation.name} with id {relation.id}")
relation.data[self.app]["host"] = self.app.name
relation.data[self.app]["ip-address"] = str(pod_ip)
relation.data[self.app]["port"] = str(HTTP1_PORT)
relation.data[self.app]["api-version"] = "v1"
logger.info(
f"Info provided in relation {relation.name} (id {relation.id})"
)
def _clear_service_info(self):
for relation in self.framework.model.relations["amf"]:
logger.debug(f"Found relation {relation.name} with id {relation.id}")
relation.data[self.app]["host"] = ""
relation.data[self.app]["ip-address"] = ""
relation.data[self.app]["port"] = ""
relation.data[self.app]["api-version"] = ""
logger.info(f"Info cleared in relation {relation.name} (id {relation.id})")
def _wait_gnb_is_registered(self, gnb_name):
self.unit.status = WaitingStatus(f"waiting for gnb {gnb_name} to be registered")
self.search_logs(subsets_in_line={"Connected", gnb_name}, wait=True)
self.unit.status = ActiveStatus()
def _wait_ue_is_registered(self, ue_imsi):
self.unit.status = WaitingStatus(f"waiting for ue {ue_imsi} to be registered")
self.search_logs(subsets_in_line={"5GMM-REGISTERED", ue_imsi}, wait=True)
self.unit.status = ActiveStatus()
def _wait_until_service_is_active(self):
logger.debug("Waiting for service to be active...")
self.unit.status = WaitingStatus("Waiting for service to be active...")
active = self.search_logs(
{
"amf_n2 started",
"amf_n11 started",
"Initiating all registered modules",
"-----gNBs' information----",
},
wait=True,
)
if active:
# wait extra time
time.sleep(10)
self.unit.status = ActiveStatus()
else:
self.unit.status = BlockedStatus("service couldn't start")
@property
def is_nrf_ready(self):
is_ready = (
self._stored.nrf_host
and self._stored.nrf_port
and self._stored.nrf_api_version
)
logger.info(f'nrf is{" " if is_ready else " not "}ready')
return is_ready
def _load_nrf_data(self):
logger.debug("Loading nrf data from relation")
relation = self.framework.model.get_relation("nrf")
if relation and relation.app in relation.data:
relation_data = relation.data[relation.app]
self._stored.nrf_host = relation_data.get("host")
self._stored.nrf_port = relation_data.get("port")
self._stored.nrf_api_version = relation_data.get("api-version")
logger.info("nrf data loaded")
else:
self._stored.nrf_host = None
self._stored.nrf_port = None
self._stored.nrf_api_version = None
logger.warning("no relation found")
@property
def is_db_ready(self):
is_ready = (
self._stored.db_host
and self._stored.db_port
and self._stored.db_user
and self._stored.db_password
and self._stored.db_database
)
logger.info(f'db is{" " if is_ready else " not "}ready')
return is_ready
def _load_db_data(self):
logger.debug("Loading db data from relation")
relation = self.framework.model.get_relation("db")
if relation and relation.app in relation.data:
relation_data = relation.data[relation.app]
self._stored.db_host = relation_data.get("host")
self._stored.db_port = relation_data.get("port")
self._stored.db_user = relation_data.get("user")
self._stored.db_password = relation_data.get("password")
self._stored.db_database = relation_data.get("database")
logger.info("db data loaded")
else:
self._stored.db_host = None
self._stored.db_port = None
self._stored.db_user = None
self._stored.db_password = None
self._stored.db_database = None
logger.warning("no relation found")
def _configure_service(self):
if not self.service_exists():
logger.debug("Cannot configure service: service does not exist yet")
return
logger.debug("Configuring amf service")
container = self.unit.get_container("amf")
container.add_layer(
"oai_amf",
{
"services": {
"oai_amf": {
"override": "merge",
"environment": {
"NRF_FQDN": self._stored.nrf_host,
"NRF_IPV4_ADDRESS": "0.0.0.0",
"NRF_PORT": self._stored.nrf_port,
"NRF_API_VERSION": self._stored.nrf_api_version,
"MYSQL_SERVER": f"{self._stored.db_host}",
"MYSQL_USER": self._stored.db_user,
"MYSQL_PASS": self._stored.db_password,
"MYSQL_DB": self._stored.db_database,
},
}
},
},
combine=True,
)
logger.info("amf service configured")
def _add_oai_amf_layer(self, container):
entrypoint = "/bin/bash /openair-amf/bin/entrypoint.sh"
command = " ".join(
["/openair-amf/bin/oai_amf", "-c", "/openair-amf/etc/amf.conf", "-o"]
)
pebble_layer = {
"summary": "oai_amf layer",
"description": "pebble config layer for oai_amf",
"services": {
"oai_amf": {
"override": "replace",
"summary": "oai_amf",
"command": f"{entrypoint} {command}",
"environment": {
"DEBIAN_FRONTEND": "noninteractive",
"TZ": "Europe/Paris",
"INSTANCE": "0",
"PID_DIRECTORY": "/var/run",
"MCC": "208",
"MNC": "95",
"REGION_ID": "128",
"AMF_SET_ID": "1",
"SERVED_GUAMI_MCC_0": "208",
"SERVED_GUAMI_MNC_0": "95",
"SERVED_GUAMI_REGION_ID_0": "128",
"SERVED_GUAMI_AMF_SET_ID_0": "1",
"SERVED_GUAMI_MCC_1": "460",
"SERVED_GUAMI_MNC_1": "11",
"SERVED_GUAMI_REGION_ID_1": "10",
"SERVED_GUAMI_AMF_SET_ID_1": "1",
"PLMN_SUPPORT_MCC": "208",
"PLMN_SUPPORT_MNC": "95",
"PLMN_SUPPORT_TAC": "0x0001",
"SST_0": "1",
"SD_0": "1",
"SST_1": "111",
"SD_1": "124",
"AMF_INTERFACE_NAME_FOR_NGAP": "eth0",
"AMF_INTERFACE_NAME_FOR_N11": "eth0",
"SMF_INSTANCE_ID_0": "1",
"SMF_IPV4_ADDR_0": "0.0.0.0",
"SMF_HTTP_VERSION_0": "v1",
"SMF_FQDN_0": "localhost",
"SMF_INSTANCE_ID_1": "2",
"SMF_IPV4_ADDR_1": "0.0.0.0",
"SMF_HTTP_VERSION_1": "v1",
"SMF_FQDN_1": "localhost",
"AUSF_IPV4_ADDRESS": "127.0.0.1",
"AUSF_PORT": 80,
"AUSF_API_VERSION": "v1",
"NF_REGISTRATION": "yes",
"SMF_SELECTION": "yes",
"USE_FQDN_DNS": "yes",
"OPERATOR_KEY": "63bfa50ee6523365ff14c1f45f88737d",
},
}
},
}
container.add_layer("oai_amf", pebble_layer, combine=True)
logger.info("oai_amf layer added")
if __name__ == "__main__":
main(OaiAmfCharm, use_juju_for_storage=True)
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
import os
import time
from typing import List, Set, Tuple, Optional
import kubernetes
from ops.charm import CharmBase
from ops.model import MaintenanceStatus
from ops.pebble import ConnectionError
from ops.framework import StoredState
from ipaddress import IPv4Address
import subprocess
class PatchFailed(RuntimeError):
"""Patching the kubernetes service failed."""
class K8sServicePatch:
"""A utility for patching the Kubernetes service set up by Juju.
Attributes:
namespace_file (str): path to the k8s namespace file in the charm container
"""
namespace_file = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
@staticmethod
def namespace() -> str:
"""Read the Kubernetes namespace we're deployed in from the mounted service token.
Returns:
str: The current Kubernetes namespace
"""
with open(K8sServicePatch.namespace_file, "r") as f:
return f.read().strip()
@staticmethod
def _k8s_service(
app: str, service_ports: List[Tuple[str, int, int, str]]
) -> kubernetes.client.V1Service:
"""Property accessor to return a valid Kubernetes Service representation for Alertmanager.
Args:
app: app name
service_ports: a list of tuples (name, port, target_port) for every service port.
Returns:
kubernetes.client.V1Service: A Kubernetes Service with correctly annotated metadata and
ports.
"""
ports = [
kubernetes.client.V1ServicePort(
name=port[0], port=port[1], target_port=port[2], protocol=port[3]
)
for port in service_ports
]
ns = K8sServicePatch.namespace()
return kubernetes.client.V1Service(
api_version="v1",
metadata=kubernetes.client.V1ObjectMeta(
namespace=ns,
name=app,
labels={"app.kubernetes.io/name": app},
),
spec=kubernetes.client.V1ServiceSpec(
ports=ports,
selector={"app.kubernetes.io/name": app},
),
)
@staticmethod
def set_ports(app: str, service_ports: List[Tuple[str, int, int, str]]):
"""Patch the Kubernetes service created by Juju to map the correct port.
Currently, Juju uses port 65535 for all endpoints. This can be observed via:
kubectl describe services -n <model_name> | grep Port -C 2
At runtime, pebble watches which ports are bound and we need to patch the gap for pebble
not telling Juju to fix the K8S Service definition.
Typical usage example from within charm code (e.g. on_install):
service_ports = [("my-app-api", 9093, 9093), ("my-app-ha", 9094, 9094)]
K8sServicePatch.set_ports(self.app.name, service_ports)
Args:
app: app name
service_ports: a list of tuples (name, port, target_port) for every service port.
Raises:
PatchFailed: if patching fails.
"""
# First ensure we're authenticated with the Kubernetes API
ns = K8sServicePatch.namespace()
# Set up a Kubernetes client
api = kubernetes.client.CoreV1Api(kubernetes.client.ApiClient())
try:
# Delete the existing service so we can redefine with correct ports
# I don't think you can issue a patch that *replaces* the existing ports,
# only append
api.delete_namespaced_service(name=app, namespace=ns)
# Recreate the service with the correct ports for the application
api.create_namespaced_service(
namespace=ns, body=K8sServicePatch._k8s_service(app, service_ports)
)
except kubernetes.client.exceptions.ApiException as e:
raise PatchFailed("Failed to patch k8s service: {}".format(e))
logger = logging.getLogger(__name__)
class OaiCharm(CharmBase):
"""Oai Base Charm."""
_stored = StoredState()
def __init__(
self,
*args,
tcpdump: bool = False,
ports=None,
privileged: bool = False,
container_name=None,
service_name,
):
super().__init__(*args)
self.ports = ports
self.privileged = privileged
self.container_name = container_name
self.service_name = service_name
event_mapping = {
self.on.install: self._on_install,
}
if tcpdump:
event_mapping[self.on.tcpdump_pebble_ready] = self._on_tcpdump_pebble_ready
for event, observer in event_mapping.items():
self.framework.observe(event, observer)
self._stored.set_default(
_k8s_stateful_patched=False,
_k8s_authed=False,
)
def _on_install(self, _=None):
if not self._stored._k8s_authed:
kubernetes.config.load_incluster_config()
self._stored._k8s_authed = True
if not self._stored._k8s_authed:
kubernetes.config.load_incluster_config()
self._stored._k8s_authed = True
if self.privileged:
self._patch_stateful_set()
K8sServicePatch.set_ports(self.app.name, self.ports)
def _on_tcpdump_pebble_ready(self, event):
self.update_tcpdump_service(event)
def update_tcpdump_service(self, event):
try:
self._configure_tcpdump_service()
if (
self.config["start-tcpdump"]
and self.service_exists("tcpdump", "tcpdump")
and not self.is_service_running("tcpdump", "tcpdump")
):
self.start_service("tcpdump", "tcpdump")
elif (
not self.config["start-tcpdump"]
and self.service_exists("tcpdump", "tcpdump")
and self.is_service_running("tcpdump", "tcpdump")
):
self.stop_service("tcpdump", "tcpdump")
except ConnectionError:
logger.info("pebble socket not available, deferring config-changed")
event.defer()
def _configure_tcpdump_service(self):
container = self.unit.get_container("tcpdump")
container.add_layer(
"tcpdump",
{
"summary": "tcpdump layer",
"description": "pebble config layer for tcpdump",
"services": {
"tcpdump": {
"override": "replace",
"summary": "tcpdump",
"command": f"/usr/sbin/tcpdump -i any -w /pcap_{self.app.name}.pcap",
"environment": {
"DEBIAN_FRONTEND": "noninteractive",
"TZ": "Europe/Paris",
},
}
},
},
combine=True,
)
def start_service(self, container_name=None, service_name=None):
if not container_name:
container_name = self.container_name
if not service_name:
service_name = self.service_name
container = self.unit.get_container(container_name)
logger.info(f"{container.get_plan()}")
container.start(service_name)
def stop_service(self, container_name=None, service_name=None):
if not container_name:
container_name = self.container_name
if not service_name:
service_name = self.service_name
container = self.unit.get_container(container_name)
container.stop(service_name)
def is_service_running(self, container_name=None, service_name=None):
if not container_name:
container_name = self.container_name
if not service_name:
service_name = self.service_name
container = self.unit.get_container(container_name)
is_running = (
service_name in container.get_plan().services
and container.get_service(service_name).is_running()
)
logger.info(f"container {self.container_name} is running: {is_running}")
return is_running
def service_exists(self, container_name=None, service_name=None):
if not container_name:
container_name = self.container_name
if not service_name:
service_name = self.service_name
container = self.unit.get_container(container_name)
service_exists = service_name in container.get_plan().services
logger.info(f"service {service_name} exists: {service_exists}")
return service_exists
def _patch_stateful_set(self) -> None:
"""Patch the StatefulSet to include specific ServiceAccount and Secret mounts"""
if self._stored._k8s_stateful_patched:
return
# Get an API client
api = kubernetes.client.AppsV1Api(kubernetes.client.ApiClient())
for attempt in range(5):
try:
self.unit.status = MaintenanceStatus(
f"patching StatefulSet for additional k8s permissions. Attempt {attempt+1}/5"
)
s = api.read_namespaced_stateful_set(
name=self.app.name, namespace=self.namespace
)
# Add the required security context to the container spec
s.spec.template.spec.containers[1].security_context.privileged = True
# Patch the StatefulSet with our modified object
api.patch_namespaced_stateful_set(
name=self.app.name, namespace=self.namespace, body=s
)
logger.info(
"Patched StatefulSet to include additional volumes and mounts"
)
self._stored._k8s_stateful_patched = True
return
except Exception as e:
self.unit.status = MaintenanceStatus(
"failed patching StatefulSet... Retrying in 10 seconds"
)
time.sleep(5)
@property
def namespace(self) -> str:
with open("/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r") as f:
return f.read().strip()
@property
def pod_ip(self) -> Optional[IPv4Address]:
return IPv4Address(
subprocess.check_output(["unit-get", "private-address"]).decode().strip()
)
def search_logs(
self, logs: Set[str] = {}, subsets_in_line: Set[str] = {}, wait: bool = False
) -> bool:
"""
Search list of logs in the container and service
:param: logs: List of logs to be found
:param: wait: Bool to wait until those logs are found
"""
if logs and subsets_in_line:
raise Exception("logs and subsets_in_line cannot both be defined")
elif not logs and not subsets_in_line:
raise Exception("logs or subsets_in_line must be defined")
found_logs = set()
os.environ[
"PEBBLE_SOCKET"
] = f"/charm/containers/{self.container_name}/pebble.socket"
p = subprocess.Popen(
f'/charm/bin/pebble logs {self.service_name} {"-f" if wait else ""} -n all',
stdout=subprocess.PIPE,
shell=True,
encoding="utf-8",
)
all_logs_found = False
for line in p.stdout:
if logs:
for log in logs:
if log in line:
found_logs.add(log)
logger.info(f"{log} log found")
break
if all(log in found_logs for log in logs):
all_logs_found = True
logger.info("all logs found")
break
else:
if all(subset in line for subset in subsets_in_line):
all_logs_found = True
logger.info("subset of strings found")
break
p.kill()
return all_logs_found
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment