17813: Fix tests
[arvados.git] / lib / crunchrun / singularity.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package crunchrun
6
7 import (
8         "fmt"
9         "io"
10         "io/ioutil"
11         "os"
12         "os/exec"
13         "sort"
14         "strings"
15         "syscall"
16
17         "git.arvados.org/arvados.git/sdk/go/arvados"
18         "golang.org/x/net/context"
19 )
20
21 type singularityExecutor struct {
22         logf            func(string, ...interface{})
23         spec            containerSpec
24         tmpdir          string
25         child           *exec.Cmd
26         imageFilename   string // "sif" image
27         containerClient *arvados.Client
28         container       arvados.Container
29         keepClient      IKeepClient
30         keepMount       string
31 }
32
33 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
34         tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
35         if err != nil {
36                 return nil, err
37         }
38         return &singularityExecutor{
39                 logf:   logf,
40                 tmpdir: tmpdir,
41         }, nil
42 }
43
44 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, create bool) (*arvados.Group, error) {
45         var gp arvados.GroupList
46         err := e.containerClient.RequestAndDecode(&gp,
47                 arvados.EndpointGroupList.Method,
48                 arvados.EndpointGroupList.Path,
49                 nil, arvados.ListOptions{Filters: []arvados.Filter{
50                         arvados.Filter{"owner_uuid", "=", ownerUuid},
51                         arvados.Filter{"name", "=", name},
52                         arvados.Filter{"group_class", "=", "project"},
53                 },
54                         Limit: 1})
55         if err != nil {
56                 return nil, err
57         }
58         if len(gp.Items) == 1 {
59                 return &gp.Items[0], nil
60         }
61         if !create {
62                 return nil, nil
63         }
64         var rgroup arvados.Group
65         err = e.containerClient.RequestAndDecode(&rgroup,
66                 arvados.EndpointGroupCreate.Method,
67                 arvados.EndpointGroupCreate.Path,
68                 nil, map[string]interface{}{
69                         "group": map[string]string{
70                                 "owner_uuid":  ownerUuid,
71                                 "name":        name,
72                                 "group_class": "project",
73                         },
74                 })
75         if err != nil {
76                 return nil, err
77         }
78         return &rgroup, nil
79 }
80
81 func (e *singularityExecutor) ImageLoaded(imageId string) bool {
82         if e.containerClient == nil {
83                 return false
84         }
85
86         // Check if docker image is cached in keep & if so set imageFilename
87
88         // Cache the image to keep
89         cacheGroup, err := e.getOrCreateProject(e.container.RuntimeUserUUID, ".cache", false)
90         if err != nil {
91                 e.logf("error getting '.cache' project: %v", err)
92                 return false
93         }
94         imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", false)
95         if err != nil {
96                 e.logf("error getting 'auto-generated singularity images' project: %s", err)
97                 return false
98         }
99
100         collectionName := fmt.Sprintf("singularity image for %v", imageId)
101         var cl arvados.CollectionList
102         err = e.containerClient.RequestAndDecode(&cl,
103                 arvados.EndpointCollectionList.Method,
104                 arvados.EndpointCollectionList.Path,
105                 nil, arvados.ListOptions{Filters: []arvados.Filter{
106                         arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
107                         arvados.Filter{"name", "=", collectionName},
108                 },
109                         Limit: 1})
110         if err != nil {
111                 e.logf("error getting collection '%v' project: %v", err)
112                 return false
113         }
114         if len(cl.Items) == 0 {
115                 e.logf("no cached image '%v' found", collectionName)
116                 return false
117         }
118
119         path := fmt.Sprintf("%s/by_id/%s/image.sif", e.keepMount, cl.Items[0].PortableDataHash)
120         e.logf("Looking for %v", path)
121         if _, err = os.Stat(path); os.IsNotExist(err) {
122                 return false
123         }
124         e.imageFilename = path
125
126         return true
127 }
128
129 // LoadImage will satisfy ContainerExecuter interface transforming
130 // containerImage into a sif file for later use.
131 func (e *singularityExecutor) LoadImage(imageTarballPath string) error {
132         if e.imageFilename != "" {
133                 e.logf("using singularity image %v", e.imageFilename)
134
135                 // was set by ImageLoaded
136                 return nil
137         }
138
139         e.logf("building singularity image")
140         // "singularity build" does not accept a
141         // docker-archive://... filename containing a ":" character,
142         // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
143         // symlink that doesn't have ":" chars.
144         err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
145         if err != nil {
146                 return err
147         }
148         e.imageFilename = e.tmpdir + "/image.sif"
149         build := exec.Command("singularity", "build", e.imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
150         e.logf("%v", build.Args)
151         out, err := build.CombinedOutput()
152         // INFO:    Starting build...
153         // Getting image source signatures
154         // Copying blob ab15617702de done
155         // Copying config 651e02b8a2 done
156         // Writing manifest to image destination
157         // Storing signatures
158         // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
159         // INFO:    Creating SIF file...
160         // INFO:    Build complete: arvados-jobs.latest.sif
161         e.logf("%s", out)
162         if err != nil {
163                 return err
164         }
165
166         if e.containerClient == nil {
167                 return nil
168         }
169
170         // Cache the image to keep
171         cacheGroup, err := e.getOrCreateProject(e.container.RuntimeUserUUID, ".cache", true)
172         if err != nil {
173                 e.logf("error getting '.cache' project: %v", err)
174                 return nil
175         }
176         imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", true)
177         if err != nil {
178                 e.logf("error getting 'auto-generated singularity images' project: %v", err)
179                 return nil
180         }
181
182         parts := strings.Split(imageTarballPath, "/")
183         imageId := parts[len(parts)-1]
184         if strings.HasSuffix(imageId, ".tar") {
185                 imageId = imageId[0 : len(imageId)-4]
186         }
187
188         fs, err := (&arvados.Collection{ManifestText: ""}).FileSystem(e.containerClient, e.keepClient)
189         if err != nil {
190                 e.logf("error creating FileSystem: %s", err)
191         }
192
193         dst, err := fs.OpenFile("image.sif", os.O_CREATE|os.O_WRONLY, 0666)
194         if err != nil {
195                 e.logf("error creating opening collection file for writing: %s", err)
196         }
197
198         src, err := os.Open(e.imageFilename)
199         if err != nil {
200                 dst.Close()
201                 return nil
202         }
203         defer src.Close()
204         _, err = io.Copy(dst, src)
205         if err != nil {
206                 dst.Close()
207                 return nil
208         }
209
210         manifestText, err := fs.MarshalManifest(".")
211         if err != nil {
212                 e.logf("error creating manifest text: %s", err)
213         }
214
215         var imageCollection arvados.Collection
216         collectionName := fmt.Sprintf("singularity image for %s", imageId)
217         err = e.containerClient.RequestAndDecode(&imageCollection,
218                 arvados.EndpointCollectionCreate.Method,
219                 arvados.EndpointCollectionCreate.Path,
220                 nil, map[string]interface{}{
221                         "collection": map[string]string{
222                                 "owner_uuid":    imageGroup.UUID,
223                                 "name":          collectionName,
224                                 "manifest_text": manifestText,
225                         },
226                 })
227         if err != nil {
228                 e.logf("error creating '%v' collection: %s", collectionName, err)
229         }
230
231         return nil
232 }
233
234 func (e *singularityExecutor) Create(spec containerSpec) error {
235         e.spec = spec
236         return nil
237 }
238
239 func (e *singularityExecutor) Start() error {
240         args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
241         if !e.spec.EnableNetwork {
242                 args = append(args, "--net", "--network=none")
243         }
244         readonlyflag := map[bool]string{
245                 false: "rw",
246                 true:  "ro",
247         }
248         var binds []string
249         for path, _ := range e.spec.BindMounts {
250                 binds = append(binds, path)
251         }
252         sort.Strings(binds)
253         for _, path := range binds {
254                 mount := e.spec.BindMounts[path]
255                 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
256         }
257
258         // This is for singularity 3.5.2. There are some behaviors
259         // that will change in singularity 3.6, please see:
260         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
261         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
262         env := make([]string, 0, len(e.spec.Env))
263         for k, v := range e.spec.Env {
264                 if k == "HOME" {
265                         // $HOME is a special case
266                         args = append(args, "--home="+v)
267                 } else {
268                         env = append(env, "SINGULARITYENV_"+k+"="+v)
269                 }
270         }
271
272         args = append(args, e.imageFilename)
273         args = append(args, e.spec.Command...)
274
275         path, err := exec.LookPath(args[0])
276         if err != nil {
277                 return err
278         }
279         child := &exec.Cmd{
280                 Path:   path,
281                 Args:   args,
282                 Env:    env,
283                 Stdin:  e.spec.Stdin,
284                 Stdout: e.spec.Stdout,
285                 Stderr: e.spec.Stderr,
286         }
287         err = child.Start()
288         if err != nil {
289                 return err
290         }
291         e.child = child
292         return nil
293 }
294
295 func (e *singularityExecutor) CgroupID() string {
296         return ""
297 }
298
299 func (e *singularityExecutor) Stop() error {
300         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
301                 // process already exited
302                 return nil
303         }
304         return e.child.Process.Signal(syscall.SIGKILL)
305 }
306
307 func (e *singularityExecutor) Wait(context.Context) (int, error) {
308         err := e.child.Wait()
309         if err, ok := err.(*exec.ExitError); ok {
310                 return err.ProcessState.ExitCode(), nil
311         }
312         if err != nil {
313                 return 0, err
314         }
315         return e.child.ProcessState.ExitCode(), nil
316 }
317
318 func (e *singularityExecutor) Close() {
319         err := os.RemoveAll(e.tmpdir)
320         if err != nil {
321                 e.logf("error removing temp dir: %s", err)
322         }
323 }
324
325 func (e *singularityExecutor) SetArvadoClient(containerClient *arvados.Client, keepClient IKeepClient, container arvados.Container, keepMount string) {
326         e.containerClient = containerClient
327         e.container = container
328         e.keepClient = keepClient
329         e.keepMount = keepMount
330 }