19099: Enable container shell when using singularity runtime.
[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         "bytes"
9         "errors"
10         "fmt"
11         "io/ioutil"
12         "net"
13         "os"
14         "os/exec"
15         "regexp"
16         "sort"
17         "strconv"
18         "syscall"
19         "time"
20
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22         "golang.org/x/net/context"
23 )
24
25 type singularityExecutor struct {
26         logf          func(string, ...interface{})
27         spec          containerSpec
28         tmpdir        string
29         child         *exec.Cmd
30         imageFilename string // "sif" image
31 }
32
33 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
34         tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
35         if err != nil {
36                 return nil, err
37         }
38         return &singularityExecutor{
39                 logf:   logf,
40                 tmpdir: tmpdir,
41         }, nil
42 }
43
44 func (e *singularityExecutor) Runtime() string { return "singularity" }
45
46 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
47         var gp arvados.GroupList
48         err := containerClient.RequestAndDecode(&gp,
49                 arvados.EndpointGroupList.Method,
50                 arvados.EndpointGroupList.Path,
51                 nil, arvados.ListOptions{Filters: []arvados.Filter{
52                         arvados.Filter{"owner_uuid", "=", ownerUuid},
53                         arvados.Filter{"name", "=", name},
54                         arvados.Filter{"group_class", "=", "project"},
55                 },
56                         Limit: 1})
57         if err != nil {
58                 return nil, err
59         }
60         if len(gp.Items) == 1 {
61                 return &gp.Items[0], nil
62         }
63
64         var rgroup arvados.Group
65         err = containerClient.RequestAndDecode(&rgroup,
66                 arvados.EndpointGroupCreate.Method,
67                 arvados.EndpointGroupCreate.Path,
68                 nil, map[string]interface{}{
69                         "group": map[string]string{
70                                 "owner_uuid":  ownerUuid,
71                                 "name":        name,
72                                 "group_class": "project",
73                         },
74                 })
75         if err != nil {
76                 return nil, err
77         }
78         return &rgroup, nil
79 }
80
81 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
82         containerClient *arvados.Client) (collection *arvados.Collection, err error) {
83
84         // Cache the image to keep
85         cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
86         if err != nil {
87                 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
88         }
89         imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
90         if err != nil {
91                 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
92         }
93
94         collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
95         var cl arvados.CollectionList
96         err = containerClient.RequestAndDecode(&cl,
97                 arvados.EndpointCollectionList.Method,
98                 arvados.EndpointCollectionList.Path,
99                 nil, arvados.ListOptions{Filters: []arvados.Filter{
100                         arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
101                         arvados.Filter{"name", "=", collectionName},
102                 },
103                         Limit: 1})
104         if err != nil {
105                 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
106         }
107         var imageCollection arvados.Collection
108         if len(cl.Items) == 1 {
109                 imageCollection = cl.Items[0]
110         } else {
111                 collectionName := "converting " + collectionName
112                 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
113                 err = containerClient.RequestAndDecode(&imageCollection,
114                         arvados.EndpointCollectionCreate.Method,
115                         arvados.EndpointCollectionCreate.Path,
116                         nil, map[string]interface{}{
117                                 "collection": map[string]string{
118                                         "owner_uuid": imageGroup.UUID,
119                                         "name":       collectionName,
120                                         "trash_at":   exp.UTC().Format(time.RFC3339),
121                                 },
122                                 "ensure_unique_name": true,
123                         })
124                 if err != nil {
125                         return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
126                 }
127
128         }
129
130         return &imageCollection, nil
131 }
132
133 // LoadImage will satisfy ContainerExecuter interface transforming
134 // containerImage into a sif file for later use.
135 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
136         containerClient *arvados.Client) error {
137
138         var imageFilename string
139         var sifCollection *arvados.Collection
140         var err error
141         if containerClient != nil {
142                 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
143                 if err != nil {
144                         return err
145                 }
146                 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
147         } else {
148                 imageFilename = e.tmpdir + "/image.sif"
149         }
150
151         if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
152                 // Make sure the docker image is readable, and error
153                 // out if not.
154                 if _, err := os.Stat(imageTarballPath); err != nil {
155                         return err
156                 }
157
158                 e.logf("building singularity image")
159                 // "singularity build" does not accept a
160                 // docker-archive://... filename containing a ":" character,
161                 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
162                 // symlink that doesn't have ":" chars.
163                 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
164                 if err != nil {
165                         return err
166                 }
167
168                 // Set up a cache and tmp dir for singularity build
169                 err = os.Mkdir(e.tmpdir+"/cache", 0700)
170                 if err != nil {
171                         return err
172                 }
173                 defer os.RemoveAll(e.tmpdir + "/cache")
174                 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
175                 if err != nil {
176                         return err
177                 }
178                 defer os.RemoveAll(e.tmpdir + "/tmp")
179
180                 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
181                 build.Env = os.Environ()
182                 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
183                 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
184                 e.logf("%v", build.Args)
185                 out, err := build.CombinedOutput()
186                 // INFO:    Starting build...
187                 // Getting image source signatures
188                 // Copying blob ab15617702de done
189                 // Copying config 651e02b8a2 done
190                 // Writing manifest to image destination
191                 // Storing signatures
192                 // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
193                 // INFO:    Creating SIF file...
194                 // INFO:    Build complete: arvados-jobs.latest.sif
195                 e.logf("%s", out)
196                 if err != nil {
197                         return err
198                 }
199         }
200
201         if containerClient == nil {
202                 e.imageFilename = imageFilename
203                 return nil
204         }
205
206         // update TTL to now + two weeks
207         exp := time.Now().Add(24 * 7 * 2 * time.Hour)
208
209         uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
210         if err != nil {
211                 e.logf("error PathForUUID: %v", err)
212                 return nil
213         }
214         var imageCollection arvados.Collection
215         err = containerClient.RequestAndDecode(&imageCollection,
216                 arvados.EndpointCollectionUpdate.Method,
217                 uuidPath,
218                 nil, map[string]interface{}{
219                         "collection": map[string]string{
220                                 "name":     fmt.Sprintf("singularity image for %v", dockerImageID),
221                                 "trash_at": exp.UTC().Format(time.RFC3339),
222                         },
223                 })
224         if err == nil {
225                 // If we just wrote the image to the cache, the
226                 // response also returns the updated PDH
227                 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
228                 return nil
229         }
230
231         e.logf("error updating/renaming collection for cached sif image: %v", err)
232         // Failed to update but maybe it lost a race and there is
233         // another cached collection in the same place, so check the cache
234         // again
235         sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
236         if err != nil {
237                 return err
238         }
239         e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
240
241         return nil
242 }
243
244 func (e *singularityExecutor) Create(spec containerSpec) error {
245         e.spec = spec
246         return nil
247 }
248
249 func (e *singularityExecutor) execCmd(path string) *exec.Cmd {
250         args := []string{path, "exec", "--containall", "--cleanenv", "--pwd", e.spec.WorkingDir, "--net"}
251         if !e.spec.EnableNetwork {
252                 args = append(args, "--network=none")
253         }
254         if e.spec.CUDADeviceCount != 0 {
255                 args = append(args, "--nv")
256         }
257
258         readonlyflag := map[bool]string{
259                 false: "rw",
260                 true:  "ro",
261         }
262         var binds []string
263         for path, _ := range e.spec.BindMounts {
264                 binds = append(binds, path)
265         }
266         sort.Strings(binds)
267         for _, path := range binds {
268                 mount := e.spec.BindMounts[path]
269                 if path == e.spec.Env["HOME"] {
270                         // Singularity treates $HOME as special case
271                         args = append(args, "--home", mount.HostPath+":"+path)
272                 } else {
273                         args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
274                 }
275         }
276
277         // This is for singularity 3.5.2. There are some behaviors
278         // that will change in singularity 3.6, please see:
279         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
280         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
281         env := make([]string, 0, len(e.spec.Env))
282         for k, v := range e.spec.Env {
283                 if k == "HOME" {
284                         // Singularity treates $HOME as special case, this is handled
285                         // with --home above
286                         continue
287                 }
288                 env = append(env, "SINGULARITYENV_"+k+"="+v)
289         }
290
291         // Singularity always makes all nvidia devices visible to the
292         // container.  If a resource manager such as slurm or LSF told
293         // us to select specific devices we need to propagate that.
294         if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
295                 // If a resource manager such as slurm or LSF told
296                 // us to select specific devices we need to propagate that.
297                 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
298         }
299
300         args = append(args, e.imageFilename)
301         args = append(args, e.spec.Command...)
302
303         return &exec.Cmd{
304                 Path:   path,
305                 Args:   args,
306                 Env:    env,
307                 Stdin:  e.spec.Stdin,
308                 Stdout: e.spec.Stdout,
309                 Stderr: e.spec.Stderr,
310         }
311 }
312
313 func (e *singularityExecutor) Start() error {
314         path, err := exec.LookPath("singularity")
315         if err != nil {
316                 return err
317         }
318         child := e.execCmd(path)
319         err = child.Start()
320         if err != nil {
321                 return err
322         }
323         e.child = child
324         return nil
325 }
326
327 func (e *singularityExecutor) CgroupID() string {
328         return ""
329 }
330
331 func (e *singularityExecutor) Stop() error {
332         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
333                 // process already exited
334                 return nil
335         }
336         return e.child.Process.Signal(syscall.SIGKILL)
337 }
338
339 func (e *singularityExecutor) Wait(context.Context) (int, error) {
340         err := e.child.Wait()
341         if err, ok := err.(*exec.ExitError); ok {
342                 return err.ProcessState.ExitCode(), nil
343         }
344         if err != nil {
345                 return 0, err
346         }
347         return e.child.ProcessState.ExitCode(), nil
348 }
349
350 func (e *singularityExecutor) Close() {
351         err := os.RemoveAll(e.tmpdir)
352         if err != nil {
353                 e.logf("error removing temp dir: %s", err)
354         }
355 }
356
357 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
358         target, err := e.containedProcess()
359         if err != nil {
360                 return nil, err
361         }
362         return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
363 }
364
365 var (
366         errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
367 )
368
369 func (e *singularityExecutor) IPAddress() (string, error) {
370         target, err := e.containedProcess()
371         if err != nil {
372                 return "", err
373         }
374         targetIPs, err := processIPs(target)
375         if err != nil {
376                 return "", err
377         }
378         selfIPs, err := processIPs(os.Getpid())
379         if err != nil {
380                 return "", err
381         }
382         for ip := range targetIPs {
383                 if !selfIPs[ip] {
384                         return ip, nil
385                 }
386         }
387         return "", errContainerHasNoIPAddress
388 }
389
390 func processIPs(pid int) (map[string]bool, error) {
391         fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
392         if err != nil {
393                 return nil, err
394         }
395
396         addrs := map[string]bool{}
397         // When we see a pair of lines like this:
398         //
399         //              |-- 10.1.2.3
400         //                 /32 host LOCAL
401         //
402         // ...we set addrs["10.1.2.3"] = true
403         lines := bytes.Split(fibtrie, []byte{'\n'})
404         for linenumber, line := range lines {
405                 if !bytes.HasSuffix(line, []byte("/32 host LOCAL")) {
406                         continue
407                 }
408                 if linenumber < 1 {
409                         continue
410                 }
411                 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
412                 if i < 0 || i >= len(line)-7 {
413                         continue
414                 }
415                 addr := string(lines[linenumber-1][i+1:])
416                 if net.ParseIP(addr).To4() != nil {
417                         addrs[addr] = true
418                 }
419         }
420         return addrs, nil
421 }
422
423 var (
424         errContainerNotStarted = errors.New("container has not started yet")
425         errCannotFindChild     = errors.New("failed to find any process inside the container")
426         reProcStatusPPid       = regexp.MustCompile(`\nPPid:\t(\d+)\n`)
427 )
428
429 // Return the PID of a process that is inside the container (not
430 // necessarily the topmost/pid=1 process in the container).
431 func (e *singularityExecutor) containedProcess() (int, error) {
432         if e.child == nil || e.child.Process == nil {
433                 return 0, errContainerNotStarted
434         }
435         lsns, err := exec.Command("lsns").CombinedOutput()
436         if err != nil {
437                 return 0, fmt.Errorf("lsns: %w", err)
438         }
439         for _, line := range bytes.Split(lsns, []byte{'\n'}) {
440                 fields := bytes.Fields(line)
441                 if len(fields) < 4 {
442                         continue
443                 }
444                 if !bytes.Equal(fields[1], []byte("pid")) {
445                         continue
446                 }
447                 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
448                 if err != nil {
449                         return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
450                 }
451                 for parent := pid; ; {
452                         procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
453                         if err != nil {
454                                 break
455                         }
456                         m := reProcStatusPPid.FindSubmatch(procstatus)
457                         if m == nil {
458                                 break
459                         }
460                         parent, err = strconv.ParseInt(string(m[1]), 10, 64)
461                         if err != nil {
462                                 break
463                         }
464                         if int(parent) == e.child.Process.Pid {
465                                 return int(pid), nil
466                         }
467                 }
468         }
469         return 0, errCannotFindChild
470 }