1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "golang.org/x/net/context"
25 type singularityExecutor struct {
26 logf func(string, ...interface{})
30 imageFilename string // "sif" image
33 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
34 tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
38 return &singularityExecutor{
44 func (e *singularityExecutor) Runtime() string { return "singularity" }
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"},
60 if len(gp.Items) == 1 {
61 return &gp.Items[0], nil
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,
72 "group_class": "project",
81 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
82 containerClient *arvados.Client) (collection *arvados.Collection, err error) {
84 // Cache the image to keep
85 cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
87 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
89 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
91 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
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},
105 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
107 var imageCollection arvados.Collection
108 if len(cl.Items) == 1 {
109 imageCollection = cl.Items[0]
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),
122 "ensure_unique_name": true,
125 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
130 return &imageCollection, nil
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 {
138 var imageFilename string
139 var sifCollection *arvados.Collection
141 if containerClient != nil {
142 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
146 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
148 imageFilename = e.tmpdir + "/image.sif"
151 if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
152 // Make sure the docker image is readable, and error
154 if _, err := os.Stat(imageTarballPath); err != nil {
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")
168 // Set up a cache and tmp dir for singularity build
169 err = os.Mkdir(e.tmpdir+"/cache", 0700)
173 defer os.RemoveAll(e.tmpdir + "/cache")
174 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
178 defer os.RemoveAll(e.tmpdir + "/tmp")
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
201 if containerClient == nil {
202 e.imageFilename = imageFilename
206 // update TTL to now + two weeks
207 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
209 uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
211 e.logf("error PathForUUID: %v", err)
214 var imageCollection arvados.Collection
215 err = containerClient.RequestAndDecode(&imageCollection,
216 arvados.EndpointCollectionUpdate.Method,
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),
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)
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
235 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
239 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
244 func (e *singularityExecutor) Create(spec containerSpec) error {
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")
254 if e.spec.CUDADeviceCount != 0 {
255 args = append(args, "--nv")
258 readonlyflag := map[bool]string{
263 for path, _ := range e.spec.BindMounts {
264 binds = append(binds, path)
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)
273 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
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 {
284 // Singularity treates $HOME as special case, this is handled
288 env = append(env, "SINGULARITYENV_"+k+"="+v)
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)
300 args = append(args, e.imageFilename)
301 args = append(args, e.spec.Command...)
308 Stdout: e.spec.Stdout,
309 Stderr: e.spec.Stderr,
313 func (e *singularityExecutor) Start() error {
314 path, err := exec.LookPath("singularity")
318 child := e.execCmd(path)
327 func (e *singularityExecutor) CgroupID() string {
331 func (e *singularityExecutor) Stop() error {
332 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
333 // process already exited
336 return e.child.Process.Signal(syscall.SIGKILL)
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
347 return e.child.ProcessState.ExitCode(), nil
350 func (e *singularityExecutor) Close() {
351 err := os.RemoveAll(e.tmpdir)
353 e.logf("error removing temp dir: %s", err)
357 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
358 target, err := e.containedProcess()
362 return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
366 errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
369 func (e *singularityExecutor) IPAddress() (string, error) {
370 target, err := e.containedProcess()
374 targetIPs, err := processIPs(target)
378 selfIPs, err := processIPs(os.Getpid())
382 for ip := range targetIPs {
387 return "", errContainerHasNoIPAddress
390 func processIPs(pid int) (map[string]bool, error) {
391 fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
396 addrs := map[string]bool{}
397 // When we see a pair of lines like this:
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")) {
411 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
412 if i < 0 || i >= len(line)-7 {
415 addr := string(lines[linenumber-1][i+1:])
416 if net.ParseIP(addr).To4() != nil {
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`)
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
435 lsns, err := exec.Command("lsns").CombinedOutput()
437 return 0, fmt.Errorf("lsns: %w", err)
439 for _, line := range bytes.Split(lsns, []byte{'\n'}) {
440 fields := bytes.Fields(line)
444 if !bytes.Equal(fields[1], []byte("pid")) {
447 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
449 return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
451 for parent := pid; ; {
452 procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
456 m := reProcStatusPPid.FindSubmatch(procstatus)
460 parent, err = strconv.ParseInt(string(m[1]), 10, 64)
464 if int(parent) == e.child.Process.Pid {
469 return 0, errCannotFindChild