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 { return "singularity" }
42 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
43 var gp arvados.GroupList
44 err := containerClient.RequestAndDecode(&gp,
45 arvados.EndpointGroupList.Method,
46 arvados.EndpointGroupList.Path,
47 nil, arvados.ListOptions{Filters: []arvados.Filter{
48 arvados.Filter{"owner_uuid", "=", ownerUuid},
49 arvados.Filter{"name", "=", name},
50 arvados.Filter{"group_class", "=", "project"},
56 if len(gp.Items) == 1 {
57 return &gp.Items[0], nil
60 var rgroup arvados.Group
61 err = containerClient.RequestAndDecode(&rgroup,
62 arvados.EndpointGroupCreate.Method,
63 arvados.EndpointGroupCreate.Path,
64 nil, map[string]interface{}{
65 "group": map[string]string{
66 "owner_uuid": ownerUuid,
68 "group_class": "project",
77 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
78 containerClient *arvados.Client) (collection *arvados.Collection, err error) {
80 // Cache the image to keep
81 cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
83 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
85 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
87 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
90 collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
91 var cl arvados.CollectionList
92 err = containerClient.RequestAndDecode(&cl,
93 arvados.EndpointCollectionList.Method,
94 arvados.EndpointCollectionList.Path,
95 nil, arvados.ListOptions{Filters: []arvados.Filter{
96 arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
97 arvados.Filter{"name", "=", collectionName},
101 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
103 var imageCollection arvados.Collection
104 if len(cl.Items) == 1 {
105 imageCollection = cl.Items[0]
107 collectionName := "converting " + collectionName
108 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
109 err = containerClient.RequestAndDecode(&imageCollection,
110 arvados.EndpointCollectionCreate.Method,
111 arvados.EndpointCollectionCreate.Path,
112 nil, map[string]interface{}{
113 "collection": map[string]string{
114 "owner_uuid": imageGroup.UUID,
115 "name": collectionName,
116 "trash_at": exp.UTC().Format(time.RFC3339),
118 "ensure_unique_name": true,
121 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
126 return &imageCollection, nil
129 // LoadImage will satisfy ContainerExecuter interface transforming
130 // containerImage into a sif file for later use.
131 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
132 containerClient *arvados.Client) error {
134 var imageFilename string
135 var sifCollection *arvados.Collection
137 if containerClient != nil {
138 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
142 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
144 imageFilename = e.tmpdir + "/image.sif"
147 if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
148 // Make sure the docker image is readable, and error
150 if _, err := os.Stat(imageTarballPath); err != nil {
154 e.logf("building singularity image")
155 // "singularity build" does not accept a
156 // docker-archive://... filename containing a ":" character,
157 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
158 // symlink that doesn't have ":" chars.
159 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
164 // Set up a cache and tmp dir for singularity build
165 err = os.Mkdir(e.tmpdir+"/cache", 0700)
169 defer os.RemoveAll(e.tmpdir + "/cache")
170 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
174 defer os.RemoveAll(e.tmpdir + "/tmp")
176 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
177 build.Env = os.Environ()
178 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
179 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
180 e.logf("%v", build.Args)
181 out, err := build.CombinedOutput()
182 // INFO: Starting build...
183 // Getting image source signatures
184 // Copying blob ab15617702de done
185 // Copying config 651e02b8a2 done
186 // Writing manifest to image destination
187 // Storing signatures
188 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
189 // INFO: Creating SIF file...
190 // INFO: Build complete: arvados-jobs.latest.sif
197 if containerClient == nil {
198 e.imageFilename = imageFilename
202 // update TTL to now + two weeks
203 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
205 uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
207 e.logf("error PathForUUID: %v", err)
210 var imageCollection arvados.Collection
211 err = containerClient.RequestAndDecode(&imageCollection,
212 arvados.EndpointCollectionUpdate.Method,
214 nil, map[string]interface{}{
215 "collection": map[string]string{
216 "name": fmt.Sprintf("singularity image for %v", dockerImageID),
217 "trash_at": exp.UTC().Format(time.RFC3339),
221 // If we just wrote the image to the cache, the
222 // response also returns the updated PDH
223 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
227 e.logf("error updating/renaming collection for cached sif image: %v", err)
228 // Failed to update but maybe it lost a race and there is
229 // another cached collection in the same place, so check the cache
231 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
235 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
240 func (e *singularityExecutor) Create(spec containerSpec) error {
245 func (e *singularityExecutor) execCmd(path string) *exec.Cmd {
246 args := []string{path, "exec", "--containall", "--cleanenv", "--pwd", e.spec.WorkingDir}
247 if !e.spec.EnableNetwork {
248 args = append(args, "--net", "--network=none")
251 if e.spec.CUDADeviceCount != 0 {
252 args = append(args, "--nv")
255 readonlyflag := map[bool]string{
260 for path, _ := range e.spec.BindMounts {
261 binds = append(binds, path)
264 for _, path := range binds {
265 mount := e.spec.BindMounts[path]
266 if path == e.spec.Env["HOME"] {
267 // Singularity treates $HOME as special case
268 args = append(args, "--home", mount.HostPath+":"+path)
270 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
274 // This is for singularity 3.5.2. There are some behaviors
275 // that will change in singularity 3.6, please see:
276 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
277 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
278 env := make([]string, 0, len(e.spec.Env))
279 for k, v := range e.spec.Env {
281 // Singularity treates $HOME as special case, this is handled
285 env = append(env, "SINGULARITYENV_"+k+"="+v)
288 // Singularity always makes all nvidia devices visible to the
289 // container. If a resource manager such as slurm or LSF told
290 // us to select specific devices we need to propagate that.
291 for _, s := range os.Environ() {
292 if strings.HasPrefix(s, "CUDA_VISIBLE_DEVICES=") {
293 env = append(env, "SINGULARITYENV_"+s)
297 args = append(args, e.imageFilename)
298 args = append(args, e.spec.Command...)
305 Stdout: e.spec.Stdout,
306 Stderr: e.spec.Stderr,
310 func (e *singularityExecutor) Start() error {
311 path, err := exec.LookPath("singularity")
315 child := e.execCmd(path)
324 func (e *singularityExecutor) CgroupID() string {
328 func (e *singularityExecutor) Stop() error {
329 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
330 // process already exited
333 return e.child.Process.Signal(syscall.SIGKILL)
336 func (e *singularityExecutor) Wait(context.Context) (int, error) {
337 err := e.child.Wait()
338 if err, ok := err.(*exec.ExitError); ok {
339 return err.ProcessState.ExitCode(), nil
344 return e.child.ProcessState.ExitCode(), nil
347 func (e *singularityExecutor) Close() {
348 err := os.RemoveAll(e.tmpdir)
350 e.logf("error removing temp dir: %s", err)