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
27 containerClient *arvados.Client
28 container arvados.Container
29 keepClient IKeepClient
33 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
34 tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
38 return &singularityExecutor{
44 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, create bool) (*arvados.Group, error) {
45 var gp arvados.GroupList
46 err := e.containerClient.RequestAndDecode(&gp,
47 arvados.EndpointGroupList.Method,
48 arvados.EndpointGroupList.Path,
49 nil, arvados.ListOptions{Filters: []arvados.Filter{
50 arvados.Filter{"owner_uuid", "=", ownerUuid},
51 arvados.Filter{"name", "=", name},
52 arvados.Filter{"group_class", "=", "project"},
58 if len(gp.Items) == 1 {
59 return &gp.Items[0], nil
64 var rgroup arvados.Group
65 err = e.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) ImageLoaded(imageId string) bool {
82 // Check if docker image is cached in keep & if so set imageFilename
84 // Cache the image to keep
85 cacheGroup, err := e.getOrCreateProject(e.container.RuntimeUserUUID, ".cache", false)
87 e.logf("error getting '.cache' project: %v", err)
90 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", false)
92 e.logf("error getting 'auto-generated singularity images' project: %s", err)
96 collectionName := fmt.Sprintf("singularity image for %v", imageId)
97 var cl arvados.CollectionList
98 err = e.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 e.logf("error getting collection '%v' project: %v", err)
110 if len(cl.Items) == 0 {
111 e.logf("no cached image '%v' found", collectionName)
115 path := fmt.Sprintf("%s/by_id/%s/image.sif", e.keepMount, cl.Items[0].PortableDataHash)
116 e.logf("Looking for %v", path)
117 if _, err = os.Stat(path); os.IsNotExist(err) {
120 e.imageFilename = path
125 // LoadImage will satisfy ContainerExecuter interface transforming
126 // containerImage into a sif file for later use.
127 func (e *singularityExecutor) LoadImage(imageTarballPath string) error {
128 if e.imageFilename != "" {
129 e.logf("using singularity image %v", e.imageFilename)
131 // was set by ImageLoaded
135 e.logf("building singularity image")
136 // "singularity build" does not accept a
137 // docker-archive://... filename containing a ":" character,
138 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
139 // symlink that doesn't have ":" chars.
140 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
144 e.imageFilename = e.tmpdir + "/image.sif"
145 build := exec.Command("singularity", "build", e.imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
146 e.logf("%v", build.Args)
147 out, err := build.CombinedOutput()
148 // INFO: Starting build...
149 // Getting image source signatures
150 // Copying blob ab15617702de done
151 // Copying config 651e02b8a2 done
152 // Writing manifest to image destination
153 // Storing signatures
154 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
155 // INFO: Creating SIF file...
156 // INFO: Build complete: arvados-jobs.latest.sif
162 // Cache the image to keep
163 cacheGroup, err := e.getOrCreateProject(e.container.RuntimeUserUUID, ".cache", true)
165 e.logf("error getting '.cache' project: %v", err)
168 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", true)
170 e.logf("error getting 'auto-generated singularity images' project: %v", err)
174 parts := strings.Split(imageTarballPath, "/")
175 imageId := parts[len(parts)-1]
176 if strings.HasSuffix(imageId, ".tar") {
177 imageId = imageId[0 : len(imageId)-4]
180 fs, err := (&arvados.Collection{ManifestText: ""}).FileSystem(e.containerClient, e.keepClient)
182 e.logf("error creating FileSystem: %s", err)
185 dst, err := fs.OpenFile("image.sif", os.O_CREATE|os.O_WRONLY, 0666)
187 e.logf("error creating opening collection file for writing: %s", err)
190 src, err := os.Open(e.imageFilename)
196 _, err = io.Copy(dst, src)
202 manifestText, err := fs.MarshalManifest(".")
204 e.logf("error creating manifest text: %s", err)
207 var imageCollection arvados.Collection
208 collectionName := fmt.Sprintf("singularity image for %s", imageId)
209 err = e.containerClient.RequestAndDecode(&imageCollection,
210 arvados.EndpointCollectionCreate.Method,
211 arvados.EndpointCollectionCreate.Path,
212 nil, map[string]interface{}{
213 "collection": map[string]string{
214 "owner_uuid": imageGroup.UUID,
215 "name": collectionName,
216 "manifest_text": manifestText,
220 e.logf("error creating '%v' collection: %s", collectionName, err)
226 func (e *singularityExecutor) Create(spec containerSpec) error {
231 func (e *singularityExecutor) Start() error {
232 args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
233 if !e.spec.EnableNetwork {
234 args = append(args, "--net", "--network=none")
236 readonlyflag := map[bool]string{
241 for path, _ := range e.spec.BindMounts {
242 binds = append(binds, path)
245 for _, path := range binds {
246 mount := e.spec.BindMounts[path]
247 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
250 // This is for singularity 3.5.2. There are some behaviors
251 // that will change in singularity 3.6, please see:
252 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
253 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
254 env := make([]string, 0, len(e.spec.Env))
255 for k, v := range e.spec.Env {
257 // $HOME is a special case
258 args = append(args, "--home="+v)
260 env = append(env, "SINGULARITYENV_"+k+"="+v)
264 args = append(args, e.imageFilename)
265 args = append(args, e.spec.Command...)
267 path, err := exec.LookPath(args[0])
276 Stdout: e.spec.Stdout,
277 Stderr: e.spec.Stderr,
287 func (e *singularityExecutor) CgroupID() string {
291 func (e *singularityExecutor) Stop() error {
292 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
293 // process already exited
296 return e.child.Process.Signal(syscall.SIGKILL)
299 func (e *singularityExecutor) Wait(context.Context) (int, error) {
300 err := e.child.Wait()
301 if err, ok := err.(*exec.ExitError); ok {
302 return err.ProcessState.ExitCode(), nil
307 return e.child.ProcessState.ExitCode(), nil
310 func (e *singularityExecutor) Close() {
311 err := os.RemoveAll(e.tmpdir)
313 e.logf("error removing temp dir: %s", err)
317 func (e *singularityExecutor) SetArvadoClient(containerClient *arvados.Client, keepClient IKeepClient, container arvados.Container, keepMount string) {
318 e.containerClient = containerClient
319 e.container = container
320 e.keepClient = keepClient
321 e.keepMount = keepMount