14495: Add warnings when estimateDockerImageSize gets bad input
[arvados.git] / lib / dispatchcloud / node_size.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package dispatchcloud
6
7 import (
8         "errors"
9         "log"
10         "os/exec"
11         "regexp"
12         "sort"
13         "strconv"
14         "strings"
15         "time"
16
17         "git.curoverse.com/arvados.git/sdk/go/arvados"
18 )
19
20 var (
21         ErrInstanceTypesNotConfigured = errors.New("site configuration does not list any instance types")
22         discountConfiguredRAMPercent  = 5
23 )
24
25 // ConstraintsNotSatisfiableError includes a list of available instance types
26 // to be reported back to the user.
27 type ConstraintsNotSatisfiableError struct {
28         error
29         AvailableTypes []arvados.InstanceType
30 }
31
32 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+(\d+)$`)
33
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)
40         if m == nil {
41                 log.Printf("estimateDockerImageSize: '%v' did not match pdhRegexp, returning 0", collectionPDH)
42                 return 0
43         }
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)
47                 return 0
48         }
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.
54         //
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)
61 }
62
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
66 // Docker image.
67 func EstimateScratchSpace(ctr *arvados.Container) (needScratch int64) {
68         for _, m := range ctr.Mounts {
69                 if m.Kind == "tmp" {
70                         needScratch += m.Capacity
71                 }
72         }
73
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)
79
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
85         }
86
87         // Now reserve space for the extracted image on disk.
88         needScratch += dockerImageSize
89
90         return
91 }
92
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
98                 return
99         }
100
101         needScratch := EstimateScratchSpace(ctr)
102
103         needVCPUs := ctr.RuntimeConstraints.VCPUs
104
105         needRAM := ctr.RuntimeConstraints.RAM + ctr.RuntimeConstraints.KeepCacheRAM
106         needRAM = (needRAM * 100) / int64(100-discountConfiguredRAMPercent)
107
108         ok := false
109         for _, it := range cc.InstanceTypes {
110                 switch {
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
118                 default:
119                         // Lower price || (same price && better specs)
120                         best = it
121                         ok = true
122                 }
123         }
124         if !ok {
125                 availableTypes := make([]arvados.InstanceType, 0, len(cc.InstanceTypes))
126                 for _, t := range cc.InstanceTypes {
127                         availableTypes = append(availableTypes, t)
128                 }
129                 sort.Slice(availableTypes, func(a, b int) bool {
130                         return availableTypes[a].Price < availableTypes[b].Price
131                 })
132                 err = ConstraintsNotSatisfiableError{
133                         errors.New("constraints not satisfiable by any configured instance type"),
134                         availableTypes,
135                 }
136                 return
137         }
138         return
139 }
140
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.
144 //
145 // It takes advantage of some SLURM peculiarities:
146 //
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.
150 //
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
153 // desired features.
154 //
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 {
162                 return
163         }
164         var features []string
165         for _, it := range cc.InstanceTypes {
166                 features = append(features, "instancetype="+it.Name)
167         }
168         for {
169                 slurmKludge(features)
170                 time.Sleep(2 * time.Second)
171         }
172 }
173
174 const slurmDummyNode = "compute0"
175
176 func slurmKludge(features []string) {
177         allFeatures := strings.Join(features, ",")
178
179         cmd := exec.Command("sinfo", "--nodes="+slurmDummyNode, "--format=%f", "--noheader")
180         out, err := cmd.CombinedOutput()
181         if err != nil {
182                 log.Printf("running %q %q: %s (output was %q)", cmd.Path, cmd.Args, err, out)
183                 return
184         }
185         if string(out) == allFeatures+"\n" {
186                 // Already configured correctly, nothing to do.
187                 return
188         }
189
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()
194         if err != nil {
195                 log.Printf("error: scontrol: %s (output was %q)", err, out)
196         }
197 }