1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "golang.org/x/net/context"
26 type singularityExecutor struct {
27 logf func(string, ...interface{})
28 fakeroot bool // use --fakeroot flag, allow --network=bridge when non-root (currently only used by tests)
32 imageFilename string // "sif" image
35 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
36 tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
40 return &singularityExecutor{
46 func (e *singularityExecutor) Runtime() string { return "singularity" }
48 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
49 var gp arvados.GroupList
50 err := containerClient.RequestAndDecode(&gp,
51 arvados.EndpointGroupList.Method,
52 arvados.EndpointGroupList.Path,
53 nil, arvados.ListOptions{Filters: []arvados.Filter{
54 arvados.Filter{"owner_uuid", "=", ownerUuid},
55 arvados.Filter{"name", "=", name},
56 arvados.Filter{"group_class", "=", "project"},
62 if len(gp.Items) == 1 {
63 return &gp.Items[0], nil
66 var rgroup arvados.Group
67 err = containerClient.RequestAndDecode(&rgroup,
68 arvados.EndpointGroupCreate.Method,
69 arvados.EndpointGroupCreate.Path,
70 nil, map[string]interface{}{
71 "group": map[string]string{
72 "owner_uuid": ownerUuid,
74 "group_class": "project",
83 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
84 containerClient *arvados.Client) (collection *arvados.Collection, err error) {
86 // Cache the image to keep
87 cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
89 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
91 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
93 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
96 collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
97 var cl arvados.CollectionList
98 err = containerClient.RequestAndDecode(&cl,
99 arvados.EndpointCollectionList.Method,
100 arvados.EndpointCollectionList.Path,
101 nil, arvados.ListOptions{Filters: []arvados.Filter{
102 arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
103 arvados.Filter{"name", "=", collectionName},
107 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
109 var imageCollection arvados.Collection
110 if len(cl.Items) == 1 {
111 imageCollection = cl.Items[0]
113 collectionName := "converting " + collectionName
114 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
115 err = containerClient.RequestAndDecode(&imageCollection,
116 arvados.EndpointCollectionCreate.Method,
117 arvados.EndpointCollectionCreate.Path,
118 nil, map[string]interface{}{
119 "collection": map[string]string{
120 "owner_uuid": imageGroup.UUID,
121 "name": collectionName,
122 "trash_at": exp.UTC().Format(time.RFC3339),
124 "ensure_unique_name": true,
127 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
132 return &imageCollection, nil
135 // LoadImage will satisfy ContainerExecuter interface transforming
136 // containerImage into a sif file for later use.
137 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
138 containerClient *arvados.Client) error {
140 var imageFilename string
141 var sifCollection *arvados.Collection
143 if containerClient != nil {
144 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
148 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
150 imageFilename = e.tmpdir + "/image.sif"
153 if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
154 // Make sure the docker image is readable, and error
156 if _, err := os.Stat(imageTarballPath); err != nil {
160 e.logf("building singularity image")
161 // "singularity build" does not accept a
162 // docker-archive://... filename containing a ":" character,
163 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
164 // symlink that doesn't have ":" chars.
165 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
170 // Set up a cache and tmp dir for singularity build
171 err = os.Mkdir(e.tmpdir+"/cache", 0700)
175 defer os.RemoveAll(e.tmpdir + "/cache")
176 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
180 defer os.RemoveAll(e.tmpdir + "/tmp")
182 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
183 build.Env = os.Environ()
184 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
185 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
186 e.logf("%v", build.Args)
187 out, err := build.CombinedOutput()
188 // INFO: Starting build...
189 // Getting image source signatures
190 // Copying blob ab15617702de done
191 // Copying config 651e02b8a2 done
192 // Writing manifest to image destination
193 // Storing signatures
194 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
195 // INFO: Creating SIF file...
196 // INFO: Build complete: arvados-jobs.latest.sif
203 if containerClient == nil {
204 e.imageFilename = imageFilename
208 // update TTL to now + two weeks
209 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
211 uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
213 e.logf("error PathForUUID: %v", err)
216 var imageCollection arvados.Collection
217 err = containerClient.RequestAndDecode(&imageCollection,
218 arvados.EndpointCollectionUpdate.Method,
220 nil, map[string]interface{}{
221 "collection": map[string]string{
222 "name": fmt.Sprintf("singularity image for %v", dockerImageID),
223 "trash_at": exp.UTC().Format(time.RFC3339),
227 // If we just wrote the image to the cache, the
228 // response also returns the updated PDH
229 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
233 e.logf("error updating/renaming collection for cached sif image: %v", err)
234 // Failed to update but maybe it lost a race and there is
235 // another cached collection in the same place, so check the cache
237 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
241 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
246 func (e *singularityExecutor) Create(spec containerSpec) error {
251 func (e *singularityExecutor) execCmd(path string) *exec.Cmd {
252 args := []string{path, "exec", "--containall", "--cleanenv", "--pwd=" + e.spec.WorkingDir}
254 args = append(args, "--fakeroot")
256 if !e.spec.EnableNetwork {
257 args = append(args, "--net", "--network=none")
258 } else if u, err := user.Current(); err == nil && u.Uid == "0" || e.fakeroot {
259 // Specifying --network=bridge fails unless (a) we are
260 // root, (b) we are using --fakeroot, or (c)
261 // singularity has been configured to allow our
262 // uid/gid to use it like so:
264 // singularity config global --set 'allow net networks' bridge
265 // singularity config global --set 'allow net groups' mygroup
266 args = append(args, "--net", "--network=bridge")
268 if e.spec.CUDADeviceCount != 0 {
269 args = append(args, "--nv")
272 readonlyflag := map[bool]string{
277 for path, _ := range e.spec.BindMounts {
278 binds = append(binds, path)
281 for _, path := range binds {
282 mount := e.spec.BindMounts[path]
283 if path == e.spec.Env["HOME"] {
284 // Singularity treates $HOME as special case
285 args = append(args, "--home", mount.HostPath+":"+path)
287 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
291 // This is for singularity 3.5.2. There are some behaviors
292 // that will change in singularity 3.6, please see:
293 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
294 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
295 env := make([]string, 0, len(e.spec.Env))
296 for k, v := range e.spec.Env {
298 // Singularity treates $HOME as special case, this is handled
302 env = append(env, "SINGULARITYENV_"+k+"="+v)
305 // Singularity always makes all nvidia devices visible to the
306 // container. If a resource manager such as slurm or LSF told
307 // us to select specific devices we need to propagate that.
308 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
309 // If a resource manager such as slurm or LSF told
310 // us to select specific devices we need to propagate that.
311 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
314 args = append(args, e.imageFilename)
315 args = append(args, e.spec.Command...)
322 Stdout: e.spec.Stdout,
323 Stderr: e.spec.Stderr,
327 func (e *singularityExecutor) Start() error {
328 path, err := exec.LookPath("singularity")
332 child := e.execCmd(path)
341 func (e *singularityExecutor) CgroupID() string {
345 func (e *singularityExecutor) Stop() error {
346 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
347 // process already exited
350 return e.child.Process.Signal(syscall.SIGKILL)
353 func (e *singularityExecutor) Wait(context.Context) (int, error) {
354 err := e.child.Wait()
355 if err, ok := err.(*exec.ExitError); ok {
356 return err.ProcessState.ExitCode(), nil
361 return e.child.ProcessState.ExitCode(), nil
364 func (e *singularityExecutor) Close() {
365 err := os.RemoveAll(e.tmpdir)
367 e.logf("error removing temp dir: %s", err)
371 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
372 target, err := e.containedProcess()
376 return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
380 errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
383 func (e *singularityExecutor) IPAddress() (string, error) {
384 target, err := e.containedProcess()
388 targetIPs, err := processIPs(target)
392 selfIPs, err := processIPs(os.Getpid())
396 for ip := range targetIPs {
401 return "", errContainerHasNoIPAddress
404 func processIPs(pid int) (map[string]bool, error) {
405 fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
410 addrs := map[string]bool{}
411 // When we see a pair of lines like this:
416 // ...we set addrs["10.1.2.3"] = true
417 lines := bytes.Split(fibtrie, []byte{'\n'})
418 for linenumber, line := range lines {
419 if !bytes.HasSuffix(line, []byte("/32 host LOCAL")) {
425 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
426 if i < 0 || i >= len(line)-7 {
429 addr := string(lines[linenumber-1][i+1:])
430 if net.ParseIP(addr).To4() != nil {
438 errContainerNotStarted = errors.New("container has not started yet")
439 errCannotFindChild = errors.New("failed to find any process inside the container")
440 reProcStatusPPid = regexp.MustCompile(`\nPPid:\t(\d+)\n`)
443 // Return the PID of a process that is inside the container (not
444 // necessarily the topmost/pid=1 process in the container).
445 func (e *singularityExecutor) containedProcess() (int, error) {
446 if e.child == nil || e.child.Process == nil {
447 return 0, errContainerNotStarted
449 lsns, err := exec.Command("lsns").CombinedOutput()
451 return 0, fmt.Errorf("lsns: %w", err)
453 for _, line := range bytes.Split(lsns, []byte{'\n'}) {
454 fields := bytes.Fields(line)
458 if !bytes.Equal(fields[1], []byte("pid")) {
461 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
463 return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
465 for parent := pid; ; {
466 procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
470 m := reProcStatusPPid.FindSubmatch(procstatus)
474 parent, err = strconv.ParseInt(string(m[1]), 10, 64)
478 if int(parent) == e.child.Process.Pid {
483 return 0, errCannotFindChild