1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
24 "git.arvados.org/arvados.git/sdk/go/arvados"
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 // If we ask for resource limits that aren't supported,
280 // singularity will not run the container at all. So we probe
281 // for support first, and only apply the limits that appear to
284 // Default debian configuration lets non-root users set memory
285 // limits but not CPU limits, so we enable/disable those
286 // limits independently.
288 // https://rootlesscontaine.rs/getting-started/common/cgroup2/
289 checkCgroupSupport(e.logf)
290 if e.spec.VCPUs > 0 {
291 if cgroupSupport["cpu"] {
292 args = append(args, "--cpus", fmt.Sprintf("%d", e.spec.VCPUs))
294 e.logf("cpu limits are not supported by current systemd/cgroup configuration, not setting --cpu %d", e.spec.VCPUs)
298 if cgroupSupport["memory"] {
299 args = append(args, "--memory", fmt.Sprintf("%d", e.spec.RAM))
301 e.logf("memory limits are not supported by current systemd/cgroup configuration, not setting --memory %d", e.spec.RAM)
305 readonlyflag := map[bool]string{
310 for path, _ := range e.spec.BindMounts {
311 binds = append(binds, path)
314 for _, path := range binds {
315 mount := e.spec.BindMounts[path]
316 if path == e.spec.Env["HOME"] {
317 // Singularity treats $HOME as special case
318 args = append(args, "--home", mount.HostPath+":"+path)
320 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
324 // This is for singularity 3.5.2. There are some behaviors
325 // that will change in singularity 3.6, please see:
326 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
327 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
328 env := make([]string, 0, len(e.spec.Env))
329 for k, v := range e.spec.Env {
331 // Singularity treats $HOME as special case,
332 // this is handled with --home above
335 env = append(env, "SINGULARITYENV_"+k+"="+v)
338 // Singularity always makes all nvidia devices visible to the
339 // container. If a resource manager such as slurm or LSF told
340 // us to select specific devices we need to propagate that.
341 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
342 // If a resource manager such as slurm or LSF told
343 // us to select specific devices we need to propagate that.
344 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
346 // Singularity's default behavior is to evaluate each
347 // SINGULARITYENV_* env var with a shell as a double-quoted
348 // string and pass the result to the contained
349 // process. Singularity 3.10+ has an option to pass env vars
350 // through literally without evaluating, which is what we
351 // want. See https://github.com/sylabs/singularity/pull/704
352 // and https://dev.arvados.org/issues/19081
353 env = append(env, "SINGULARITY_NO_EVAL=1")
355 // If we don't propagate XDG_RUNTIME_DIR and
356 // DBUS_SESSION_BUS_ADDRESS, singularity resource limits fail
357 // with "FATAL: container creation failed: while applying
358 // cgroups config: system configuration does not support
359 // cgroup management" or "FATAL: container creation failed:
360 // while applying cgroups config: rootless cgroups require a
361 // D-Bus session - check that XDG_RUNTIME_DIR and
362 // DBUS_SESSION_BUS_ADDRESS are set".
363 env = append(env, "XDG_RUNTIME_DIR="+os.Getenv("XDG_RUNTIME_DIR"))
364 env = append(env, "DBUS_SESSION_BUS_ADDRESS="+os.Getenv("DBUS_SESSION_BUS_ADDRESS"))
366 args = append(args, e.imageFilename)
367 args = append(args, e.spec.Command...)
374 Stdout: e.spec.Stdout,
375 Stderr: e.spec.Stderr,
379 func (e *singularityExecutor) Start() error {
380 path, err := exec.LookPath("singularity")
384 child := e.execCmd(path)
393 func (e *singularityExecutor) Pid() int {
394 childproc, err := e.containedProcess()
401 func (e *singularityExecutor) Stop() error {
402 if e.child == nil || e.child.Process == nil {
403 // no process started, or Wait already called
406 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
407 // process already exited
410 return e.child.Process.Signal(syscall.SIGKILL)
413 func (e *singularityExecutor) Wait(context.Context) (int, error) {
414 err := e.child.Wait()
415 if err, ok := err.(*exec.ExitError); ok {
416 return err.ProcessState.ExitCode(), nil
421 return e.child.ProcessState.ExitCode(), nil
424 func (e *singularityExecutor) Close() {
425 err := os.RemoveAll(e.tmpdir)
427 e.logf("error removing temp dir: %s", err)
431 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
432 target, err := e.containedProcess()
436 return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
440 errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
443 func (e *singularityExecutor) IPAddress() (string, error) {
444 target, err := e.containedProcess()
448 targetIPs, err := processIPs(target)
452 selfIPs, err := processIPs(os.Getpid())
456 for ip := range targetIPs {
461 return "", errContainerHasNoIPAddress
464 func processIPs(pid int) (map[string]bool, error) {
465 fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
470 addrs := map[string]bool{}
471 // When we see a pair of lines like this:
476 // ...we set addrs["10.1.2.3"] = true
477 lines := bytes.Split(fibtrie, []byte{'\n'})
478 for linenumber, line := range lines {
479 if !bytes.HasSuffix(line, []byte("/32 host LOCAL")) {
485 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
486 if i < 0 || i >= len(line)-7 {
489 addr := string(lines[linenumber-1][i+1:])
490 if net.ParseIP(addr).To4() != nil {
498 errContainerNotStarted = errors.New("container has not started yet")
499 errCannotFindChild = errors.New("failed to find any process inside the container")
500 reProcStatusPPid = regexp.MustCompile(`\nPPid:\t(\d+)\n`)
503 // Return the PID of a process that is inside the container (not
504 // necessarily the topmost/pid=1 process in the container).
505 func (e *singularityExecutor) containedProcess() (int, error) {
506 if e.child == nil || e.child.Process == nil {
507 return 0, errContainerNotStarted
509 lsns, err := exec.Command("lsns").CombinedOutput()
511 return 0, fmt.Errorf("lsns: %w", err)
513 for _, line := range bytes.Split(lsns, []byte{'\n'}) {
514 fields := bytes.Fields(line)
518 if !bytes.Equal(fields[1], []byte("pid")) {
521 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
523 return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
525 for parent := pid; ; {
526 procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
530 m := reProcStatusPPid.FindSubmatch(procstatus)
534 parent, err = strconv.ParseInt(string(m[1]), 10, 64)
538 if int(parent) == e.child.Process.Pid {
543 return 0, errCannotFindChild