Merge branch '15159-export-trustallcontent' into main. Closes #15159
[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) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
40         var gp arvados.GroupList
41         err := containerClient.RequestAndDecode(&gp,
42                 arvados.EndpointGroupList.Method,
43                 arvados.EndpointGroupList.Path,
44                 nil, arvados.ListOptions{Filters: []arvados.Filter{
45                         arvados.Filter{"owner_uuid", "=", ownerUuid},
46                         arvados.Filter{"name", "=", name},
47                         arvados.Filter{"group_class", "=", "project"},
48                 },
49                         Limit: 1})
50         if err != nil {
51                 return nil, err
52         }
53         if len(gp.Items) == 1 {
54                 return &gp.Items[0], nil
55         }
56
57         var rgroup arvados.Group
58         err = containerClient.RequestAndDecode(&rgroup,
59                 arvados.EndpointGroupCreate.Method,
60                 arvados.EndpointGroupCreate.Path,
61                 nil, map[string]interface{}{
62                         "group": map[string]string{
63                                 "owner_uuid":  ownerUuid,
64                                 "name":        name,
65                                 "group_class": "project",
66                         },
67                 })
68         if err != nil {
69                 return nil, err
70         }
71         return &rgroup, nil
72 }
73
74 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
75         containerClient *arvados.Client) (collection *arvados.Collection, err error) {
76
77         // Cache the image to keep
78         cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
79         if err != nil {
80                 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
81         }
82         imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
83         if err != nil {
84                 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
85         }
86
87         collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
88         var cl arvados.CollectionList
89         err = containerClient.RequestAndDecode(&cl,
90                 arvados.EndpointCollectionList.Method,
91                 arvados.EndpointCollectionList.Path,
92                 nil, arvados.ListOptions{Filters: []arvados.Filter{
93                         arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
94                         arvados.Filter{"name", "=", collectionName},
95                 },
96                         Limit: 1})
97         if err != nil {
98                 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
99         }
100         var imageCollection arvados.Collection
101         if len(cl.Items) == 1 {
102                 imageCollection = cl.Items[0]
103         } else {
104                 collectionName := "converting " + collectionName
105                 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
106                 err = containerClient.RequestAndDecode(&imageCollection,
107                         arvados.EndpointCollectionCreate.Method,
108                         arvados.EndpointCollectionCreate.Path,
109                         nil, map[string]interface{}{
110                                 "collection": map[string]string{
111                                         "owner_uuid": imageGroup.UUID,
112                                         "name":       collectionName,
113                                         "trash_at":   exp.UTC().Format(time.RFC3339),
114                                 },
115                                 "ensure_unique_name": true,
116                         })
117                 if err != nil {
118                         return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
119                 }
120
121         }
122
123         return &imageCollection, nil
124 }
125
126 // LoadImage will satisfy ContainerExecuter interface transforming
127 // containerImage into a sif file for later use.
128 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
129         containerClient *arvados.Client) error {
130
131         var imageFilename string
132         var sifCollection *arvados.Collection
133         var err error
134         if containerClient != nil {
135                 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
136                 if err != nil {
137                         return err
138                 }
139                 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
140         } else {
141                 imageFilename = e.tmpdir + "/image.sif"
142         }
143
144         if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
145                 // Make sure the docker image is readable, and error
146                 // out if not.
147                 if _, err := os.Stat(imageTarballPath); err != nil {
148                         return err
149                 }
150
151                 e.logf("building singularity image")
152                 // "singularity build" does not accept a
153                 // docker-archive://... filename containing a ":" character,
154                 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
155                 // symlink that doesn't have ":" chars.
156                 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
157                 if err != nil {
158                         return err
159                 }
160
161                 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
162                 e.logf("%v", build.Args)
163                 out, err := build.CombinedOutput()
164                 // INFO:    Starting build...
165                 // Getting image source signatures
166                 // Copying blob ab15617702de done
167                 // Copying config 651e02b8a2 done
168                 // Writing manifest to image destination
169                 // Storing signatures
170                 // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
171                 // INFO:    Creating SIF file...
172                 // INFO:    Build complete: arvados-jobs.latest.sif
173                 e.logf("%s", out)
174                 if err != nil {
175                         return err
176                 }
177         }
178
179         if containerClient == nil {
180                 e.imageFilename = imageFilename
181                 return nil
182         }
183
184         // update TTL to now + two weeks
185         exp := time.Now().Add(24 * 7 * 2 * time.Hour)
186
187         uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
188         if err != nil {
189                 e.logf("error PathForUUID: %v", err)
190                 return nil
191         }
192         var imageCollection arvados.Collection
193         err = containerClient.RequestAndDecode(&imageCollection,
194                 arvados.EndpointCollectionUpdate.Method,
195                 uuidPath,
196                 nil, map[string]interface{}{
197                         "collection": map[string]string{
198                                 "name":     fmt.Sprintf("singularity image for %v", dockerImageID),
199                                 "trash_at": exp.UTC().Format(time.RFC3339),
200                         },
201                 })
202         if err == nil {
203                 // If we just wrote the image to the cache, the
204                 // response also returns the updated PDH
205                 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
206                 return nil
207         }
208
209         e.logf("error updating/renaming collection for cached sif image: %v", err)
210         // Failed to update but maybe it lost a race and there is
211         // another cached collection in the same place, so check the cache
212         // again
213         sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
214         if err != nil {
215                 return err
216         }
217         e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
218
219         return nil
220 }
221
222 func (e *singularityExecutor) Create(spec containerSpec) error {
223         e.spec = spec
224         return nil
225 }
226
227 func (e *singularityExecutor) Start() error {
228         args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
229         if !e.spec.EnableNetwork {
230                 args = append(args, "--net", "--network=none")
231         }
232         readonlyflag := map[bool]string{
233                 false: "rw",
234                 true:  "ro",
235         }
236         var binds []string
237         for path, _ := range e.spec.BindMounts {
238                 binds = append(binds, path)
239         }
240         sort.Strings(binds)
241         for _, path := range binds {
242                 mount := e.spec.BindMounts[path]
243                 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
244         }
245
246         // This is for singularity 3.5.2. There are some behaviors
247         // that will change in singularity 3.6, please see:
248         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
249         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
250         env := make([]string, 0, len(e.spec.Env))
251         for k, v := range e.spec.Env {
252                 if k == "HOME" {
253                         // $HOME is a special case
254                         args = append(args, "--home="+v)
255                 } else {
256                         env = append(env, "SINGULARITYENV_"+k+"="+v)
257                 }
258         }
259
260         args = append(args, e.imageFilename)
261         args = append(args, e.spec.Command...)
262
263         path, err := exec.LookPath(args[0])
264         if err != nil {
265                 return err
266         }
267         child := &exec.Cmd{
268                 Path:   path,
269                 Args:   args,
270                 Env:    env,
271                 Stdin:  e.spec.Stdin,
272                 Stdout: e.spec.Stdout,
273                 Stderr: e.spec.Stderr,
274         }
275         err = child.Start()
276         if err != nil {
277                 return err
278         }
279         e.child = child
280         return nil
281 }
282
283 func (e *singularityExecutor) CgroupID() string {
284         return ""
285 }
286
287 func (e *singularityExecutor) Stop() error {
288         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
289                 // process already exited
290                 return nil
291         }
292         return e.child.Process.Signal(syscall.SIGKILL)
293 }
294
295 func (e *singularityExecutor) Wait(context.Context) (int, error) {
296         err := e.child.Wait()
297         if err, ok := err.(*exec.ExitError); ok {
298                 return err.ProcessState.ExitCode(), nil
299         }
300         if err != nil {
301                 return 0, err
302         }
303         return e.child.ProcessState.ExitCode(), nil
304 }
305
306 func (e *singularityExecutor) Close() {
307         err := os.RemoveAll(e.tmpdir)
308         if err != nil {
309                 e.logf("error removing temp dir: %s", err)
310         }
311 }