From 9c0872dc7e1fa468ed73f8ec7a936a0af5dc1b96 Mon Sep 17 00:00:00 2001 From: Ted Yu Date: Tue, 3 Dec 2019 06:06:51 -0800 Subject: [PATCH] vc: Remove device when AddDevice encounters error Fixes #2295 Signed-off-by: Ted Yu --- virtcontainers/sandbox.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/virtcontainers/sandbox.go b/virtcontainers/sandbox.go index 1d91057a46..277ff7dd78 100644 --- a/virtcontainers/sandbox.go +++ b/virtcontainers/sandbox.go @@ -1892,17 +1892,28 @@ func (s *Sandbox) AddDevice(info config.DeviceInfo) (api.Device, error) { return nil, fmt.Errorf("device manager isn't initialized") } + var err error b, err := s.devManager.NewDevice(info) if err != nil { return nil, err } + defer func() { + if err != nil { + s.devManager.RemoveDevice(b.DeviceID()) + } + }() - if err := s.devManager.AttachDevice(b.DeviceID(), s); err != nil { + if err = s.devManager.AttachDevice(b.DeviceID(), s); err != nil { return nil, err } + defer func() { + if err != nil { + s.devManager.DetachDevice(b.DeviceID(), s) + } + }() if !s.supportNewStore() { - if err := s.storeSandboxDevices(); err != nil { + if err = s.storeSandboxDevices(); err != nil { return nil, err } }