From 8380ad1ef3b9b3997fdcbac2bb2018806152cec3 Mon Sep 17 00:00:00 2001
From: Liz Rice <liz@lizrice.com>
Date: Thu, 31 Aug 2017 16:01:31 +0100
Subject: [PATCH] Better detection of running executables

---
 cmd/util.go      | 16 ++++++++--------
 cmd/util_test.go |  5 +++++
 2 files changed, 13 insertions(+), 8 deletions(-)

diff --git a/cmd/util.go b/cmd/util.go
index 52010f4..4d96c51 100644
--- a/cmd/util.go
+++ b/cmd/util.go
@@ -159,14 +159,14 @@ func verifyBin(bin string) bool {
 	proc := strings.Fields(bin)[0]
 	out := psFunc(proc)
 
-	if !strings.Contains(out, bin) {
-		return false
-	}
-
-	// Make sure we're not just matching on a partial word (e.g. if we're looking for apiserver, don't match on kube-apiserver)
-	// This will give a false positive for matching "one two" against "zero one two-x" but it will do for now
-	for _, f := range strings.Fields(out) {
-		if f == proc {
+	// There could be multiple lines in the ps output
+	// The binary needs to be the first word in the ps output, except that it could be preceded by a path
+	// e.g. /usr/bin/kubelet is a match for kubelet
+	// but apiserver is not a match for kube-apiserver
+	reFirstWord := regexp.MustCompile(`^(\S*\/)*` + bin)
+	lines := strings.Split(out, "\n")
+	for _, l := range lines {
+		if reFirstWord.Match([]byte(l)) {
 			return true
 		}
 	}
diff --git a/cmd/util_test.go b/cmd/util_test.go
index c95e6e4..eb1b90f 100644
--- a/cmd/util_test.go
+++ b/cmd/util_test.go
@@ -108,6 +108,11 @@ func TestVerifyBin(t *testing.T) {
 		{proc: "cmd", psOut: "cmd param1 param2", exp: true},
 		{proc: "cmd param", psOut: "cmd param1 param2", exp: true},
 		{proc: "cmd param", psOut: "cmd", exp: false},
+		{proc: "cmd", psOut: "cmd x \ncmd y", exp: true},
+		{proc: "cmd y", psOut: "cmd x \ncmd y", exp: true},
+		{proc: "cmd", psOut: "/usr/bin/cmd", exp: true},
+		{proc: "cmd", psOut: "kube-cmd", exp: false},
+		{proc: "cmd", psOut: "/usr/bin/kube-cmd", exp: false},
 	}
 
 	psFunc = fakeps
-- 
GitLab