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