From 899164391d2ca57f84716a5b2f34500883bc3690 Mon Sep 17 00:00:00 2001
From: LiangZhang <zhangliang5@huawei.com>
Date: Mon, 11 Jan 2021 11:03:39 +0800
Subject: [PATCH] runtime: fixup that the getPids function returns pid 0

Use pidfile to record the real pid of stratovirt, getPids then read the content of pidfile to get pid value.

Signed-off-by: LiangZhang <zhangliang5@Huawei.com>
---
 virtcontainers/stratovirt.go | 31 ++++++++++++++++++++++++++--
 1 file changed, 29 insertions(+), 2 deletions(-)

diff --git a/virtcontainers/stratovirt.go b/virtcontainers/stratovirt.go
index 020135e..a8151de 100644
--- a/virtcontainers/stratovirt.go
+++ b/virtcontainers/stratovirt.go
@@ -3,6 +3,7 @@ package virtcontainers
 import (
 	"context"
 	"fmt"
+	"io/ioutil"
 	"os"
 	"os/exec"
 	"path/filepath"
@@ -148,6 +149,7 @@ func (s *stratovirt) startSandbox(timeout int) error {
 	params = append(params, "-smp", fmt.Sprintf("%d", s.config.NumVCPUs))
 	params = append(params, "-m", fmt.Sprintf("%d", uint64(s.config.MemorySize)*1024*1024))
 	params = append(params, "-chardev", fmt.Sprintf("id=charconsole0,path=%s", s.consolePath))
+	params = append(params, "-pidfile", filepath.Join(s.store.RunVMStoragePath(), s.id, "pid"))
 
 	// add devices to cmdline
 	for _, d := range s.devices {
@@ -587,7 +589,27 @@ func (s *stratovirt) cleanup() error {
 }
 
 func (s *stratovirt) getPids() []int {
-	return []int{s.pid}
+	var pids []int
+	if s.pid != 0 {
+		pids = append(pids, s.pid)
+	} else {
+		pid, err := ioutil.ReadFile(filepath.Join(s.store.RunVMStoragePath(), s.id, "pid"))
+		if err != nil {
+			s.Logger().WithError(err).Error("Read pid file failed.")
+			return []int{0}
+		}
+
+		p, err := strconv.Atoi(strings.Trim(string(pid), "\n\t "))
+		if err != nil {
+			s.Logger().WithError(err).Error("Get pid from pid file failed.")
+			return []int{0}
+		}
+
+		pids = append(pids, p)
+		s.pid = p
+	}
+
+	return pids
 }
 
 func (s *stratovirt) fromGrpc(ctx context.Context, hypervisorConfig *HypervisorConfig, j []byte) error {
@@ -611,12 +633,17 @@ func (s *stratovirt) generateSocket(id string, useVsock bool) (interface{}, erro
 }
 
 func (s *stratovirt) save() (p persistapi.HypervisorState) {
-	p.Pid = s.pid
+	pids := s.getPids()
+	p.Pid = pids[0]
 	p.Type = string(StratovirtHypervisor)
 	return
 }
 
 func (s *stratovirt) load(p persistapi.HypervisorState) {
 	s.pid = p.Pid
+	if sandbox, err := globalSandboxList.lookupSandbox(s.id); err == nil {
+		s.sandbox = sandbox
+	}
+
 	return
 }
-- 
2.27.0

