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 if e.containerClient == nil {
86 // Check if docker image is cached in keep & if so set imageFilename
88 // Cache the image to keep
89 cacheGroup, err := e.getOrCreateProject(e.container.RuntimeUserUUID, ".cache", false)
91 e.logf("error getting '.cache' project: %v", err)
94 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", false)
96 e.logf("error getting 'auto-generated singularity images' project: %s", err)
100 collectionName := fmt.Sprintf("singularity image for %v", imageId)
101 var cl arvados.CollectionList
102 err = e.containerClient.RequestAndDecode(&cl,
103 arvados.EndpointCollectionList.Method,
104 arvados.EndpointCollectionList.Path,
105 nil, arvados.ListOptions{Filters: []arvados.Filter{
106 arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
107 arvados.Filter{"name", "=", collectionName},
111 e.logf("error getting collection '%v' project: %v", err)
114 if len(cl.Items) == 0 {
115 e.logf("no cached image '%v' found", collectionName)
119 path := fmt.Sprintf("%s/by_id/%s/image.sif", e.keepMount, cl.Items[0].PortableDataHash)
120 e.logf("Looking for %v", path)
121 if _, err = os.Stat(path); os.IsNotExist(err) {
124 e.imageFilename = path
129 // LoadImage will satisfy ContainerExecuter interface transforming
130 // containerImage into a sif file for later use.
131 func (e *singularityExecutor) LoadImage(imageTarballPath string) error {
132 if e.imageFilename != "" {
133 e.logf("using singularity image %v", e.imageFilename)
135 // was set by ImageLoaded
139 e.logf("building singularity image")
140 // "singularity build" does not accept a
141 // docker-archive://... filename containing a ":" character,
142 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
143 // symlink that doesn't have ":" chars.
144 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
148 e.imageFilename = e.tmpdir + "/image.sif"
149 build := exec.Command("singularity", "build", e.imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
150 e.logf("%v", build.Args)
151 out, err := build.CombinedOutput()
152 // INFO: Starting build...
153 // Getting image source signatures
154 // Copying blob ab15617702de done
155 // Copying config 651e02b8a2 done
156 // Writing manifest to image destination
157 // Storing signatures
158 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
159 // INFO: Creating SIF file...
160 // INFO: Build complete: arvados-jobs.latest.sif
166 if e.containerClient == nil {
170 // Cache the image to keep
171 cacheGroup, err := e.getOrCreateProject(e.container.RuntimeUserUUID, ".cache", true)
173 e.logf("error getting '.cache' project: %v", err)
176 imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", true)
178 e.logf("error getting 'auto-generated singularity images' project: %v", err)
182 parts := strings.Split(imageTarballPath, "/")
183 imageId := parts[len(parts)-1]
184 if strings.HasSuffix(imageId, ".tar") {
185 imageId = imageId[0 : len(imageId)-4]
188 fs, err := (&arvados.Collection{ManifestText: ""}).FileSystem(e.containerClient, e.keepClient)
190 e.logf("error creating FileSystem: %s", err)
193 dst, err := fs.OpenFile("image.sif", os.O_CREATE|os.O_WRONLY, 0666)
195 e.logf("error creating opening collection file for writing: %s", err)
198 src, err := os.Open(e.imageFilename)
204 _, err = io.Copy(dst, src)
210 manifestText, err := fs.MarshalManifest(".")
212 e.logf("error creating manifest text: %s", err)
215 var imageCollection arvados.Collection
216 collectionName := fmt.Sprintf("singularity image for %s", imageId)
217 err = e.containerClient.RequestAndDecode(&imageCollection,
218 arvados.EndpointCollectionCreate.Method,
219 arvados.EndpointCollectionCreate.Path,
220 nil, map[string]interface{}{
221 "collection": map[string]string{
222 "owner_uuid": imageGroup.UUID,
223 "name": collectionName,
224 "manifest_text": manifestText,
228 e.logf("error creating '%v' collection: %s", collectionName, err)
234 func (e *singularityExecutor) Create(spec containerSpec) error {
239 func (e *singularityExecutor) Start() error {
240 args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
241 if !e.spec.EnableNetwork {
242 args = append(args, "--net", "--network=none")
244 readonlyflag := map[bool]string{
249 for path, _ := range e.spec.BindMounts {
250 binds = append(binds, path)
253 for _, path := range binds {
254 mount := e.spec.BindMounts[path]
255 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
258 // This is for singularity 3.5.2. There are some behaviors
259 // that will change in singularity 3.6, please see:
260 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
261 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
262 env := make([]string, 0, len(e.spec.Env))
263 for k, v := range e.spec.Env {
265 // $HOME is a special case
266 args = append(args, "--home="+v)
268 env = append(env, "SINGULARITYENV_"+k+"="+v)
272 args = append(args, e.imageFilename)
273 args = append(args, e.spec.Command...)
275 path, err := exec.LookPath(args[0])
284 Stdout: e.spec.Stdout,
285 Stderr: e.spec.Stderr,
295 func (e *singularityExecutor) CgroupID() string {
299 func (e *singularityExecutor) Stop() error {
300 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
301 // process already exited
304 return e.child.Process.Signal(syscall.SIGKILL)
307 func (e *singularityExecutor) Wait(context.Context) (int, error) {
308 err := e.child.Wait()
309 if err, ok := err.(*exec.ExitError); ok {
310 return err.ProcessState.ExitCode(), nil
315 return e.child.ProcessState.ExitCode(), nil
318 func (e *singularityExecutor) Close() {
319 err := os.RemoveAll(e.tmpdir)
321 e.logf("error removing temp dir: %s", err)
325 func (e *singularityExecutor) SetArvadoClient(containerClient *arvados.Client, keepClient IKeepClient, container arvados.Container, keepMount string) {
326 e.containerClient = containerClient
327 e.container = container
328 e.keepClient = keepClient
329 e.keepMount = keepMount