64a3773250701ecd62832e52e88a5fcf8a2b3da2
[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) execCmd(path string) *exec.Cmd {
245         args := []string{path, "exec", "--containall", "--cleanenv", "--pwd", e.spec.WorkingDir}
246         if !e.spec.EnableNetwork {
247                 args = append(args, "--net", "--network=none")
248         }
249
250         if e.spec.CUDADeviceCount != 0 {
251                 args = append(args, "--nv")
252         }
253
254         readonlyflag := map[bool]string{
255                 false: "rw",
256                 true:  "ro",
257         }
258         var binds []string
259         for path, _ := range e.spec.BindMounts {
260                 binds = append(binds, path)
261         }
262         sort.Strings(binds)
263         for _, path := range binds {
264                 mount := e.spec.BindMounts[path]
265                 if path == e.spec.Env["HOME"] {
266                         // Singularity treates $HOME as special case
267                         args = append(args, "--home", mount.HostPath+":"+path)
268                 } else {
269                         args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
270                 }
271         }
272
273         // This is for singularity 3.5.2. There are some behaviors
274         // that will change in singularity 3.6, please see:
275         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
276         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
277         env := make([]string, 0, len(e.spec.Env))
278         for k, v := range e.spec.Env {
279                 if k == "HOME" {
280                         // Singularity treates $HOME as special case, this is handled
281                         // with --home above
282                         continue
283                 }
284                 env = append(env, "SINGULARITYENV_"+k+"="+v)
285         }
286
287         // Singularity always makes all nvidia devices visible to the
288         // container.  If a resource manager such as slurm or LSF told
289         // us to select specific devices we need to propagate that.
290         if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
291                 // If a resource manager such as slurm or LSF told
292                 // us to select specific devices we need to propagate that.
293                 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
294         }
295
296         args = append(args, e.imageFilename)
297         args = append(args, e.spec.Command...)
298
299         return &exec.Cmd{
300                 Path:   path,
301                 Args:   args,
302                 Env:    env,
303                 Stdin:  e.spec.Stdin,
304                 Stdout: e.spec.Stdout,
305                 Stderr: e.spec.Stderr,
306         }
307 }
308
309 func (e *singularityExecutor) Start() error {
310         path, err := exec.LookPath("singularity")
311         if err != nil {
312                 return err
313         }
314         child := e.execCmd(path)
315         err = child.Start()
316         if err != nil {
317                 return err
318         }
319         e.child = child
320         return nil
321 }
322
323 func (e *singularityExecutor) CgroupID() string {
324         return ""
325 }
326
327 func (e *singularityExecutor) Stop() error {
328         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
329                 // process already exited
330                 return nil
331         }
332         return e.child.Process.Signal(syscall.SIGKILL)
333 }
334
335 func (e *singularityExecutor) Wait(context.Context) (int, error) {
336         err := e.child.Wait()
337         if err, ok := err.(*exec.ExitError); ok {
338                 return err.ProcessState.ExitCode(), nil
339         }
340         if err != nil {
341                 return 0, err
342         }
343         return e.child.ProcessState.ExitCode(), nil
344 }
345
346 func (e *singularityExecutor) Close() {
347         err := os.RemoveAll(e.tmpdir)
348         if err != nil {
349                 e.logf("error removing temp dir: %s", err)
350         }
351 }