17813: continue refactor & fix tests
[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) (collectionUuid string, err error) {
76
77         // Cache the image to keep
78         cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
79         if err != nil {
80                 return "", 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 "", 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 "", 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
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                                 },
114                         })
115                 if err != nil {
116                         e.logf("error creating '%v' collection: %s", collectionName, err)
117                 }
118
119         }
120
121         return imageCollection.UUID, nil
122 }
123
124 // LoadImage will satisfy ContainerExecuter interface transforming
125 // containerImage into a sif file for later use.
126 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
127         containerClient *arvados.Client) error {
128
129         var sifCollectionUUID string
130         var imageFilename string
131         if containerClient != nil {
132                 sifCollectionUUID, err := e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
133                 if err != nil {
134                         return err
135                 }
136                 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollectionUUID)
137         } else {
138                 imageFilename = e.tmpdir + "/image.sif"
139         }
140
141         if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
142                 exec.Command("find", arvMountPoint+"/by_id/").Run()
143
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", sifCollectionUUID)
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                 e.logf("error updating collection trash_at: %v", err)
197         }
198         e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
199
200         return nil
201 }
202
203 func (e *singularityExecutor) Create(spec containerSpec) error {
204         e.spec = spec
205         return nil
206 }
207
208 func (e *singularityExecutor) Start() error {
209         args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
210         if !e.spec.EnableNetwork {
211                 args = append(args, "--net", "--network=none")
212         }
213         readonlyflag := map[bool]string{
214                 false: "rw",
215                 true:  "ro",
216         }
217         var binds []string
218         for path, _ := range e.spec.BindMounts {
219                 binds = append(binds, path)
220         }
221         sort.Strings(binds)
222         for _, path := range binds {
223                 mount := e.spec.BindMounts[path]
224                 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
225         }
226
227         // This is for singularity 3.5.2. There are some behaviors
228         // that will change in singularity 3.6, please see:
229         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
230         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
231         env := make([]string, 0, len(e.spec.Env))
232         for k, v := range e.spec.Env {
233                 if k == "HOME" {
234                         // $HOME is a special case
235                         args = append(args, "--home="+v)
236                 } else {
237                         env = append(env, "SINGULARITYENV_"+k+"="+v)
238                 }
239         }
240
241         args = append(args, e.imageFilename)
242         args = append(args, e.spec.Command...)
243
244         path, err := exec.LookPath(args[0])
245         if err != nil {
246                 return err
247         }
248         child := &exec.Cmd{
249                 Path:   path,
250                 Args:   args,
251                 Env:    env,
252                 Stdin:  e.spec.Stdin,
253                 Stdout: e.spec.Stdout,
254                 Stderr: e.spec.Stderr,
255         }
256         err = child.Start()
257         if err != nil {
258                 return err
259         }
260         e.child = child
261         return nil
262 }
263
264 func (e *singularityExecutor) CgroupID() string {
265         return ""
266 }
267
268 func (e *singularityExecutor) Stop() error {
269         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
270                 // process already exited
271                 return nil
272         }
273         return e.child.Process.Signal(syscall.SIGKILL)
274 }
275
276 func (e *singularityExecutor) Wait(context.Context) (int, error) {
277         err := e.child.Wait()
278         if err, ok := err.(*exec.ExitError); ok {
279                 return err.ProcessState.ExitCode(), nil
280         }
281         if err != nil {
282                 return 0, err
283         }
284         return e.child.ProcessState.ExitCode(), nil
285 }
286
287 func (e *singularityExecutor) Close() {
288         err := os.RemoveAll(e.tmpdir)
289         if err != nil {
290                 e.logf("error removing temp dir: %s", err)
291         }
292 }