Use md5 to generate unique lock names

pull/6059/head
Thomas Stromberg 2019-12-11 08:13:12 -08:00
parent 11630973e5
commit cfe0f5a5b7
2 changed files with 12 additions and 19 deletions

View File

@ -17,12 +17,12 @@ limitations under the License.
package lock
import (
"crypto/md5"
"fmt"
"io/ioutil"
"os"
"os/user"
"regexp"
"strings"
"time"
"github.com/golang/glog"
@ -78,13 +78,5 @@ func UserMutexSpec(path string) mutex.Spec {
func getMutexNameForPath(path string) string {
// juju requires that names match ^[a-zA-Z][a-zA-Z0-9-]*$", and be under 40 chars long.
n := strings.Trim(nonString.ReplaceAllString(path, "-"), "-")
// we need to always guarantee an alphanumeric prefix
prefix := "m"
// Prefer the last 40 chars, as paths tend get more specific toward the end
if len(n) >= 40 {
return prefix + n[len(n)-39:]
}
return prefix + n
return fmt.Sprintf("m%x", md5.Sum([]byte(path)))
}

View File

@ -24,45 +24,46 @@ func TestUserMutexSpec(t *testing.T) {
var tests = []struct {
description string
path string
expected string
}{
{
description: "standard",
path: "/foo/bar",
expected: "mfoo-bar-test",
},
{
description: "deep directory",
path: "/foo/bar/baz/bat",
expected: "mfoo-bar-baz-bat-test",
},
{
description: "underscores",
path: "/foo_bar/baz",
expected: "mfoo-bar-baz-test",
},
{
description: "starts with number",
path: "/foo/2bar/baz",
expected: "mfoo-2bar-baz-test",
},
{
description: "starts with punctuation",
path: "/.foo/bar",
expected: "mfoo-bar-test",
},
{
description: "long filename",
path: "/very-very-very-very-very-very-very-very-long/bar",
expected: "m-very-very-very-very-very-long-bar-test",
},
{
description: "Windows kubeconfig",
path: `C:\Users\admin/.kube/config`,
},
{
description: "Windows json",
path: `C:\Users\admin\.minikube\profiles\containerd-20191210T212325.7356633-8584\config.json`,
},
}
for _, tc := range tests {
t.Run(tc.description, func(t *testing.T) {
got := UserMutexSpec(tc.path)
if got.Name != tc.expected {
t.Errorf("%s mutex name = %q, expected %q", tc.path, got.Name, tc.expected)
if len(got.Name) > 40 {
t.Errorf("%s mutex name is too long", got.Name)
}
})
}