18258: also handle SINGULARITY_TMPDIR
[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                 // Set up a cache and tmp dir for singularity build
164                 err = os.Mkdir(e.tmpdir+"/cache", 0700)
165                 if err != nil {
166                         return err
167                 }
168                 defer os.RemoveAll(e.tmpdir + "/cache")
169                 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
170                 if err != nil {
171                         return err
172                 }
173                 defer os.RemoveAll(e.tmpdir + "/tmp")
174
175                 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
176                 build.Env = os.Environ()
177                 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
178                 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
179                 e.logf("%v", build.Args)
180                 out, err := build.CombinedOutput()
181                 // INFO:    Starting build...
182                 // Getting image source signatures
183                 // Copying blob ab15617702de done
184                 // Copying config 651e02b8a2 done
185                 // Writing manifest to image destination
186                 // Storing signatures
187                 // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
188                 // INFO:    Creating SIF file...
189                 // INFO:    Build complete: arvados-jobs.latest.sif
190                 e.logf("%s", out)
191                 if err != nil {
192                         return err
193                 }
194         }
195
196         if containerClient == nil {
197                 e.imageFilename = imageFilename
198                 return nil
199         }
200
201         // update TTL to now + two weeks
202         exp := time.Now().Add(24 * 7 * 2 * time.Hour)
203
204         uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
205         if err != nil {
206                 e.logf("error PathForUUID: %v", err)
207                 return nil
208         }
209         var imageCollection arvados.Collection
210         err = containerClient.RequestAndDecode(&imageCollection,
211                 arvados.EndpointCollectionUpdate.Method,
212                 uuidPath,
213                 nil, map[string]interface{}{
214                         "collection": map[string]string{
215                                 "name":     fmt.Sprintf("singularity image for %v", dockerImageID),
216                                 "trash_at": exp.UTC().Format(time.RFC3339),
217                         },
218                 })
219         if err == nil {
220                 // If we just wrote the image to the cache, the
221                 // response also returns the updated PDH
222                 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
223                 return nil
224         }
225
226         e.logf("error updating/renaming collection for cached sif image: %v", err)
227         // Failed to update but maybe it lost a race and there is
228         // another cached collection in the same place, so check the cache
229         // again
230         sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
231         if err != nil {
232                 return err
233         }
234         e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
235
236         return nil
237 }
238
239 func (e *singularityExecutor) Create(spec containerSpec) error {
240         e.spec = spec
241         return nil
242 }
243
244 func (e *singularityExecutor) Start() error {
245         args := []string{"singularity", "exec", "--containall", "--cleanenv", "--pwd", e.spec.WorkingDir}
246         if !e.spec.EnableNetwork {
247                 args = append(args, "--net", "--network=none")
248         }
249         readonlyflag := map[bool]string{
250                 false: "rw",
251                 true:  "ro",
252         }
253         var binds []string
254         for path, _ := range e.spec.BindMounts {
255                 binds = append(binds, path)
256         }
257         sort.Strings(binds)
258         for _, path := range binds {
259                 mount := e.spec.BindMounts[path]
260                 if path == e.spec.Env["HOME"] {
261                         // Singularity treates $HOME as special case
262                         args = append(args, "--home", mount.HostPath+":"+path)
263                 } else {
264                         args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
265                 }
266         }
267
268         // This is for singularity 3.5.2. There are some behaviors
269         // that will change in singularity 3.6, please see:
270         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
271         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
272         env := make([]string, 0, len(e.spec.Env))
273         for k, v := range e.spec.Env {
274                 if k == "HOME" {
275                         // Singularity treates $HOME as special case, this is handled
276                         // with --home above
277                         continue
278                 }
279                 env = append(env, "SINGULARITYENV_"+k+"="+v)
280         }
281
282         args = append(args, e.imageFilename)
283         args = append(args, e.spec.Command...)
284
285         path, err := exec.LookPath(args[0])
286         if err != nil {
287                 return err
288         }
289         child := &exec.Cmd{
290                 Path:   path,
291                 Args:   args,
292                 Env:    env,
293                 Stdin:  e.spec.Stdin,
294                 Stdout: e.spec.Stdout,
295                 Stderr: e.spec.Stderr,
296         }
297         err = child.Start()
298         if err != nil {
299                 return err
300         }
301         e.child = child
302         return nil
303 }
304
305 func (e *singularityExecutor) CgroupID() string {
306         return ""
307 }
308
309 func (e *singularityExecutor) Stop() error {
310         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
311                 // process already exited
312                 return nil
313         }
314         return e.child.Process.Signal(syscall.SIGKILL)
315 }
316
317 func (e *singularityExecutor) Wait(context.Context) (int, error) {
318         err := e.child.Wait()
319         if err, ok := err.(*exec.ExitError); ok {
320                 return err.ProcessState.ExitCode(), nil
321         }
322         if err != nil {
323                 return 0, err
324         }
325         return e.child.ProcessState.ExitCode(), nil
326 }
327
328 func (e *singularityExecutor) Close() {
329         err := os.RemoveAll(e.tmpdir)
330         if err != nil {
331                 e.logf("error removing temp dir: %s", err)
332         }
333 }