{"id":2003662,"url":"http://patchwork.ozlabs.org/api/patches/2003662/?format=json","web_url":"http://patchwork.ozlabs.org/project/openvswitch/patch/20241029101608.2991596-2-i.maximets@ovn.org/","project":{"id":47,"url":"http://patchwork.ozlabs.org/api/projects/47/?format=json","name":"Open vSwitch","link_name":"openvswitch","list_id":"ovs-dev.openvswitch.org","list_email":"ovs-dev@openvswitch.org","web_url":"http://openvswitch.org/","scm_url":"git@github.com:openvswitch/ovs.git","webscm_url":"https://github.com/openvswitch/ovs","list_archive_url":"","list_archive_url_format":"","commit_url_format":""},"msgid":"<20241029101608.2991596-2-i.maximets@ovn.org>","list_archive_url":null,"date":"2024-10-29T10:14:59","name":"[ovs-dev,1/9] ipsec: Add a helper function to run commands from the monitor.","commit_ref":null,"pull_url":null,"state":"changes-requested","archived":false,"hash":"7aed1c7242ea648c7264f7729cc0015b781593d9","submitter":{"id":76798,"url":"http://patchwork.ozlabs.org/api/people/76798/?format=json","name":"Ilya Maximets","email":"i.maximets@ovn.org"},"delegate":null,"mbox":"http://patchwork.ozlabs.org/project/openvswitch/patch/20241029101608.2991596-2-i.maximets@ovn.org/mbox/","series":[{"id":430270,"url":"http://patchwork.ozlabs.org/api/series/430270/?format=json","web_url":"http://patchwork.ozlabs.org/project/openvswitch/list/?series=430270","date":"2024-10-29T10:14:58","name":"ipsec: Resiliency to Libreswan failures.","version":1,"mbox":"http://patchwork.ozlabs.org/series/430270/mbox/"}],"comments":"http://patchwork.ozlabs.org/api/patches/2003662/comments/","check":"success","checks":"http://patchwork.ozlabs.org/api/patches/2003662/checks/","tags":{},"related":[],"headers":{"Return-Path":"<ovs-dev-bounces@openvswitch.org>","X-Original-To":["incoming@patchwork.ozlabs.org","ovs-dev@openvswitch.org"],"Delivered-To":["patchwork-incoming@legolas.ozlabs.org","ovs-dev@lists.linuxfoundation.org"],"Authentication-Results":["legolas.ozlabs.org;\n spf=pass (sender SPF authorized) smtp.mailfrom=openvswitch.org\n (client-ip=140.211.166.136; helo=smtp3.osuosl.org;\n envelope-from=ovs-dev-bounces@openvswitch.org; receiver=patchwork.ozlabs.org)","smtp2.osuosl.org;\n dmarc=none (p=none dis=none) header.from=ovn.org"],"Received":["from smtp3.osuosl.org (smtp3.osuosl.org [140.211.166.136])\n\t(using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)\n\t key-exchange X25519 server-signature ECDSA (secp384r1) server-digest SHA384)\n\t(No client certificate requested)\n\tby legolas.ozlabs.org (Postfix) with ESMTPS id 4Xd5ky4Cb9z1xwn\n\tfor <incoming@patchwork.ozlabs.org>; Tue, 29 Oct 2024 21:16:26 +1100 (AEDT)","from localhost (localhost [127.0.0.1])\n\tby smtp3.osuosl.org (Postfix) with ESMTP id B840760D53;\n\tTue, 29 Oct 2024 10:16:24 +0000 (UTC)","from smtp3.osuosl.org ([127.0.0.1])\n by localhost (smtp3.osuosl.org [127.0.0.1]) (amavis, port 10024) with ESMTP\n id au72CrJDiE3l; Tue, 29 Oct 2024 10:16:21 +0000 (UTC)","from lists.linuxfoundation.org (lf-lists.osuosl.org\n [IPv6:2605:bc80:3010:104::8cd3:938])\n\tby smtp3.osuosl.org (Postfix) with ESMTPS id A73E360A3B;\n\tTue, 29 Oct 2024 10:16:21 +0000 (UTC)","from lf-lists.osuosl.org (localhost [127.0.0.1])\n\tby lists.linuxfoundation.org (Postfix) with ESMTP id 86247C08A6;\n\tTue, 29 Oct 2024 10:16:21 +0000 (UTC)","from smtp2.osuosl.org (smtp2.osuosl.org [140.211.166.133])\n by lists.linuxfoundation.org (Postfix) with ESMTP id 90E3CC08A8\n for <ovs-dev@openvswitch.org>; Tue, 29 Oct 2024 10:16:20 +0000 (UTC)","from localhost (localhost [127.0.0.1])\n by smtp2.osuosl.org (Postfix) with ESMTP id 6A23D40B1F\n for <ovs-dev@openvswitch.org>; Tue, 29 Oct 2024 10:16:20 +0000 (UTC)","from smtp2.osuosl.org ([127.0.0.1])\n by localhost (smtp2.osuosl.org [127.0.0.1]) (amavis, port 10024) with ESMTP\n id ZKA3JUSY-PAG for <ovs-dev@openvswitch.org>;\n Tue, 29 Oct 2024 10:16:18 +0000 (UTC)","from mail-wm1-f68.google.com (mail-wm1-f68.google.com\n [209.85.128.68])\n by smtp2.osuosl.org (Postfix) with ESMTPS id 83EE840AFB\n for <ovs-dev@openvswitch.org>; Tue, 29 Oct 2024 10:16:17 +0000 (UTC)","by mail-wm1-f68.google.com with SMTP id\n 5b1f17b1804b1-431ac30d379so15819535e9.1\n for <ovs-dev@openvswitch.org>; Tue, 29 Oct 2024 03:16:17 -0700 (PDT)","from im-t490s.redhat.com (ip-86-49-44-151.bb.vodafone.cz.\n [86.49.44.151]) by smtp.gmail.com with ESMTPSA id\n 5b1f17b1804b1-431b4594ec3sm20279685e9.1.2024.10.29.03.16.14\n (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256);\n Tue, 29 Oct 2024 03:16:14 -0700 (PDT)"],"X-Virus-Scanned":["amavis at osuosl.org","amavis at osuosl.org"],"X-Comment":"SPF check N/A for local connections -\n client-ip=2605:bc80:3010:104::8cd3:938; helo=lists.linuxfoundation.org;\n envelope-from=ovs-dev-bounces@openvswitch.org; receiver=<UNKNOWN> ","DKIM-Filter":["OpenDKIM Filter v2.11.0 smtp3.osuosl.org A73E360A3B","OpenDKIM Filter v2.11.0 smtp2.osuosl.org 83EE840AFB"],"Received-SPF":"Pass (mailfrom) identity=mailfrom; client-ip=209.85.128.68;\n helo=mail-wm1-f68.google.com; envelope-from=i.maximets.ovn@gmail.com;\n receiver=<UNKNOWN>","DMARC-Filter":"OpenDMARC Filter v1.4.2 smtp2.osuosl.org 83EE840AFB","X-Google-DKIM-Signature":"v=1; a=rsa-sha256; c=relaxed/relaxed;\n d=1e100.net; s=20230601; t=1730196975; x=1730801775;\n h=content-transfer-encoding:mime-version:references:in-reply-to\n :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc\n :subject:date:message-id:reply-to;\n bh=sTc4JfznMqjHEBSgMU5MG3oR025MM5QTzNErnxhkfY4=;\n b=KYh2nUMz8+UpomI818/vGZg3kCKG4otE7HmekKko4uOUTeu6kTSGtsWbuD7nkVVlL+\n luyp3HQtFCx+ej1YLJwYp2zdzAngjHDax4cd2UdLsHTJwBShCTy6behze8a7hEgb3AgU\n cA+Qd+Opok5zwKATXGdTVLFpo+rtjo0JGJfepayi/ymWFfIMzndHsTh/dfyXn4cm077H\n DXS2KVWQ/ehCOcH0X2MQ4yLKzOdbjCRBZBbkxvYUNrOmC9WTXmIhbpWJDriO4KJtgzGZ\n SdlsPQa5q73VXHLpSCI1Rxn/BQBR2inWGd/Bbdb1B2r8p/MawRIsEpwKsGDuYEIuXJ5h\n 3/8Q==","X-Gm-Message-State":"AOJu0YzdE9498xswlKhSUVnCuci8+WC8z8uaIe8d13sPOnjGezseHg2s\n hA+PD6XTsJXv553fsvLJRXrRRp0EexCXbGCVKNG1+qqUnRyJ7YJEP2rySlSY","X-Google-Smtp-Source":"\n AGHT+IGSvbILYQVs+eCFU6r9FFHVtk10c/zys09juaH+W1oogz9fvFT3y8x7DJA/jVZi+YXJd4231Q==","X-Received":"by 2002:a05:600c:1c82:b0:430:699b:7d22 with SMTP id\n 5b1f17b1804b1-4319ad14d14mr109825345e9.26.1730196975101;\n Tue, 29 Oct 2024 03:16:15 -0700 (PDT)","From":"Ilya Maximets <i.maximets@ovn.org>","To":"ovs-dev@openvswitch.org","Date":"Tue, 29 Oct 2024 11:14:59 +0100","Message-ID":"<20241029101608.2991596-2-i.maximets@ovn.org>","X-Mailer":"git-send-email 2.46.0","In-Reply-To":"<20241029101608.2991596-1-i.maximets@ovn.org>","References":"<20241029101608.2991596-1-i.maximets@ovn.org>","MIME-Version":"1.0","Subject":"[ovs-dev] [PATCH 1/9] ipsec: Add a helper function to run commands\n from the monitor.","X-BeenThere":"ovs-dev@openvswitch.org","X-Mailman-Version":"2.1.30","Precedence":"list","List-Id":"<ovs-dev.openvswitch.org>","List-Unsubscribe":"<https://mail.openvswitch.org/mailman/options/ovs-dev>,\n <mailto:ovs-dev-request@openvswitch.org?subject=unsubscribe>","List-Archive":"<http://mail.openvswitch.org/pipermail/ovs-dev/>","List-Post":"<mailto:ovs-dev@openvswitch.org>","List-Help":"<mailto:ovs-dev-request@openvswitch.org?subject=help>","List-Subscribe":"<https://mail.openvswitch.org/mailman/listinfo/ovs-dev>,\n <mailto:ovs-dev-request@openvswitch.org?subject=subscribe>","Cc":"Ilya Maximets <i.maximets@ovn.org>","Content-Type":"text/plain; charset=\"us-ascii\"","Content-Transfer-Encoding":"7bit","Errors-To":"ovs-dev-bounces@openvswitch.org","Sender":"\"dev\" <ovs-dev-bounces@openvswitch.org>"},"content":"Until now, functions that needed to call external programs like openssl\nor ipsec commands were using subprocess commands directly.  Most of\nthese calls had no failure checks or any logging making it hard to\nunderstand what is happening inside the daemon when something doesn't\nwork as intended.\n\nSome commands also had a chance to not read the command output in full.\nThat might sound like not a big problem, but in practice it causes\novs-monitor-ipsec to deadlock pluto and itself with certain versions of\nLibreswan (mainly Libreswan 5+).  The order of events is following:\n\n 1. ovs-monitor-ipsec calls ipsec status redirecting the output\n    to a pipe.\n 2. ipsec status calls ipsec whack.\n 3. ipsec whack connects to pluto and asks for status.\n 4. ovs-monitor-ipsec doesn't read the pipe in full.\n 5. ipsec whack blocks on write to the other side of the pipe\n    when it runs out of buffer space.\n 6. pluto blocks on sendmsg to ipsec whack for the same reason.\n 7. ovs-monitor-ipsec calls another ipsec command and blocks\n    on connection to pluto.\n\nIn this scenario the running process is at the mercy of garbage\ncollector and it doesn't run because we're blocked on calling another\nipsec command.  All the processes are completely blocked and will not\ndo any work until ipsec whack is killed.\n\nWith this change we're introducing a new function that will be used\nfor all the external process execution commands and will read the full\noutput before returning, avoiding the deadlock.  It will also log all\nthe failures as warnings and the commands themselves at the debug level.\n\nWe'll be adding more logic into this function in later commits as well,\nso it will not stay that simple.\n\nSigned-off-by: Ilya Maximets <i.maximets@ovn.org>\n---\n ipsec/ovs-monitor-ipsec.in | 296 +++++++++++++++++--------------------\n 1 file changed, 134 insertions(+), 162 deletions(-)","diff":"diff --git a/ipsec/ovs-monitor-ipsec.in b/ipsec/ovs-monitor-ipsec.in\nindex 37c509ac6..19a401609 100755\n--- a/ipsec/ovs-monitor-ipsec.in\n+++ b/ipsec/ovs-monitor-ipsec.in\n@@ -84,6 +84,28 @@ monitor = None\n xfrm = None\n \n \n+def run_command(args, description=None):\n+    \"\"\" This function runs the process args[0] with args[1:] arguments\n+    and returns a tuple: return-code, stdout, stderr. \"\"\"\n+\n+    if not description:\n+        description = args[-1]\n+\n+    vlog.dbg(\"Running %s\" % args)\n+    proc = subprocess.Popen(args, stdout=subprocess.PIPE,\n+                            stderr=subprocess.PIPE)\n+    pout, perr = proc.communicate()\n+\n+    if proc.returncode or len(perr):\n+        vlog.warn(\"Failed to %s; exit code: %d\"\n+                  % (description, proc.returncode))\n+        vlog.warn(\"cmdline: %s\" % proc.args)\n+        vlog.warn(\"stderr: %s\" % perr)\n+        vlog.warn(\"stdout: %s\" % pout)\n+\n+    return proc.returncode, pout or b'', perr or b''\n+\n+\n class XFRM(object):\n     \"\"\"This class is a simple wrapper around ip-xfrm (8) command line\n     utility.  We are using this class only for informational purposes\n@@ -99,13 +121,14 @@ class XFRM(object):\n         where <key> is destination IPv4 address and <value> is SELECTOR of\n         the IPsec policy.\"\"\"\n         policies = {}\n-        proc = subprocess.Popen([self.IP, 'xfrm', 'policy'],\n-                                stdout=subprocess.PIPE)\n-        while True:\n-            line = proc.stdout.readline().strip().decode()\n-            if line == '':\n-                break\n-            a = line.split(\" \")\n+\n+        ret, pout, perr = run_command([self.IP, 'xfrm', 'policy'],\n+                                      \"get XFRM policies\")\n+        if ret:\n+            return policies\n+\n+        for line in pout.decode().splitlines():\n+            a = line.strip().split(\" \")\n             if len(a) >= 4 and a[0] == \"src\" and a[2] == \"dst\":\n                 dst = (a[3].split(\"/\"))[0]\n                 if dst not in policies:\n@@ -122,13 +145,14 @@ class XFRM(object):\n         in a dictionary where <key> is destination IPv4 address and <value>\n         is SELECTOR.\"\"\"\n         securities = {}\n-        proc = subprocess.Popen([self.IP, 'xfrm', 'state'],\n-                                stdout=subprocess.PIPE)\n-        while True:\n-            line = proc.stdout.readline().strip().decode()\n-            if line == '':\n-                break\n-            a = line.split(\" \")\n+\n+        ret, pout, perr = run_command([self.IP, 'xfrm', 'state'],\n+                                      \"get XFRM state\")\n+        if ret:\n+            return securities\n+\n+        for line in pout.decode().splitlines():\n+            a = line.strip().split(\" \")\n             if len(a) >= 4 and a[0] == \"sel\" \\\n                     and a[1] == \"src\" and a[3] == \"dst\":\n                 remote_ip = a[4].rstrip().split(\"/\")[0]\n@@ -242,7 +266,7 @@ conn prevent_unencrypted_vxlan\n         f.close()\n \n         vlog.info(\"Restarting StrongSwan\")\n-        subprocess.call([self.IPSEC, \"restart\"])\n+        run_command([self.IPSEC, \"restart\"], \"restart StrongSwan\")\n \n     def get_active_conns(self):\n         \"\"\"This function parses output from 'ipsec status' command.\n@@ -252,13 +276,13 @@ conn prevent_unencrypted_vxlan\n         sample line from the parsed outpus as <value>. \"\"\"\n \n         conns = {}\n-        proc = subprocess.Popen([self.IPSEC, 'status'], stdout=subprocess.PIPE)\n+        ret, pout, perr = run_command([self.IPSEC, 'status'],\n+                                      \"get active connections\")\n+        if ret:\n+            return conns\n \n-        while True:\n-            line = proc.stdout.readline().strip().decode()\n-            if line == '':\n-                break\n-            tunnel_name = line.split(\":\")\n+        for line in pout.decode().splitlines():\n+            tunnel_name = line.strip().split(\":\")\n             if len(tunnel_name) < 2:\n                 continue\n             m = re.match(r\"(.*)(-in-\\d+|-out-\\d+|-\\d+).*\", tunnel_name[0])\n@@ -341,15 +365,11 @@ conn prevent_unencrypted_vxlan\n         Once strongSwan vici bindings will be distributed with major\n         Linux distributions this function could be simplified.\"\"\"\n         vlog.info(\"Refreshing StrongSwan configuration\")\n-        proc = subprocess.Popen([self.IPSEC, \"update\"],\n-                        stdout=subprocess.PIPE,\n-                        stderr=subprocess.PIPE)\n-        outs, errs = proc.communicate()\n-        if proc.returncode != 0:\n-            vlog.err(\"StrongSwan failed to update configuration:\\n\"\n-                           \"%s \\n %s\" % (str(outs), str(errs)))\n-\n-        subprocess.call([self.IPSEC, \"rereadsecrets\"])\n+\n+        run_command([self.IPSEC, \"update\"],\n+                    \"update StrongSwan's configuration\")\n+        run_command([self.IPSEC, \"rereadsecrets\"], \"re-read secrets\")\n+\n         # \"ipsec update\" command does not remove those tunnels that were\n         # updated or that disappeared from the ipsec.conf file.  So, we have\n         # to manually remove them by calling \"ipsec stroke down-nb <tunnel>\"\n@@ -382,7 +402,8 @@ conn prevent_unencrypted_vxlan\n \n                 if not tunnel or tunnel.version != ver:\n                     vlog.info(\"%s is outdated %u\" % (conn, ver))\n-                    subprocess.call([self.IPSEC, \"stroke\", \"down-nb\", conn])\n+                    run_command([self.IPSEC, \"stroke\", \"down-nb\", conn],\n+                                \"stroke the outdated %s\" % conn)\n \n \n class LibreSwanHelper(object):\n@@ -460,13 +481,11 @@ conn prevent_unencrypted_vxlan\n         # Collect version infromation\n         self.IPSEC = libreswan_root_prefix + \"/usr/sbin/ipsec\"\n         self.IPSEC_AUTO = [self.IPSEC]\n-        proc = subprocess.Popen([self.IPSEC, \"--version\"],\n-                                stdout=subprocess.PIPE,\n-                                encoding=\"latin1\")\n-        pout, perr = proc.communicate()\n \n-        v = re.match(\"^Libreswan v?(.*)$\", pout)\n+        ret, pout, perr = run_command([self.IPSEC, \"--version\"],\n+                                      \"get Libreswan's version\")\n         try:\n+            v = re.match(\"^Libreswan v?(.*)$\", pout.decode().strip())\n             version = int(v.group(1).split(\".\")[0])\n         except:\n             version = 0\n@@ -513,7 +532,7 @@ conn prevent_unencrypted_vxlan\n         f.close()\n \n         vlog.info(\"Restarting LibreSwan\")\n-        subprocess.call([self.IPSEC, \"restart\"])\n+        run_command([self.IPSEC, \"restart\"], \"restart Libreswan\")\n \n     def config_init(self):\n         self.conf_file = open(self.IPSEC_CONF, \"w\")\n@@ -599,8 +618,10 @@ conn prevent_unencrypted_vxlan\n \n     def refresh(self, monitor):\n         vlog.info(\"Refreshing LibreSwan configuration\")\n-        subprocess.call(self.IPSEC_AUTO + [\"--ctlsocket\", self.IPSEC_CTL,\n-                        \"--config\", self.IPSEC_CONF, \"--rereadsecrets\"])\n+        run_command(self.IPSEC_AUTO + [\"--ctlsocket\", self.IPSEC_CTL,\n+                                       \"--config\", self.IPSEC_CONF,\n+                                       \"--rereadsecrets\"],\n+                    \"re-read secrets\")\n         tunnels = set(monitor.tunnels.keys())\n \n         # Delete old connections\n@@ -627,9 +648,10 @@ conn prevent_unencrypted_vxlan\n \n                 if not tunnel or tunnel.version != ver:\n                     vlog.info(\"%s is outdated %u\" % (conn, ver))\n-                    subprocess.call(self.IPSEC_AUTO + [\"--ctlsocket\",\n-                                    self.IPSEC_CTL, \"--config\",\n-                                    self.IPSEC_CONF, \"--delete\", conn])\n+                    run_command(self.IPSEC_AUTO +\n+                                [\"--ctlsocket\", self.IPSEC_CTL,\n+                                 \"--config\", self.IPSEC_CONF,\n+                                 \"--delete\", conn], \"delete %s\" % conn)\n                 elif ifname in tunnels:\n                     tunnels.remove(ifname)\n \n@@ -649,43 +671,43 @@ conn prevent_unencrypted_vxlan\n         # Update shunt policy if changed\n         if monitor.conf_in_use[\"skb_mark\"] != monitor.conf[\"skb_mark\"]:\n             if monitor.conf[\"skb_mark\"]:\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--add\",\n                             \"--asynchronous\", \"prevent_unencrypted_gre\"])\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--add\",\n                             \"--asynchronous\", \"prevent_unencrypted_geneve\"])\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--add\",\n                             \"--asynchronous\", \"prevent_unencrypted_stt\"])\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--add\",\n                             \"--asynchronous\", \"prevent_unencrypted_vxlan\"])\n             else:\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--delete\",\n                             \"--asynchronous\", \"prevent_unencrypted_gre\"])\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--delete\",\n                             \"--asynchronous\", \"prevent_unencrypted_geneve\"])\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--delete\",\n                             \"--asynchronous\", \"prevent_unencrypted_stt\"])\n-                subprocess.call(self.IPSEC_AUTO +\n+                run_command(self.IPSEC_AUTO +\n                             [\"--config\", self.IPSEC_CONF,\n                             \"--ctlsocket\", self.IPSEC_CTL,\n                             \"--delete\",\n@@ -700,14 +722,13 @@ conn prevent_unencrypted_vxlan\n         sample line from the parsed outpus as <value>. \"\"\"\n \n         conns = {}\n-        proc = subprocess.Popen([self.IPSEC, 'status', '--ctlsocket',\n-                                self.IPSEC_CTL], stdout=subprocess.PIPE)\n-\n-        while True:\n-            line = proc.stdout.readline().strip().decode()\n-            if line == '':\n-                break\n+        ret, pout, perr = run_command([self.IPSEC, 'status',\n+                                      '--ctlsocket', self.IPSEC_CTL],\n+                                      \"get active connections\")\n+        if ret:\n+            return conns\n \n+        for line in pout.decode().splitlines():\n             m = re.search(r\"#\\d+: \\\"(.*)\\\".*\", line)\n             if not m:\n                 continue\n@@ -732,117 +753,72 @@ conn prevent_unencrypted_vxlan\n         # the \"ipsec auto --start\" command is lost. Just retry to make sure\n         # the command is received by LibreSwan.\n         while True:\n-            proc = subprocess.Popen(self.IPSEC_AUTO +\n-                                    [\"--config\", self.IPSEC_CONF,\n-                                    \"--ctlsocket\", self.IPSEC_CTL,\n-                                    \"--start\",\n-                                    \"--asynchronous\", conn],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE)\n-            perr = str(proc.stderr.read())\n-            pout = str(proc.stdout.read())\n-            if not re.match(r\".*Connection refused.*\", perr) and \\\n-                    not re.match(r\".*need --listen.*\", pout):\n+            ret, pout, perr = run_command(self.IPSEC_AUTO +\n+                                          [\"--config\", self.IPSEC_CONF,\n+                                          \"--ctlsocket\", self.IPSEC_CTL,\n+                                          \"--start\",\n+                                          \"--asynchronous\", conn],\n+                                          \"start %s\" % conn)\n+            if not re.match(r\".*Connection refused.*\", perr.decode()) and \\\n+                    not re.match(r\".*need --listen.*\", pout.decode()):\n                 break\n \n-        if re.match(r\".*[F|f]ailed to initiate connection.*\", pout):\n+        if re.match(r\".*[F|f]ailed to initiate connection.*\", pout.decode()):\n             vlog.err('Failed to initiate connection through'\n                     ' Interface %s.\\n' % (conn.split('-')[0]))\n-            vlog.err(pout)\n+            vlog.err(\"stdout: %s\" % pout)\n \n     def _nss_clear_database(self):\n         \"\"\"Remove all OVS IPsec related state from the NSS database\"\"\"\n-        try:\n-            proc = subprocess.Popen(['certutil', '-L', '-d',\n-                                    self.IPSEC_D],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE,\n-                                    universal_newlines=True)\n-            lines = proc.stdout.readlines()\n-\n-            for line in lines:\n-                s = line.strip().split()\n-                if len(s) < 1:\n-                    continue\n-                name = s[0]\n-                if name.startswith(self.CERT_PREFIX):\n-                    self._nss_delete_cert(name)\n-                elif name.startswith(self.CERTKEY_PREFIX):\n-                    self._nss_delete_cert_and_key(name)\n+        ret, pout, perr = run_command(['certutil', '-L', '-d', self.IPSEC_D],\n+                                      \"clear NSS database\")\n+        if ret:\n+            return\n \n-        except Exception as e:\n-            vlog.err(\"Failed to clear NSS database.\\n\" + str(e))\n+        for line in pout.decode().splitlines():\n+            s = line.strip().split()\n+            if len(s) < 1:\n+                continue\n+            name = s[0]\n+            if name.startswith(self.CERT_PREFIX):\n+                self._nss_delete_cert(name)\n+            elif name.startswith(self.CERTKEY_PREFIX):\n+                self._nss_delete_cert_and_key(name)\n \n     def _nss_import_cert(self, cert, name, cert_type):\n         \"\"\"Cert_type is 'CT,,' for the CA certificate and 'P,P,P' for the\n         normal certificate.\"\"\"\n-        try:\n-            proc = subprocess.Popen(['certutil', '-A', '-a', '-i', cert,\n-                                    '-d', self.IPSEC_D, '-n',\n-                                    name, '-t', cert_type],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE)\n-            proc.wait()\n-            if proc.returncode:\n-                raise Exception(proc.stderr.read())\n-        except Exception as e:\n-            vlog.err(\"Failed to import certificate into NSS.\\n\" + str(e))\n+        run_command(['certutil', '-A', '-a', '-i', cert, '-d', self.IPSEC_D,\n+                     '-n', name, '-t', cert_type],\n+                    \"import certificate %s into NSS\" % name)\n \n     def _nss_delete_cert(self, name):\n-        try:\n-            proc = subprocess.Popen(['certutil', '-D', '-d',\n-                                    self.IPSEC_D, '-n', name],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE)\n-            proc.wait()\n-            if proc.returncode:\n-                raise Exception(proc.stderr.read())\n-        except Exception as e:\n-            vlog.err(\"Failed to delete certificate from NSS.\\n\" + str(e))\n+        run_command(['certutil', '-D', '-d', self.IPSEC_D, '-n', name],\n+                    \"delete certificate %s from NSS\" % name)\n \n     def _nss_import_cert_and_key(self, cert, key, name):\n-        try:\n-            # Avoid deleting other files\n-            path = os.path.abspath('/tmp/%s.p12' % name)\n-            if not path.startswith('/tmp/'):\n-                raise Exception(\"Illegal certificate name!\")\n-\n-            # Create p12 file from pem files\n-            proc = subprocess.Popen(['openssl', 'pkcs12', '-export',\n-                                    '-in', cert, '-inkey', key, '-out',\n-                                    path, '-name', name, '-passout', 'pass:'],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE)\n-            proc.wait()\n-            if proc.returncode:\n-                raise Exception(proc.stderr.read())\n-\n-            # Load p12 file to the database\n-            proc = subprocess.Popen(['pk12util', '-i', path, '-d',\n-                                    self.IPSEC_D, '-W', ''],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE)\n-            proc.wait()\n-            if proc.returncode:\n-                raise Exception(proc.stderr.read())\n-\n-        except Exception as e:\n-            vlog.err(\"Import cert and key failed.\\n\" + str(e))\n+        # Avoid deleting other files\n+        path = os.path.abspath('/tmp/%s.p12' % name)\n+        if not path.startswith('/tmp/'):\n+            vlog.err(\"Illegal certificate name '%s'!\" % name)\n+            return\n+\n+        if run_command(['openssl', 'pkcs12', '-export',\n+                       '-in', cert, '-inkey', key,\n+                       '-out', path, '-name', name,\n+                       '-passout', 'pass:'],\n+                       \"create p12 file from pem files\")[0]:\n+            return\n+\n+        # Load p12 file to the database\n+        run_command(['pk12util', '-i', path, '-d', self.IPSEC_D, '-W', ''],\n+                    \"load p12 file to the NSS database\")\n         os.remove(path)\n \n     def _nss_delete_cert_and_key(self, name):\n-        try:\n-            # Delete certificate and private key\n-            proc = subprocess.Popen(['certutil', '-F', '-d',\n-                                    self.IPSEC_D, '-n', name],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE)\n-            proc.wait()\n-            if proc.returncode:\n-                raise Exception(proc.stderr.read())\n-\n-        except Exception as e:\n-            vlog.err(\"Delete cert and key failed.\\n\" + str(e))\n+        # Delete certificate and private key\n+        run_command(['certutil', '-F', '-d', self.IPSEC_D, '-n', name],\n+                    \"delete certificate and private key for %s\" % name)\n \n \n class IPsecTunnel(object):\n@@ -1220,19 +1196,15 @@ class IPsecMonitor(object):\n             self.ike_helper.refresh(self)\n \n     def _get_cn_from_cert(self, cert):\n-        try:\n-            proc = subprocess.Popen(['openssl', 'x509', '-noout', '-subject',\n-                                    '-nameopt', 'RFC2253', '-in', cert],\n-                                    stdout=subprocess.PIPE,\n-                                    stderr=subprocess.PIPE)\n-            proc.wait()\n-            if proc.returncode:\n-                raise Exception(proc.stderr.read())\n-            m = re.search(r\"CN=(.+?),\", proc.stdout.readline().decode())\n-            if not m:\n-                raise Exception(\"No CN in the certificate subject.\")\n-        except Exception as e:\n-            vlog.warn(str(e))\n+        ret, pout, perr = run_command(['openssl', 'x509', '-noout', '-subject',\n+                                       '-nameopt', 'RFC2253', '-in', cert],\n+                                       \"get certificate %s options\" % cert)\n+        if ret:\n+            return None\n+\n+        m = re.search(r\"CN=(.+?),\", pout.decode().strip())\n+        if not m:\n+            vlog.warn(\"No CN in the certificate subject (%s).\" % cert)\n             return None\n \n         return m.group(1)\n","prefixes":["ovs-dev","1/9"]}