1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 ErrInstanceTypesNotConfigured = errors.New("site configuration does not list any instance types")
22 discountConfiguredRAMPercent = 5
25 // ConstraintsNotSatisfiableError includes a list of available instance types
26 // to be reported back to the user.
27 type ConstraintsNotSatisfiableError struct {
29 AvailableTypes []arvados.InstanceType
32 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+(\d+)$`)
34 // estimateDockerImageSize estimates how much disk space will be used
35 // by a Docker image, given the PDH of a collection containing a
36 // Docker image that was created by "arv-keepdocker". Returns
37 // estimated number of bytes of disk space that should be reserved.
38 func estimateDockerImageSize(collectionPDH string) int64 {
39 m := pdhRegexp.FindStringSubmatch(collectionPDH)
41 log.Printf("estimateDockerImageSize: '%v' did not match pdhRegexp, returning 0", collectionPDH)
44 n, err := strconv.ParseInt(m[1], 10, 64)
45 if err != nil || n < 122 {
46 log.Printf("estimateDockerImageSize: short manifest %v or error (%v), returning 0", n, err)
49 // To avoid having to fetch the collection, take advantage of
50 // the fact that the manifest storing a container image
51 // uploaded by arv-keepdocker has a predictable format, which
52 // allows us to estimate the size of the image based on just
53 // the size of the manifest.
55 // Use the following heuristic:
56 // - Start with the length of the mainfest (n)
57 // - Subtract 80 characters for the filename and file segment
58 // - Divide by 42 to get the number of block identifiers ('hash\+size\ ' is 32+1+8+1)
59 // - Assume each block is full, multiply by 64 MiB
60 return ((n - 80) / 42) * (64 * 1024 * 1024)
63 // EstimateScratchSpace estimates how much available disk space (in
64 // bytes) is needed to run the container by summing the capacity
65 // requested by 'tmp' mounts plus disk space required to load the
67 func EstimateScratchSpace(ctr *arvados.Container) (needScratch int64) {
68 for _, m := range ctr.Mounts {
70 needScratch += m.Capacity
74 // Account for disk space usage by Docker, assumes the following behavior:
75 // - Layer tarballs are buffered to disk during "docker load".
76 // - Individual layer tarballs are extracted from buffered
77 // copy to the filesystem
78 dockerImageSize := estimateDockerImageSize(ctr.ContainerImage)
80 // The buffer is only needed during image load, so make sure
81 // the baseline scratch space at least covers dockerImageSize,
82 // and assume it will be released to the job afterwards.
83 if needScratch < dockerImageSize {
84 needScratch = dockerImageSize
87 // Now reserve space for the extracted image on disk.
88 needScratch += dockerImageSize
93 // ChooseInstanceType returns the cheapest available
94 // arvados.InstanceType big enough to run ctr.
95 func ChooseInstanceType(cc *arvados.Cluster, ctr *arvados.Container) (best arvados.InstanceType, err error) {
96 if len(cc.InstanceTypes) == 0 {
97 err = ErrInstanceTypesNotConfigured
101 needScratch := EstimateScratchSpace(ctr)
103 needVCPUs := ctr.RuntimeConstraints.VCPUs
105 needRAM := ctr.RuntimeConstraints.RAM + ctr.RuntimeConstraints.KeepCacheRAM
106 needRAM = (needRAM * 100) / int64(100-discountConfiguredRAMPercent)
109 for _, it := range cc.InstanceTypes {
111 case ok && it.Price > best.Price:
112 case int64(it.Scratch) < needScratch:
113 case int64(it.RAM) < needRAM:
114 case it.VCPUs < needVCPUs:
115 case it.Preemptible != ctr.SchedulingParameters.Preemptible:
116 case it.Price == best.Price && (it.RAM < best.RAM || it.VCPUs < best.VCPUs):
117 // Equal price, but worse specs
119 // Lower price || (same price && better specs)
125 availableTypes := make([]arvados.InstanceType, 0, len(cc.InstanceTypes))
126 for _, t := range cc.InstanceTypes {
127 availableTypes = append(availableTypes, t)
129 sort.Slice(availableTypes, func(a, b int) bool {
130 return availableTypes[a].Price < availableTypes[b].Price
132 err = ConstraintsNotSatisfiableError{
133 errors.New("constraints not satisfiable by any configured instance type"),
141 // SlurmNodeTypeFeatureKludge ensures SLURM accepts every instance
142 // type name as a valid feature name, even if no instances of that
143 // type have appeared yet.
145 // It takes advantage of some SLURM peculiarities:
147 // (1) A feature is valid after it has been offered by a node, even if
148 // it is no longer offered by any node. So, to make a feature name
149 // valid, we can add it to a dummy node ("compute0"), then remove it.
151 // (2) To test whether a set of feature names are valid without
152 // actually submitting a job, we can call srun --test-only with the
155 // SlurmNodeTypeFeatureKludge does a test-and-fix operation
156 // immediately, and then periodically, in case slurm restarts and
157 // forgets the list of valid features. It never returns (unless there
158 // are no node types configured, in which case it returns
159 // immediately), so it should generally be invoked with "go".
160 func SlurmNodeTypeFeatureKludge(cc *arvados.Cluster) {
161 if len(cc.InstanceTypes) == 0 {
164 var features []string
165 for _, it := range cc.InstanceTypes {
166 features = append(features, "instancetype="+it.Name)
169 slurmKludge(features)
170 time.Sleep(2 * time.Second)
174 const slurmDummyNode = "compute0"
176 func slurmKludge(features []string) {
177 allFeatures := strings.Join(features, ",")
179 cmd := exec.Command("sinfo", "--nodes="+slurmDummyNode, "--format=%f", "--noheader")
180 out, err := cmd.CombinedOutput()
182 log.Printf("running %q %q: %s (output was %q)", cmd.Path, cmd.Args, err, out)
185 if string(out) == allFeatures+"\n" {
186 // Already configured correctly, nothing to do.
190 log.Printf("configuring node %q with all node type features", slurmDummyNode)
191 cmd = exec.Command("scontrol", "update", "NodeName="+slurmDummyNode, "Features="+allFeatures)
192 log.Printf("running: %q %q", cmd.Path, cmd.Args)
193 out, err = cmd.CombinedOutput()
195 log.Printf("error: scontrol: %s (output was %q)", err, out)