From 4b4f5b15f37275b2a52966a92573c6eef45475f8 Mon Sep 17 00:00:00 2001
From: David Garcia <david.garcia@canonical.com>
Date: Fri, 29 May 2020 11:02:36 +0200
Subject: [PATCH] Add actions to enodeB

---
 .gitignore                                    |  3 +
 .../charms/enodeb/actions.yaml                | 17 ++---
 .../charms/enodeb/src/charm.py                | 68 +++++++++++++++----
 .../magma-agw-enb_vnfd.yaml                   |  5 ++
 4 files changed, 69 insertions(+), 24 deletions(-)

diff --git a/.gitignore b/.gitignore
index dc24ba1f..f1a98d03 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,6 +43,9 @@ checksums.txt
 .pydevproject
 .settings
 
+#vscode
+.vscode
+
 #local stuff files that end in ".local" or "tmp" or folders called "local" or "tmp"
 *.local
 *.tmp
diff --git a/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/actions.yaml b/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/actions.yaml
index 25cea587..4f34831a 100644
--- a/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/actions.yaml
+++ b/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/actions.yaml
@@ -17,15 +17,8 @@ register:
     - mme-addr
     - gtp-bind-addr
     - s1c-bind-addr
-kill-pid:
-  description: "Kill PID."
-  params:
-    pid:
-      description: "PID."
-      type: string
-      default: ""
-  required:
-    - pid
+unregister:
+  description: "Unregister from AGW."
 attach-ue:
   description: Attach User Emulator to enodeB
   params:
@@ -44,4 +37,8 @@ attach-ue:
   required:
     - usim-imsi
     - usim-k
-    - usim-opc
\ No newline at end of file
+    - usim-opc
+detach-ue:
+  description: "Detach from AGW."
+remove-default-gw:
+  description: "Remove default gateway"
\ No newline at end of file
diff --git a/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/src/charm.py b/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/src/charm.py
index 69b74cd6..15eb976d 100755
--- a/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/src/charm.py
+++ b/magma/hackfest_magma-agw-enb_vnfd/charms/enodeb/src/charm.py
@@ -13,6 +13,7 @@
 #     See the License for the specific language governing permissions and
 #     limitations under the License.
 import sys
+
 sys.path.append("lib")
 from ops.charm import CharmBase
 from ops.framework import StoredState
@@ -34,6 +35,7 @@ logger = logging.getLogger(__name__)
 
 class EnodebCharm(CharmBase):
     state = StoredState()
+
     def __init__(self, *args):
         super().__init__(*args)
         # An example of setting charm state
@@ -49,17 +51,22 @@ class EnodebCharm(CharmBase):
             self.on.upgrade_charm,
             self.on.register_action,
             self.on.attach_ue_action,
-            self.on.kill_pid_action,
+            self.on.unregister_action,
+            self.on.detach_ue_action,
+            self.on.remove_default_gw,
         ):
             self.framework.observe(event, self)
+
     def on_config_changed(self, event):
         """Handle changes in configuration"""
         unit = self.model.unit
+
     def on_install(self, event):
         """Called when the charm is being installed"""
         unit = self.model.unit
         # Install your software and its dependencies
         unit.status = ActiveStatus()
+
     def on_upgrade_charm(self, event):
         """Upgrade the charm."""
         unit = self.model.unit
@@ -68,6 +75,7 @@ class EnodebCharm(CharmBase):
         self.on_install(event)
         # When maintenance is done, return to an Active state
         unit.status = ActiveStatus()
+
     def on_register_action(self, event):
         """Register to AGW (EPC)."""
         try:
@@ -89,7 +97,7 @@ class EnodebCharm(CharmBase):
                     "--enb_files.drb_config=/configzmq/drb.conf",
                     "/configzmq/enb.conf",
                     "--rf.device_name=zmq",
-                    "--rf.device_args='fail_on_disconnect=true,tx_port=tcp://*:2000,rx_port=tcp://localhost:2001,id=enb,base_srate=23.04e6'"
+                    "--rf.device_args='fail_on_disconnect=true,tx_port=tcp://*:2000,rx_port=tcp://localhost:2001,id=enb,base_srate=23.04e6'",
                 ]
             )
             logger.debug("Register action: executing")
@@ -104,24 +112,24 @@ class EnodebCharm(CharmBase):
             event.fail("Timeout error")
         except Exception as e:
             event.fail(e)
-    def on_kill_pid_action(self, event):
-        """Kill PID"""
+
+    def on_unregister_action(self, event):
+        """Unregister action"""
         try:
-            pid = event.params["pid"]
-            command = "kill -9 {}".format(pid)
-            subprocess.check_output(command, shell=True)
+            command = "sudo killall -s KILL srsenb"
+            output = subprocess.check_output(command, shell=True)
             event.set_results(
-                {"status": "ok", "pid": pid, "message": "PID {} killed".format(pid)}
+                {
+                    "status": "ok",
+                    "message": "Unregistered successfully",
+                    "output": output,
+                }
             )
         except subprocess.CalledProcessError as e:
             event.fail("Command error: {}".format(e.output))
         except Exception as e:
             event.fail(e)
 
-    def _run_daemon(self, cmd, stdout_file):
-        with open(stdout_file, "wb") as f:
-            return subprocess.Popen(cmd, shell=True, stdout=f)
-
     def on_attach_ue_action(self, event):
         """Attach User Emulator to EnodeB."""
         try:
@@ -140,7 +148,7 @@ class EnodebCharm(CharmBase):
                     "--nas.apn=oai.ipv4",
                     "--rf.device_name=zmq",
                     "--rf.device_args='tx_port=tcp://*:2001,rx_port=tcp://localhost:2000,id=ue,base_srate=23.04e6'",
-                    "/configzmq/ue.conf"
+                    "/configzmq/ue.conf",
                 ]
             )
             logger.debug("Attach UE action: executing")
@@ -151,5 +159,37 @@ class EnodebCharm(CharmBase):
             )
         except subprocess.CalledProcessError as ex:
             event.fail(ex)
+
+    def on_detach_ue_action(self, event):
+        """Detach UE action"""
+        try:
+            command = "sudo killall -s KILL srsue"
+            output = subprocess.check_output(command, shell=True)
+            event.set_results(
+                {"status": "ok", "message": "Detached successfully", "output": output}
+            )
+        except subprocess.CalledProcessError as e:
+            event.fail("Command error: {}".format(e.output))
+        except Exception as e:
+            event.fail(e)
+
+    def remove_default_gw(self, event):
+        """Remove default gw"""
+        try:
+            command = "sudo route del default"
+            output = subprocess.check_output(command, shell=True)
+            event.set_results(
+                {"status": "ok", "message": "Default route removed!", "output": output}
+            )
+        except subprocess.CalledProcessError as e:
+            event.fail("Command error: {}".format(e.output))
+        except Exception as e:
+            event.fail(e)
+
+    def _run_daemon(self, cmd, stdout_file):
+        with open(stdout_file, "wb") as f:
+            return subprocess.Popen(cmd, shell=True, stdout=f)
+
+
 if __name__ == "__main__":
-    main(EnodebCharm)
\ No newline at end of file
+    main(EnodebCharm)
diff --git a/magma/hackfest_magma-agw-enb_vnfd/magma-agw-enb_vnfd.yaml b/magma/hackfest_magma-agw-enb_vnfd/magma-agw-enb_vnfd.yaml
index 148da0de..aed0f977 100644
--- a/magma/hackfest_magma-agw-enb_vnfd/magma-agw-enb_vnfd.yaml
+++ b/magma/hackfest_magma-agw-enb_vnfd/magma-agw-enb_vnfd.yaml
@@ -91,6 +91,9 @@ vnfd:vnfd-catalog:
                   ssh-access:
                      required: True
                      default-user: ubuntu
+               initial-config-primitive:
+               -  seq: '1'
+                  name: remove-default-gw
                config-primitive:
                -  name: register
                   parameter:
@@ -108,6 +111,8 @@ vnfd:vnfd-catalog:
                      data-type: STRING
                   -  name: usim-opc
                      data-type: STRING
+               -  name: unregister
+               -  name: detach-ue
         internal-vld:
         -   id: internalS1
             name: internalS1
-- 
GitLab