18258: set the SINGULARITY_CACHEDIR to a path underneath our temporary
[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/ioutil"
10         "os"
11         "os/exec"
12         "sort"
13         "syscall"
14         "time"
15
16         "git.arvados.org/arvados.git/sdk/go/arvados"
17         "golang.org/x/net/context"
18 )
19
20 type singularityExecutor struct {
21         logf          func(string, ...interface{})
22         spec          containerSpec
23         tmpdir        string
24         child         *exec.Cmd
25         imageFilename string // "sif" image
26 }
27
28 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
29         tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
30         if err != nil {
31                 return nil, err
32         }
33         return &singularityExecutor{
34                 logf:   logf,
35                 tmpdir: tmpdir,
36         }, nil
37 }
38
39 func (e *singularityExecutor) Runtime() string { return "singularity" }
40
41 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
42         var gp arvados.GroupList
43         err := containerClient.RequestAndDecode(&gp,
44                 arvados.EndpointGroupList.Method,
45                 arvados.EndpointGroupList.Path,
46                 nil, arvados.ListOptions{Filters: []arvados.Filter{
47                         arvados.Filter{"owner_uuid", "=", ownerUuid},
48                         arvados.Filter{"name", "=", name},
49                         arvados.Filter{"group_class", "=", "project"},
50                 },
51                         Limit: 1})
52         if err != nil {
53                 return nil, err
54         }
55         if len(gp.Items) == 1 {
56                 return &gp.Items[0], nil
57         }
58
59         var rgroup arvados.Group
60         err = containerClient.RequestAndDecode(&rgroup,
61                 arvados.EndpointGroupCreate.Method,
62                 arvados.EndpointGroupCreate.Path,
63                 nil, map[string]interface{}{
64                         "group": map[string]string{
65                                 "owner_uuid":  ownerUuid,
66                                 "name":        name,
67                                 "group_class": "project",
68                         },
69                 })
70         if err != nil {
71                 return nil, err
72         }
73         return &rgroup, nil
74 }
75
76 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
77         containerClient *arvados.Client) (collection *arvados.Collection, err error) {
78
79         // Cache the image to keep
80         cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
81         if err != nil {
82                 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
83         }
84         imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
85         if err != nil {
86                 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
87         }
88
89         collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
90         var cl arvados.CollectionList
91         err = containerClient.RequestAndDecode(&cl,
92                 arvados.EndpointCollectionList.Method,
93                 arvados.EndpointCollectionList.Path,
94                 nil, arvados.ListOptions{Filters: []arvados.Filter{
95                         arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
96                         arvados.Filter{"name", "=", collectionName},
97                 },
98                         Limit: 1})
99         if err != nil {
100                 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
101         }
102         var imageCollection arvados.Collection
103         if len(cl.Items) == 1 {
104                 imageCollection = cl.Items[0]
105         } else {
106                 collectionName := "converting " + collectionName
107                 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
108                 err = containerClient.RequestAndDecode(&imageCollection,
109                         arvados.EndpointCollectionCreate.Method,
110                         arvados.EndpointCollectionCreate.Path,
111                         nil, map[string]interface{}{
112                                 "collection": map[string]string{
113                                         "owner_uuid": imageGroup.UUID,
114                                         "name":       collectionName,
115                                         "trash_at":   exp.UTC().Format(time.RFC3339),
116                                 },
117                                 "ensure_unique_name": true,
118                         })
119                 if err != nil {
120                         return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
121                 }
122
123         }
124
125         return &imageCollection, nil
126 }
127
128 // LoadImage will satisfy ContainerExecuter interface transforming
129 // containerImage into a sif file for later use.
130 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
131         containerClient *arvados.Client) error {
132
133         var imageFilename string
134         var sifCollection *arvados.Collection
135         var err error
136         if containerClient != nil {
137                 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
138                 if err != nil {
139                         return err
140                 }
141                 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
142         } else {
143                 imageFilename = e.tmpdir + "/image.sif"
144         }
145
146         if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
147                 // Make sure the docker image is readable, and error
148                 // out if not.
149                 if _, err := os.Stat(imageTarballPath); err != nil {
150                         return err
151                 }
152
153                 e.logf("building singularity image")
154                 // "singularity build" does not accept a
155                 // docker-archive://... filename containing a ":" character,
156                 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
157                 // symlink that doesn't have ":" chars.
158                 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
159                 if err != nil {
160                         return err
161                 }
162
163                 os.Mkdir(e.tmpdir+"/cache", 0700)
164                 defer os.RemoveAll(e.tmpdir + "/cache")
165
166                 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
167                 build.Env = os.Environ()
168                 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
169                 e.logf("%v", build.Args)
170                 out, err := build.CombinedOutput()
171                 // INFO:    Starting build...
172                 // Getting image source signatures
173                 // Copying blob ab15617702de done
174                 // Copying config 651e02b8a2 done
175                 // Writing manifest to image destination
176                 // Storing signatures
177                 // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
178                 // INFO:    Creating SIF file...
179                 // INFO:    Build complete: arvados-jobs.latest.sif
180                 e.logf("%s", out)
181                 if err != nil {
182                         return err
183                 }
184         }
185
186         if containerClient == nil {
187                 e.imageFilename = imageFilename
188                 return nil
189         }
190
191         // update TTL to now + two weeks
192         exp := time.Now().Add(24 * 7 * 2 * time.Hour)
193
194         uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
195         if err != nil {
196                 e.logf("error PathForUUID: %v", err)
197                 return nil
198         }
199         var imageCollection arvados.Collection
200         err = containerClient.RequestAndDecode(&imageCollection,
201                 arvados.EndpointCollectionUpdate.Method,
202                 uuidPath,
203                 nil, map[string]interface{}{
204                         "collection": map[string]string{
205                                 "name":     fmt.Sprintf("singularity image for %v", dockerImageID),
206                                 "trash_at": exp.UTC().Format(time.RFC3339),
207                         },
208                 })
209         if err == nil {
210                 // If we just wrote the image to the cache, the
211                 // response also returns the updated PDH
212                 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
213                 return nil
214         }
215
216         e.logf("error updating/renaming collection for cached sif image: %v", err)
217         // Failed to update but maybe it lost a race and there is
218         // another cached collection in the same place, so check the cache
219         // again
220         sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
221         if err != nil {
222                 return err
223         }
224         e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
225
226         return nil
227 }
228
229 func (e *singularityExecutor) Create(spec containerSpec) error {
230         e.spec = spec
231         return nil
232 }
233
234 func (e *singularityExecutor) Start() error {
235         args := []string{"singularity", "exec", "--containall", "--cleanenv", "--pwd", e.spec.WorkingDir}
236         if !e.spec.EnableNetwork {
237                 args = append(args, "--net", "--network=none")
238         }
239         readonlyflag := map[bool]string{
240                 false: "rw",
241                 true:  "ro",
242         }
243         var binds []string
244         for path, _ := range e.spec.BindMounts {
245                 binds = append(binds, path)
246         }
247         sort.Strings(binds)
248         for _, path := range binds {
249                 mount := e.spec.BindMounts[path]
250                 if path == e.spec.Env["HOME"] {
251                         // Singularity treates $HOME as special case
252                         args = append(args, "--home", mount.HostPath+":"+path)
253                 } else {
254                         args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
255                 }
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                         // Singularity treates $HOME as special case, this is handled
266                         // with --home above
267                         continue
268                 }
269                 env = append(env, "SINGULARITYENV_"+k+"="+v)
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 }