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) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
40 var gp arvados.GroupList
41 err := containerClient.RequestAndDecode(&gp,
42 arvados.EndpointGroupList.Method,
43 arvados.EndpointGroupList.Path,
44 nil, arvados.ListOptions{Filters: []arvados.Filter{
45 arvados.Filter{"owner_uuid", "=", ownerUuid},
46 arvados.Filter{"name", "=", name},
47 arvados.Filter{"group_class", "=", "project"},
53 if len(gp.Items) == 1 {
54 return &gp.Items[0], nil
57 var rgroup arvados.Group
58 err = containerClient.RequestAndDecode(&rgroup,
59 arvados.EndpointGroupCreate.Method,
60 arvados.EndpointGroupCreate.Path,
61 nil, map[string]interface{}{
62 "group": map[string]string{
63 "owner_uuid": ownerUuid,
65 "group_class": "project",
74 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
75 containerClient *arvados.Client) (collection *arvados.Collection, err error) {
77 // Cache the image to keep
78 cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
80 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
82 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
84 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
87 collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
88 var cl arvados.CollectionList
89 err = containerClient.RequestAndDecode(&cl,
90 arvados.EndpointCollectionList.Method,
91 arvados.EndpointCollectionList.Path,
92 nil, arvados.ListOptions{Filters: []arvados.Filter{
93 arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
94 arvados.Filter{"name", "=", collectionName},
98 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
100 var imageCollection arvados.Collection
101 if len(cl.Items) == 1 {
102 imageCollection = cl.Items[0]
104 collectionName := "converting " + collectionName
105 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
106 err = containerClient.RequestAndDecode(&imageCollection,
107 arvados.EndpointCollectionCreate.Method,
108 arvados.EndpointCollectionCreate.Path,
109 nil, map[string]interface{}{
110 "collection": map[string]string{
111 "owner_uuid": imageGroup.UUID,
112 "name": collectionName,
113 "trash_at": exp.UTC().Format(time.RFC3339),
115 "ensure_unique_name": true,
118 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
123 return &imageCollection, nil
126 // LoadImage will satisfy ContainerExecuter interface transforming
127 // containerImage into a sif file for later use.
128 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
129 containerClient *arvados.Client) error {
131 var imageFilename string
132 var sifCollection *arvados.Collection
134 if containerClient != nil {
135 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
139 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
141 imageFilename = e.tmpdir + "/image.sif"
144 if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
145 // Make sure the docker image is readable
146 if _, err := os.Stat(dockerImageID); err != nil {
150 e.logf("building singularity image")
151 // "singularity build" does not accept a
152 // docker-archive://... filename containing a ":" character,
153 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
154 // symlink that doesn't have ":" chars.
155 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
160 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
161 e.logf("%v", build.Args)
162 out, err := build.CombinedOutput()
163 // INFO: Starting build...
164 // Getting image source signatures
165 // Copying blob ab15617702de done
166 // Copying config 651e02b8a2 done
167 // Writing manifest to image destination
168 // Storing signatures
169 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
170 // INFO: Creating SIF file...
171 // INFO: Build complete: arvados-jobs.latest.sif
178 if containerClient == nil {
179 e.imageFilename = imageFilename
183 // update TTL to now + two weeks
184 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
186 uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
188 e.logf("error PathForUUID: %v", err)
191 var imageCollection arvados.Collection
192 err = containerClient.RequestAndDecode(&imageCollection,
193 arvados.EndpointCollectionUpdate.Method,
195 nil, map[string]interface{}{
196 "collection": map[string]string{
197 "name": fmt.Sprintf("singularity image for %v", dockerImageID),
198 "trash_at": exp.UTC().Format(time.RFC3339),
202 // If we just wrote the image to the cache, the
203 // response also returns the updated PDH
204 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
208 e.logf("error updating/renaming collection for cached sif image: %v", err)
209 // Failed to update but maybe it lost a race and there is
210 // another cached collection in the same place, so check the cache
212 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
216 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
221 func (e *singularityExecutor) Create(spec containerSpec) error {
226 func (e *singularityExecutor) Start() error {
227 args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
228 if !e.spec.EnableNetwork {
229 args = append(args, "--net", "--network=none")
231 readonlyflag := map[bool]string{
236 for path, _ := range e.spec.BindMounts {
237 binds = append(binds, path)
240 for _, path := range binds {
241 mount := e.spec.BindMounts[path]
242 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
245 // This is for singularity 3.5.2. There are some behaviors
246 // that will change in singularity 3.6, please see:
247 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
248 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
249 env := make([]string, 0, len(e.spec.Env))
250 for k, v := range e.spec.Env {
252 // $HOME is a special case
253 args = append(args, "--home="+v)
255 env = append(env, "SINGULARITYENV_"+k+"="+v)
259 args = append(args, e.imageFilename)
260 args = append(args, e.spec.Command...)
262 path, err := exec.LookPath(args[0])
271 Stdout: e.spec.Stdout,
272 Stderr: e.spec.Stderr,
282 func (e *singularityExecutor) CgroupID() string {
286 func (e *singularityExecutor) Stop() error {
287 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
288 // process already exited
291 return e.child.Process.Signal(syscall.SIGKILL)
294 func (e *singularityExecutor) Wait(context.Context) (int, error) {
295 err := e.child.Wait()
296 if err, ok := err.(*exec.ExitError); ok {
297 return err.ProcessState.ExitCode(), nil
302 return e.child.ProcessState.ExitCode(), nil
305 func (e *singularityExecutor) Close() {
306 err := os.RemoveAll(e.tmpdir)
308 e.logf("error removing temp dir: %s", err)