Merge branch '16665-keepproxy-spurious-413-status' into main. Closes #16665
[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 := collectionName + " " + time.Now().UTC().Format(time.RFC3339)
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                         })
116                 if err != nil {
117                         return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
118                 }
119
120         }
121
122         return &imageCollection, nil
123 }
124
125 // LoadImage will satisfy ContainerExecuter interface transforming
126 // containerImage into a sif file for later use.
127 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
128         containerClient *arvados.Client) error {
129
130         var imageFilename string
131         var sifCollection *arvados.Collection
132         var err error
133         if containerClient != nil {
134                 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
135                 if err != nil {
136                         return err
137                 }
138                 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
139         } else {
140                 imageFilename = e.tmpdir + "/image.sif"
141         }
142
143         if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
144                 e.logf("building singularity image")
145                 // "singularity build" does not accept a
146                 // docker-archive://... filename containing a ":" character,
147                 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
148                 // symlink that doesn't have ":" chars.
149                 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
150                 if err != nil {
151                         return err
152                 }
153
154                 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
155                 e.logf("%v", build.Args)
156                 out, err := build.CombinedOutput()
157                 // INFO:    Starting build...
158                 // Getting image source signatures
159                 // Copying blob ab15617702de done
160                 // Copying config 651e02b8a2 done
161                 // Writing manifest to image destination
162                 // Storing signatures
163                 // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
164                 // INFO:    Creating SIF file...
165                 // INFO:    Build complete: arvados-jobs.latest.sif
166                 e.logf("%s", out)
167                 if err != nil {
168                         return err
169                 }
170         }
171
172         if containerClient == nil {
173                 e.imageFilename = imageFilename
174                 return nil
175         }
176
177         // update TTL to now + two weeks
178         exp := time.Now().Add(24 * 7 * 2 * time.Hour)
179
180         uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
181         if err != nil {
182                 e.logf("error PathForUUID: %v", err)
183                 return nil
184         }
185         var imageCollection arvados.Collection
186         err = containerClient.RequestAndDecode(&imageCollection,
187                 arvados.EndpointCollectionUpdate.Method,
188                 uuidPath,
189                 nil, map[string]interface{}{
190                         "collection": map[string]string{
191                                 "name":     fmt.Sprintf("singularity image for %v", dockerImageID),
192                                 "trash_at": exp.UTC().Format(time.RFC3339),
193                         },
194                 })
195         if err == nil {
196                 // If we just wrote the image to the cache, the
197                 // response also returns the updated PDH
198                 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
199                 return nil
200         }
201
202         e.logf("error updating/renaming collection for cached sif image: %v", err)
203         // Failed to update but maybe it lost a race and there is
204         // another cached collection in the same place, so check the cache
205         // again
206         sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
207         if err != nil {
208                 return err
209         }
210         e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
211
212         return nil
213 }
214
215 func (e *singularityExecutor) Create(spec containerSpec) error {
216         e.spec = spec
217         return nil
218 }
219
220 func (e *singularityExecutor) Start() error {
221         args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
222         if !e.spec.EnableNetwork {
223                 args = append(args, "--net", "--network=none")
224         }
225         readonlyflag := map[bool]string{
226                 false: "rw",
227                 true:  "ro",
228         }
229         var binds []string
230         for path, _ := range e.spec.BindMounts {
231                 binds = append(binds, path)
232         }
233         sort.Strings(binds)
234         for _, path := range binds {
235                 mount := e.spec.BindMounts[path]
236                 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
237         }
238
239         // This is for singularity 3.5.2. There are some behaviors
240         // that will change in singularity 3.6, please see:
241         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
242         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
243         env := make([]string, 0, len(e.spec.Env))
244         for k, v := range e.spec.Env {
245                 if k == "HOME" {
246                         // $HOME is a special case
247                         args = append(args, "--home="+v)
248                 } else {
249                         env = append(env, "SINGULARITYENV_"+k+"="+v)
250                 }
251         }
252
253         args = append(args, e.imageFilename)
254         args = append(args, e.spec.Command...)
255
256         path, err := exec.LookPath(args[0])
257         if err != nil {
258                 return err
259         }
260         child := &exec.Cmd{
261                 Path:   path,
262                 Args:   args,
263                 Env:    env,
264                 Stdin:  e.spec.Stdin,
265                 Stdout: e.spec.Stdout,
266                 Stderr: e.spec.Stderr,
267         }
268         err = child.Start()
269         if err != nil {
270                 return err
271         }
272         e.child = child
273         return nil
274 }
275
276 func (e *singularityExecutor) CgroupID() string {
277         return ""
278 }
279
280 func (e *singularityExecutor) Stop() error {
281         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
282                 // process already exited
283                 return nil
284         }
285         return e.child.Process.Signal(syscall.SIGKILL)
286 }
287
288 func (e *singularityExecutor) Wait(context.Context) (int, error) {
289         err := e.child.Wait()
290         if err, ok := err.(*exec.ExitError); ok {
291                 return err.ProcessState.ExitCode(), nil
292         }
293         if err != nil {
294                 return 0, err
295         }
296         return e.child.ProcessState.ExitCode(), nil
297 }
298
299 func (e *singularityExecutor) Close() {
300         err := os.RemoveAll(e.tmpdir)
301         if err != nil {
302                 e.logf("error removing temp dir: %s", err)
303         }
304 }