1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 "git.arvados.org/arvados.git/sdk/go/arvados"
17 "golang.org/x/net/context"
20 type singularityExecutor struct {
21 logf func(string, ...interface{})
25 imageFilename string // "sif" image
28 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
29 tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
33 return &singularityExecutor{
39 func (e *singularityExecutor) Runtime() string { return "singularity" }
41 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
42 var gp arvados.GroupList
43 err := containerClient.RequestAndDecode(&gp,
44 arvados.EndpointGroupList.Method,
45 arvados.EndpointGroupList.Path,
46 nil, arvados.ListOptions{Filters: []arvados.Filter{
47 arvados.Filter{"owner_uuid", "=", ownerUuid},
48 arvados.Filter{"name", "=", name},
49 arvados.Filter{"group_class", "=", "project"},
55 if len(gp.Items) == 1 {
56 return &gp.Items[0], nil
59 var rgroup arvados.Group
60 err = containerClient.RequestAndDecode(&rgroup,
61 arvados.EndpointGroupCreate.Method,
62 arvados.EndpointGroupCreate.Path,
63 nil, map[string]interface{}{
64 "group": map[string]string{
65 "owner_uuid": ownerUuid,
67 "group_class": "project",
76 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
77 containerClient *arvados.Client) (collection *arvados.Collection, err error) {
79 // Cache the image to keep
80 cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
82 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
84 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
86 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
89 collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
90 var cl arvados.CollectionList
91 err = containerClient.RequestAndDecode(&cl,
92 arvados.EndpointCollectionList.Method,
93 arvados.EndpointCollectionList.Path,
94 nil, arvados.ListOptions{Filters: []arvados.Filter{
95 arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
96 arvados.Filter{"name", "=", collectionName},
100 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
102 var imageCollection arvados.Collection
103 if len(cl.Items) == 1 {
104 imageCollection = cl.Items[0]
106 collectionName := "converting " + collectionName
107 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
108 err = containerClient.RequestAndDecode(&imageCollection,
109 arvados.EndpointCollectionCreate.Method,
110 arvados.EndpointCollectionCreate.Path,
111 nil, map[string]interface{}{
112 "collection": map[string]string{
113 "owner_uuid": imageGroup.UUID,
114 "name": collectionName,
115 "trash_at": exp.UTC().Format(time.RFC3339),
117 "ensure_unique_name": true,
120 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
125 return &imageCollection, nil
128 // LoadImage will satisfy ContainerExecuter interface transforming
129 // containerImage into a sif file for later use.
130 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
131 containerClient *arvados.Client) error {
133 var imageFilename string
134 var sifCollection *arvados.Collection
136 if containerClient != nil {
137 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
141 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
143 imageFilename = e.tmpdir + "/image.sif"
146 if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
147 // Make sure the docker image is readable, and error
149 if _, err := os.Stat(imageTarballPath); err != nil {
153 e.logf("building singularity image")
154 // "singularity build" does not accept a
155 // docker-archive://... filename containing a ":" character,
156 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
157 // symlink that doesn't have ":" chars.
158 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
163 // Set up a cache and tmp dir for singularity build
164 err = os.Mkdir(e.tmpdir+"/cache", 0700)
168 defer os.RemoveAll(e.tmpdir + "/cache")
169 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
173 defer os.RemoveAll(e.tmpdir + "/tmp")
175 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
176 build.Env = os.Environ()
177 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
178 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
179 e.logf("%v", build.Args)
180 out, err := build.CombinedOutput()
181 // INFO: Starting build...
182 // Getting image source signatures
183 // Copying blob ab15617702de done
184 // Copying config 651e02b8a2 done
185 // Writing manifest to image destination
186 // Storing signatures
187 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
188 // INFO: Creating SIF file...
189 // INFO: Build complete: arvados-jobs.latest.sif
196 if containerClient == nil {
197 e.imageFilename = imageFilename
201 // update TTL to now + two weeks
202 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
204 uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
206 e.logf("error PathForUUID: %v", err)
209 var imageCollection arvados.Collection
210 err = containerClient.RequestAndDecode(&imageCollection,
211 arvados.EndpointCollectionUpdate.Method,
213 nil, map[string]interface{}{
214 "collection": map[string]string{
215 "name": fmt.Sprintf("singularity image for %v", dockerImageID),
216 "trash_at": exp.UTC().Format(time.RFC3339),
220 // If we just wrote the image to the cache, the
221 // response also returns the updated PDH
222 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
226 e.logf("error updating/renaming collection for cached sif image: %v", err)
227 // Failed to update but maybe it lost a race and there is
228 // another cached collection in the same place, so check the cache
230 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
234 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
239 func (e *singularityExecutor) Create(spec containerSpec) error {
244 func (e *singularityExecutor) Start() error {
245 args := []string{"singularity", "exec", "--containall", "--cleanenv", "--pwd", e.spec.WorkingDir}
246 if !e.spec.EnableNetwork {
247 args = append(args, "--net", "--network=none")
249 readonlyflag := map[bool]string{
254 for path, _ := range e.spec.BindMounts {
255 binds = append(binds, path)
258 for _, path := range binds {
259 mount := e.spec.BindMounts[path]
260 if path == e.spec.Env["HOME"] {
261 // Singularity treates $HOME as special case
262 args = append(args, "--home", mount.HostPath+":"+path)
264 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
268 // This is for singularity 3.5.2. There are some behaviors
269 // that will change in singularity 3.6, please see:
270 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
271 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
272 env := make([]string, 0, len(e.spec.Env))
273 for k, v := range e.spec.Env {
275 // Singularity treates $HOME as special case, this is handled
279 env = append(env, "SINGULARITYENV_"+k+"="+v)
282 args = append(args, e.imageFilename)
283 args = append(args, e.spec.Command...)
285 path, err := exec.LookPath(args[0])
294 Stdout: e.spec.Stdout,
295 Stderr: e.spec.Stderr,
305 func (e *singularityExecutor) CgroupID() string {
309 func (e *singularityExecutor) Stop() error {
310 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
311 // process already exited
314 return e.child.Process.Signal(syscall.SIGKILL)
317 func (e *singularityExecutor) Wait(context.Context) (int, error) {
318 err := e.child.Wait()
319 if err, ok := err.(*exec.ExitError); ok {
320 return err.ProcessState.ExitCode(), nil
325 return e.child.ProcessState.ExitCode(), nil
328 func (e *singularityExecutor) Close() {
329 err := os.RemoveAll(e.tmpdir)
331 e.logf("error removing temp dir: %s", err)