-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathshellscript.go
229 lines (185 loc) · 5.2 KB
/
shellscript.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package bidengine
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
atypes "github.com/akash-network/akash-api/go/node/types/v1beta3"
"github.com/akash-network/node/sdl"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/akash-network/provider/cluster/util"
)
type shellScriptPricing struct {
path string
processLimit chan int
runtimeLimit time.Duration
}
func MakeShellScriptPricing(path string, processLimit uint, runtimeLimit time.Duration) (BidPricingStrategy, error) {
if len(path) == 0 {
return nil, errPathEmpty
}
if processLimit == 0 {
return nil, errProcessLimitZero
}
if runtimeLimit == 0 {
return nil, errProcessRuntimeLimitZero
}
result := shellScriptPricing{
path: path,
processLimit: make(chan int, processLimit),
runtimeLimit: runtimeLimit,
}
// Use the channel as a semaphore to limit the number of processes created for computing bid processes
// Most platforms put a limit on the number of processes a user can open. Even if the limit is high
// it isn't a good idea to open thousands of processes.
for i := uint(0); i != processLimit; i++ {
result.processLimit <- 0
}
return result, nil
}
func parseCPU(res *atypes.CPU) uint64 {
return res.Units.Val.Uint64()
}
func parseMemory(res *atypes.Memory) uint64 {
return res.Quantity.Val.Uint64()
}
func parseGPU(resource *atypes.GPU) gpuElement {
res := gpuElement{
Units: resource.Units.Value(),
Attributes: gpuAttributes{
Vendor: make(map[string]gpuVendorAttributes),
},
}
for _, attr := range resource.Attributes {
tokens := strings.Split(attr.Key, "/")
// vendor/nvidia/model/a100
switch tokens[0] {
case "vendor":
vendor := tokens[1]
model := tokens[3]
tokens = tokens[4:]
attrs := gpuVendorAttributes{
Model: model,
}
for i := 0; i < len(tokens); i += 2 {
key := tokens[i]
val := tokens[i+1]
switch key {
case "ram":
attrs.RAM = new(string)
*attrs.RAM = val
case "interface":
attrs.Interface = new(string)
*attrs.Interface = val
default:
continue
}
}
res.Attributes.Vendor[vendor] = attrs
default:
}
}
return res
}
func parseStorage(resource atypes.Volumes) []storageElement {
res := make([]storageElement, 0, len(resource))
for _, storage := range resource {
class := sdl.StorageEphemeral
if attr := storage.Attributes; attr != nil {
if cl, _ := attr.Find(sdl.StorageAttributeClass).AsString(); cl != "" {
class = cl
}
}
res = append(res, storageElement{
Class: class,
Size: storage.Quantity.Val.Uint64(),
})
}
return res
}
func (ssp shellScriptPricing) CalculatePrice(ctx context.Context, r Request) (sdk.DecCoin, error) {
d := newDataForScript(r)
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(&d); err != nil {
return sdk.DecCoin{}, err
}
// Take 1 from the channel
<-ssp.processLimit
defer func() {
// Always return it when this function is complete
ssp.processLimit <- 0
}()
processCtx, cancel := context.WithTimeout(ctx, ssp.runtimeLimit)
defer cancel()
cmd := exec.CommandContext(processCtx, ssp.path) // nolint: gosec
cmd.Stdin = buf
outputBuf := &bytes.Buffer{}
cmd.Stdout = outputBuf
stderrBuf := &bytes.Buffer{}
cmd.Stderr = stderrBuf
denom := r.GSpec.Price().Denom
subprocEnv := os.Environ()
subprocEnv = append(subprocEnv, fmt.Sprintf("AKASH_OWNER=%s", r.Owner))
subprocEnv = append(subprocEnv, fmt.Sprintf("AKASH_DENOM=%s", denom))
cmd.Env = subprocEnv
err := cmd.Run()
if ctxErr := processCtx.Err(); ctxErr != nil {
return sdk.DecCoin{}, ctxErr
}
if err != nil {
return sdk.DecCoin{}, fmt.Errorf("%w: script failure %s", err, stderrBuf.String())
}
// Decode the result
valueStr := strings.TrimSpace(outputBuf.String())
if valueStr == "" {
return sdk.DecCoin{}, fmt.Errorf("bid script must return amount:%w%w", io.EOF, ErrBidQuantityInvalid)
}
price, err := sdk.NewDecFromStr(valueStr)
if err != nil {
return sdk.DecCoin{}, fmt.Errorf("%w%w", err, ErrBidQuantityInvalid)
}
if price.IsZero() {
return sdk.DecCoin{}, ErrBidZero
}
if price.IsNegative() {
return sdk.DecCoin{}, ErrBidQuantityInvalid
}
return sdk.NewDecCoinFromDec(denom, price), nil
}
func newDataForScript(r Request) dataForScript {
d := dataForScript{
Resources: make([]dataForScriptElement, len(r.GSpec.Resources)),
Price: r.GSpec.Price(),
}
if r.PricePrecision > 0 {
d.PricePrecision = &r.PricePrecision
}
resources := r.GSpec.Resources
if len(r.AllocatedResources) > 0 {
resources = r.AllocatedResources
}
// iterate over everything & sum it up
for i, group := range resources {
groupCount := group.Count
cpuQuantity := parseCPU(group.CPU)
gpuQuantity := parseGPU(group.GPU)
memoryQuantity := parseMemory(group.Memory)
storageQuantity := parseStorage(group.Storage)
endpointQuantity := len(group.Endpoints)
d.Resources[i] = dataForScriptElement{
CPU: cpuQuantity,
GPU: gpuQuantity,
Memory: memoryQuantity,
Storage: storageQuantity,
Count: groupCount,
EndpointQuantity: endpointQuantity,
IPLeaseQuantity: util.GetEndpointQuantityOfResourceUnits(group.Resources, atypes.Endpoint_LEASED_IP),
}
}
return d
}