1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "golang.org/x/net/context"
27 type singularityExecutor struct {
28 logf func(string, ...interface{})
29 fakeroot bool // use --fakeroot flag, allow --network=bridge when non-root (currently only used by tests)
33 imageFilename string // "sif" image
36 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
37 tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
41 return &singularityExecutor{
47 func (e *singularityExecutor) Runtime() string {
48 buf, err := exec.Command("singularity", "--version").CombinedOutput()
50 return "singularity (unknown version)"
52 return strings.TrimSuffix(string(buf), "\n")
55 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
56 var gp arvados.GroupList
57 err := containerClient.RequestAndDecode(&gp,
58 arvados.EndpointGroupList.Method,
59 arvados.EndpointGroupList.Path,
60 nil, arvados.ListOptions{Filters: []arvados.Filter{
61 arvados.Filter{"owner_uuid", "=", ownerUuid},
62 arvados.Filter{"name", "=", name},
63 arvados.Filter{"group_class", "=", "project"},
69 if len(gp.Items) == 1 {
70 return &gp.Items[0], nil
73 var rgroup arvados.Group
74 err = containerClient.RequestAndDecode(&rgroup,
75 arvados.EndpointGroupCreate.Method,
76 arvados.EndpointGroupCreate.Path,
77 nil, map[string]interface{}{
78 "group": map[string]string{
79 "owner_uuid": ownerUuid,
81 "group_class": "project",
90 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
91 containerClient *arvados.Client) (collection *arvados.Collection, err error) {
93 // Cache the image to keep
94 cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
96 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
98 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
100 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
103 collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
104 var cl arvados.CollectionList
105 err = containerClient.RequestAndDecode(&cl,
106 arvados.EndpointCollectionList.Method,
107 arvados.EndpointCollectionList.Path,
108 nil, arvados.ListOptions{Filters: []arvados.Filter{
109 arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
110 arvados.Filter{"name", "=", collectionName},
114 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
116 var imageCollection arvados.Collection
117 if len(cl.Items) == 1 {
118 imageCollection = cl.Items[0]
120 collectionName := "converting " + collectionName
121 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
122 err = containerClient.RequestAndDecode(&imageCollection,
123 arvados.EndpointCollectionCreate.Method,
124 arvados.EndpointCollectionCreate.Path,
125 nil, map[string]interface{}{
126 "collection": map[string]string{
127 "owner_uuid": imageGroup.UUID,
128 "name": collectionName,
129 "trash_at": exp.UTC().Format(time.RFC3339),
131 "ensure_unique_name": true,
134 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
139 return &imageCollection, nil
142 // LoadImage will satisfy ContainerExecuter interface transforming
143 // containerImage into a sif file for later use.
144 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
145 containerClient *arvados.Client) error {
147 var imageFilename string
148 var sifCollection *arvados.Collection
150 if containerClient != nil {
151 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
155 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
157 imageFilename = e.tmpdir + "/image.sif"
160 if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
161 // Make sure the docker image is readable, and error
163 if _, err := os.Stat(imageTarballPath); err != nil {
167 e.logf("building singularity image")
168 // "singularity build" does not accept a
169 // docker-archive://... filename containing a ":" character,
170 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
171 // symlink that doesn't have ":" chars.
172 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
177 // Set up a cache and tmp dir for singularity build
178 err = os.Mkdir(e.tmpdir+"/cache", 0700)
182 defer os.RemoveAll(e.tmpdir + "/cache")
183 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
187 defer os.RemoveAll(e.tmpdir + "/tmp")
189 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
190 build.Env = os.Environ()
191 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
192 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
193 e.logf("%v", build.Args)
194 out, err := build.CombinedOutput()
195 // INFO: Starting build...
196 // Getting image source signatures
197 // Copying blob ab15617702de done
198 // Copying config 651e02b8a2 done
199 // Writing manifest to image destination
200 // Storing signatures
201 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
202 // INFO: Creating SIF file...
203 // INFO: Build complete: arvados-jobs.latest.sif
210 if containerClient == nil {
211 e.imageFilename = imageFilename
215 // update TTL to now + two weeks
216 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
218 uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
220 e.logf("error PathForUUID: %v", err)
223 var imageCollection arvados.Collection
224 err = containerClient.RequestAndDecode(&imageCollection,
225 arvados.EndpointCollectionUpdate.Method,
227 nil, map[string]interface{}{
228 "collection": map[string]string{
229 "name": fmt.Sprintf("singularity image for %v", dockerImageID),
230 "trash_at": exp.UTC().Format(time.RFC3339),
234 // If we just wrote the image to the cache, the
235 // response also returns the updated PDH
236 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
240 e.logf("error updating/renaming collection for cached sif image: %v", err)
241 // Failed to update but maybe it lost a race and there is
242 // another cached collection in the same place, so check the cache
244 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
248 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
253 func (e *singularityExecutor) Create(spec containerSpec) error {
258 func (e *singularityExecutor) execCmd(path string) *exec.Cmd {
259 args := []string{path, "exec", "--containall", "--cleanenv", "--pwd=" + e.spec.WorkingDir}
261 args = append(args, "--fakeroot")
263 if !e.spec.EnableNetwork {
264 args = append(args, "--net", "--network=none")
265 } else if u, err := user.Current(); err == nil && u.Uid == "0" || e.fakeroot {
266 // Specifying --network=bridge fails unless (a) we are
267 // root, (b) we are using --fakeroot, or (c)
268 // singularity has been configured to allow our
269 // uid/gid to use it like so:
271 // singularity config global --set 'allow net networks' bridge
272 // singularity config global --set 'allow net groups' mygroup
273 args = append(args, "--net", "--network=bridge")
275 if e.spec.CUDADeviceCount != 0 {
276 args = append(args, "--nv")
279 readonlyflag := map[bool]string{
284 for path, _ := range e.spec.BindMounts {
285 binds = append(binds, path)
288 for _, path := range binds {
289 mount := e.spec.BindMounts[path]
290 if path == e.spec.Env["HOME"] {
291 // Singularity treats $HOME as special case
292 args = append(args, "--home", mount.HostPath+":"+path)
294 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
298 // This is for singularity 3.5.2. There are some behaviors
299 // that will change in singularity 3.6, please see:
300 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
301 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
302 env := make([]string, 0, len(e.spec.Env))
303 for k, v := range e.spec.Env {
305 // Singularity treats $HOME as special case,
306 // this is handled with --home above
309 env = append(env, "SINGULARITYENV_"+k+"="+v)
312 // Singularity always makes all nvidia devices visible to the
313 // container. If a resource manager such as slurm or LSF told
314 // us to select specific devices we need to propagate that.
315 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
316 // If a resource manager such as slurm or LSF told
317 // us to select specific devices we need to propagate that.
318 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
320 // Singularity's default behavior is to evaluate each
321 // SINGULARITYENV_* env var with a shell as a double-quoted
322 // string and pass the result to the contained
323 // process. Singularity 3.10+ has an option to pass env vars
324 // through literally without evaluating, which is what we
325 // want. See https://github.com/sylabs/singularity/pull/704
326 // and https://dev.arvados.org/issues/19081
327 env = append(env, "SINGULARITY_NO_EVAL=1")
329 args = append(args, e.imageFilename)
330 args = append(args, e.spec.Command...)
337 Stdout: e.spec.Stdout,
338 Stderr: e.spec.Stderr,
342 func (e *singularityExecutor) Start() error {
343 path, err := exec.LookPath("singularity")
347 child := e.execCmd(path)
356 func (e *singularityExecutor) CgroupID() string {
360 func (e *singularityExecutor) Stop() error {
361 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
362 // process already exited
365 return e.child.Process.Signal(syscall.SIGKILL)
368 func (e *singularityExecutor) Wait(context.Context) (int, error) {
369 err := e.child.Wait()
370 if err, ok := err.(*exec.ExitError); ok {
371 return err.ProcessState.ExitCode(), nil
376 return e.child.ProcessState.ExitCode(), nil
379 func (e *singularityExecutor) Close() {
380 err := os.RemoveAll(e.tmpdir)
382 e.logf("error removing temp dir: %s", err)
386 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
387 target, err := e.containedProcess()
391 return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
395 errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
398 func (e *singularityExecutor) IPAddress() (string, error) {
399 target, err := e.containedProcess()
403 targetIPs, err := processIPs(target)
407 selfIPs, err := processIPs(os.Getpid())
411 for ip := range targetIPs {
416 return "", errContainerHasNoIPAddress
419 func processIPs(pid int) (map[string]bool, error) {
420 fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
425 addrs := map[string]bool{}
426 // When we see a pair of lines like this:
431 // ...we set addrs["10.1.2.3"] = true
432 lines := bytes.Split(fibtrie, []byte{'\n'})
433 for linenumber, line := range lines {
434 if !bytes.HasSuffix(line, []byte("/32 host LOCAL")) {
440 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
441 if i < 0 || i >= len(line)-7 {
444 addr := string(lines[linenumber-1][i+1:])
445 if net.ParseIP(addr).To4() != nil {
453 errContainerNotStarted = errors.New("container has not started yet")
454 errCannotFindChild = errors.New("failed to find any process inside the container")
455 reProcStatusPPid = regexp.MustCompile(`\nPPid:\t(\d+)\n`)
458 // Return the PID of a process that is inside the container (not
459 // necessarily the topmost/pid=1 process in the container).
460 func (e *singularityExecutor) containedProcess() (int, error) {
461 if e.child == nil || e.child.Process == nil {
462 return 0, errContainerNotStarted
464 lsns, err := exec.Command("lsns").CombinedOutput()
466 return 0, fmt.Errorf("lsns: %w", err)
468 for _, line := range bytes.Split(lsns, []byte{'\n'}) {
469 fields := bytes.Fields(line)
473 if !bytes.Equal(fields[1], []byte("pid")) {
476 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
478 return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
480 for parent := pid; ; {
481 procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
485 m := reProcStatusPPid.FindSubmatch(procstatus)
489 parent, err = strconv.ParseInt(string(m[1]), 10, 64)
493 if int(parent) == e.child.Process.Pid {
498 return 0, errCannotFindChild