github.com/apptainer/singularity@v3.1.1+incompatible/internal/pkg/runtime/engines/singularity/cleanup.go (about) 1 // Copyright (c) 2018, Sylabs Inc. All rights reserved. 2 // This software is licensed under a 3-clause BSD license. Please consult the 3 // LICENSE.md file distributed with the sources of this project regarding your 4 // rights to use or distribute this software. 5 6 package singularity 7 8 import ( 9 "fmt" 10 "os" 11 "syscall" 12 13 "github.com/sylabs/singularity/internal/pkg/util/mainthread" 14 15 "github.com/sylabs/singularity/internal/pkg/instance" 16 "github.com/sylabs/singularity/internal/pkg/sylog" 17 ) 18 19 /* 20 * see https://github.com/opencontainers/runtime-spec/blob/master/runtime.md#lifecycle 21 * we will run step 8/9 there 22 */ 23 24 // CleanupContainer cleans up the container 25 func (engine *EngineOperations) CleanupContainer(fatal error, status syscall.WaitStatus) error { 26 sylog.Debugf("Cleanup container") 27 28 if engine.EngineConfig.GetDeleteImage() { 29 image := engine.EngineConfig.GetImage() 30 sylog.Verbosef("Removing image %s", image) 31 sylog.Infof("Cleaning up image...") 32 if err := os.RemoveAll(image); err != nil { 33 sylog.Errorf("failed to delete container image %s: %s", image, err) 34 } 35 } 36 37 if engine.EngineConfig.Network != nil { 38 if err := engine.EngineConfig.Network.DelNetworks(); err != nil { 39 sylog.Errorf("%s", err) 40 } 41 } 42 43 if engine.EngineConfig.Cgroups != nil { 44 if err := engine.EngineConfig.Cgroups.Remove(); err != nil { 45 sylog.Errorf("%s", err) 46 } 47 } 48 49 if engine.EngineConfig.GetInstance() { 50 uid := os.Getuid() 51 52 file, err := instance.Get(engine.CommonConfig.ContainerID, instance.SingSubDir) 53 if err != nil { 54 return err 55 } 56 57 if file.PPid != os.Getpid() { 58 return nil 59 } 60 61 if file.Privileged { 62 var err error 63 64 mainthread.Execute(func() { 65 if err := syscall.Setresuid(0, 0, uid); err != nil { 66 err = fmt.Errorf("failed to escalate privileges") 67 return 68 } 69 defer syscall.Setresuid(uid, uid, 0) 70 71 if err = file.Delete(); err != nil { 72 return 73 } 74 }) 75 return err 76 } 77 return file.Delete() 78 } 79 80 return nil 81 }