1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.arvados.org/arvados.git/sdk/go/arvados"
18 "golang.org/x/net/context"
21 type singularityExecutor struct {
22 logf func(string, ...interface{})
26 imageFilename string // "sif" image
29 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
30 tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
34 return &singularityExecutor{
40 func (e *singularityExecutor) Runtime() string {
41 buf, err := exec.Command("singularity", "--version").CombinedOutput()
43 return "singularity (unknown version)"
45 return strings.TrimSuffix(string(buf), "\n")
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}
253 if !e.spec.EnableNetwork {
254 args = append(args, "--net", "--network=none")
257 if e.spec.CUDADeviceCount != 0 {
258 args = append(args, "--nv")
261 readonlyflag := map[bool]string{
266 for path, _ := range e.spec.BindMounts {
267 binds = append(binds, path)
270 for _, path := range binds {
271 mount := e.spec.BindMounts[path]
272 if path == e.spec.Env["HOME"] {
273 // Singularity treates $HOME as special case
274 args = append(args, "--home", mount.HostPath+":"+path)
276 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
280 // This is for singularity 3.5.2. There are some behaviors
281 // that will change in singularity 3.6, please see:
282 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
283 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
284 env := make([]string, 0, len(e.spec.Env))
285 for k, v := range e.spec.Env {
287 // Singularity treates $HOME as special case, this is handled
291 env = append(env, "SINGULARITYENV_"+k+"="+v)
294 // Singularity always makes all nvidia devices visible to the
295 // container. If a resource manager such as slurm or LSF told
296 // us to select specific devices we need to propagate that.
297 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
298 // If a resource manager such as slurm or LSF told
299 // us to select specific devices we need to propagate that.
300 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
303 args = append(args, e.imageFilename)
304 args = append(args, e.spec.Command...)
311 Stdout: e.spec.Stdout,
312 Stderr: e.spec.Stderr,
316 func (e *singularityExecutor) Start() error {
317 path, err := exec.LookPath("singularity")
321 child := e.execCmd(path)
330 func (e *singularityExecutor) CgroupID() string {
334 func (e *singularityExecutor) Stop() error {
335 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
336 // process already exited
339 return e.child.Process.Signal(syscall.SIGKILL)
342 func (e *singularityExecutor) Wait(context.Context) (int, error) {
343 err := e.child.Wait()
344 if err, ok := err.(*exec.ExitError); ok {
345 return err.ProcessState.ExitCode(), nil
350 return e.child.ProcessState.ExitCode(), nil
353 func (e *singularityExecutor) Close() {
354 err := os.RemoveAll(e.tmpdir)
356 e.logf("error removing temp dir: %s", err)