From ee33245d95519ff86796ef6ece43a09d462637dd Mon Sep 17 00:00:00 2001 From: Peng Tao Date: Thu, 21 Jun 2018 10:29:18 +0800 Subject: [PATCH] kata_agent: fix connection race If we send multiple grpcs at once before a client is created, we end up creating multiple connections to the agent and that breaks when using builtin proxy since only one connection is allowed. Fixes: #431 Signed-off-by: Peng Tao --- virtcontainers/kata_agent.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/virtcontainers/kata_agent.go b/virtcontainers/kata_agent.go index 186f95de7e..3167bc5ab3 100644 --- a/virtcontainers/kata_agent.go +++ b/virtcontainers/kata_agent.go @@ -13,6 +13,7 @@ import ( "path/filepath" "strconv" "strings" + "sync" "syscall" "time" @@ -77,9 +78,13 @@ type KataAgentState struct { } type kataAgent struct { - shim shim - proxy proxy - client *kataclient.AgentClient + shim shim + proxy proxy + + // lock protects the client pointer + sync.Mutex + client *kataclient.AgentClient + reqHandlers map[string]reqFunc state KataAgentState keepConn bool @@ -1089,6 +1094,14 @@ func (k *kataAgent) statsContainer(sandbox *Sandbox, c Container) (*ContainerSta } func (k *kataAgent) connect() error { + // lockless quick pass + if k.client != nil { + return nil + } + + // This is for the first connection only, to prevent race + k.Lock() + defer k.Unlock() if k.client != nil { return nil } @@ -1105,6 +1118,9 @@ func (k *kataAgent) connect() error { } func (k *kataAgent) disconnect() error { + k.Lock() + defer k.Unlock() + if k.client == nil { return nil }