21700: Install Bundler system-wide in Rails postinst
[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         "math"
10         "regexp"
11         "sort"
12         "strconv"
13
14         "git.arvados.org/arvados.git/sdk/go/arvados"
15 )
16
17 var ErrInstanceTypesNotConfigured = errors.New("site configuration does not list any instance types")
18
19 var discountConfiguredRAMPercent = 5
20
21 // ConstraintsNotSatisfiableError includes a list of available instance types
22 // to be reported back to the user.
23 type ConstraintsNotSatisfiableError struct {
24         error
25         AvailableTypes []arvados.InstanceType
26 }
27
28 var pdhRegexp = regexp.MustCompile(`^[0-9a-f]{32}\+(\d+)$`)
29
30 // estimateDockerImageSize estimates how much disk space will be used
31 // by a Docker image, given the PDH of a collection containing a
32 // Docker image that was created by "arv-keepdocker".  Returns
33 // estimated number of bytes of disk space that should be reserved.
34 func estimateDockerImageSize(collectionPDH string) int64 {
35         m := pdhRegexp.FindStringSubmatch(collectionPDH)
36         if m == nil {
37                 return 0
38         }
39         n, err := strconv.ParseInt(m[1], 10, 64)
40         if err != nil || n < 122 {
41                 return 0
42         }
43         // To avoid having to fetch the collection, take advantage of
44         // the fact that the manifest storing a container image
45         // uploaded by arv-keepdocker has a predictable format, which
46         // allows us to estimate the size of the image based on just
47         // the size of the manifest.
48         //
49         // Use the following heuristic:
50         // - Start with the length of the manifest (n)
51         // - Subtract 80 characters for the filename and file segment
52         // - Divide by 42 to get the number of block identifiers ('hash\+size\ ' is 32+1+8+1)
53         // - Assume each block is full, multiply by 64 MiB
54         return ((n - 80) / 42) * (64 * 1024 * 1024)
55 }
56
57 // EstimateScratchSpace estimates how much available disk space (in
58 // bytes) is needed to run the container by summing the capacity
59 // requested by 'tmp' mounts plus disk space required to load the
60 // Docker image plus arv-mount block cache.
61 func EstimateScratchSpace(ctr *arvados.Container) (needScratch int64) {
62         for _, m := range ctr.Mounts {
63                 if m.Kind == "tmp" {
64                         needScratch += m.Capacity
65                 }
66         }
67
68         // Account for disk space usage by Docker, assumes the following behavior:
69         // - Layer tarballs are buffered to disk during "docker load".
70         // - Individual layer tarballs are extracted from buffered
71         // copy to the filesystem
72         dockerImageSize := estimateDockerImageSize(ctr.ContainerImage)
73
74         // The buffer is only needed during image load, so make sure
75         // the baseline scratch space at least covers dockerImageSize,
76         // and assume it will be released to the job afterwards.
77         if needScratch < dockerImageSize {
78                 needScratch = dockerImageSize
79         }
80
81         // Now reserve space for the extracted image on disk.
82         needScratch += dockerImageSize
83
84         // Now reserve space the arv-mount disk cache
85         needScratch += ctr.RuntimeConstraints.KeepCacheDisk
86
87         return
88 }
89
90 // compareVersion returns true if vs1 < vs2, otherwise false
91 func versionLess(vs1 string, vs2 string) (bool, error) {
92         v1, err := strconv.ParseFloat(vs1, 64)
93         if err != nil {
94                 return false, err
95         }
96         v2, err := strconv.ParseFloat(vs2, 64)
97         if err != nil {
98                 return false, err
99         }
100         return v1 < v2, nil
101 }
102
103 // ChooseInstanceType returns the arvados.InstanceTypes eligible to
104 // run ctr, i.e., those that have enough RAM, VCPUs, etc., and are not
105 // too expensive according to cluster configuration.
106 //
107 // The returned types are sorted with lower prices first.
108 //
109 // The error is non-nil if and only if the returned slice is empty.
110 func ChooseInstanceType(cc *arvados.Cluster, ctr *arvados.Container) ([]arvados.InstanceType, error) {
111         if len(cc.InstanceTypes) == 0 {
112                 return nil, ErrInstanceTypesNotConfigured
113         }
114
115         needScratch := EstimateScratchSpace(ctr)
116
117         needVCPUs := ctr.RuntimeConstraints.VCPUs
118
119         needRAM := ctr.RuntimeConstraints.RAM + ctr.RuntimeConstraints.KeepCacheRAM
120         needRAM += int64(cc.Containers.ReserveExtraRAM)
121         if cc.Containers.LocalKeepBlobBuffersPerVCPU > 0 {
122                 // + 200 MiB for keepstore process + 10% for GOGC=10
123                 needRAM += 220 << 20
124                 // + 64 MiB for each blob buffer + 10% for GOGC=10
125                 needRAM += int64(cc.Containers.LocalKeepBlobBuffersPerVCPU * needVCPUs * (1 << 26) * 11 / 10)
126         }
127         needRAM = (needRAM * 100) / int64(100-discountConfiguredRAMPercent)
128
129         maxPriceFactor := math.Max(cc.Containers.MaximumPriceFactor, 1)
130         var types []arvados.InstanceType
131         var maxPrice float64
132         for _, it := range cc.InstanceTypes {
133                 driverInsuff, driverErr := versionLess(it.CUDA.DriverVersion, ctr.RuntimeConstraints.CUDA.DriverVersion)
134                 capabilityInsuff, capabilityErr := versionLess(it.CUDA.HardwareCapability, ctr.RuntimeConstraints.CUDA.HardwareCapability)
135
136                 switch {
137                 // reasons to reject a node
138                 case maxPrice > 0 && it.Price > maxPrice: // too expensive
139                 case int64(it.Scratch) < needScratch: // insufficient scratch
140                 case int64(it.RAM) < needRAM: // insufficient RAM
141                 case it.VCPUs < needVCPUs: // insufficient VCPUs
142                 case it.Preemptible != ctr.SchedulingParameters.Preemptible: // wrong preemptable setting
143                 case it.CUDA.DeviceCount < ctr.RuntimeConstraints.CUDA.DeviceCount: // insufficient CUDA devices
144                 case ctr.RuntimeConstraints.CUDA.DeviceCount > 0 && (driverInsuff || driverErr != nil): // insufficient driver version
145                 case ctr.RuntimeConstraints.CUDA.DeviceCount > 0 && (capabilityInsuff || capabilityErr != nil): // insufficient hardware capability
146                         // Don't select this node
147                 default:
148                         // Didn't reject the node, so select it
149                         types = append(types, it)
150                         if newmax := it.Price * maxPriceFactor; newmax < maxPrice || maxPrice == 0 {
151                                 maxPrice = newmax
152                         }
153                 }
154         }
155         if len(types) == 0 {
156                 availableTypes := make([]arvados.InstanceType, 0, len(cc.InstanceTypes))
157                 for _, t := range cc.InstanceTypes {
158                         availableTypes = append(availableTypes, t)
159                 }
160                 sort.Slice(availableTypes, func(a, b int) bool {
161                         return availableTypes[a].Price < availableTypes[b].Price
162                 })
163                 return nil, ConstraintsNotSatisfiableError{
164                         errors.New("constraints not satisfiable by any configured instance type"),
165                         availableTypes,
166                 }
167         }
168         sort.Slice(types, func(i, j int) bool {
169                 if types[i].Price != types[j].Price {
170                         // prefer lower price
171                         return types[i].Price < types[j].Price
172                 }
173                 if types[i].RAM != types[j].RAM {
174                         // if same price, prefer more RAM
175                         return types[i].RAM > types[j].RAM
176                 }
177                 if types[i].VCPUs != types[j].VCPUs {
178                         // if same price and RAM, prefer more VCPUs
179                         return types[i].VCPUs > types[j].VCPUs
180                 }
181                 if types[i].Scratch != types[j].Scratch {
182                         // if same price and RAM and VCPUs, prefer more scratch
183                         return types[i].Scratch > types[j].Scratch
184                 }
185                 // no preference, just sort the same way each time
186                 return types[i].Name < types[j].Name
187         })
188         // Truncate types at maxPrice. We rejected it.Price>maxPrice
189         // in the loop above, but at that point maxPrice wasn't
190         // necessarily the final (lowest) maxPrice.
191         for i, it := range types {
192                 if i > 0 && it.Price > maxPrice {
193                         types = types[:i]
194                         break
195                 }
196         }
197         return types, nil
198 }