/
fleetautoscalers.go
226 lines (193 loc) · 5.94 KB
/
fleetautoscalers.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
/*
* Copyright 2018 Google LLC All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fleetautoscalers
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/url"
"strings"
"time"
agonesv1 "agones.dev/agones/pkg/apis/agones/v1"
autoscalingv1 "agones.dev/agones/pkg/apis/autoscaling/v1"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/uuid"
)
var client = http.Client{
Timeout: 15 * time.Second,
}
// computeDesiredFleetSize computes the new desired size of the given fleet
func computeDesiredFleetSize(fas *autoscalingv1.FleetAutoscaler, f *agonesv1.Fleet) (int32, bool, error) {
switch fas.Spec.Policy.Type {
case autoscalingv1.BufferPolicyType:
return applyBufferPolicy(fas.Spec.Policy.Buffer, f)
case autoscalingv1.WebhookPolicyType:
return applyWebhookPolicy(fas.Spec.Policy.Webhook, f)
}
return 0, false, errors.New("wrong policy type, should be one of: Buffer, Webhook")
}
// buildURLFromWebhookPolicy - build URL for Webhook and set CARoot for client Transport
func buildURLFromWebhookPolicy(w *autoscalingv1.WebhookPolicy) (u *url.URL, err error) {
if w.URL != nil && w.Service != nil {
return nil, errors.New("service and URL cannot be used simultaneously")
}
scheme := "http"
if w.CABundle != nil {
scheme = "https"
if err := setCABundle(w.CABundle); err != nil {
return nil, err
}
}
if w.URL != nil {
if *w.URL == "" {
return nil, errors.New("URL was not provided")
}
return url.ParseRequestURI(*w.URL)
}
if w.Service == nil {
return nil, errors.New("service was not provided, either URL or Service must be provided")
}
if w.Service.Name == "" {
return nil, errors.New("service name was not provided")
}
if w.Service.Path == nil {
empty := ""
w.Service.Path = &empty
}
if w.Service.Namespace == "" {
w.Service.Namespace = "default"
}
return createURL(scheme, w.Service.Name, w.Service.Namespace, *w.Service.Path, w.Service.Port), nil
}
// moved to a separate method to cover it with unit tests and check that URL corresponds to a proper pattern
func createURL(scheme, name, namespace, path string, port *int32) *url.URL {
var hostPort int32 = 8000
if port != nil {
hostPort = *port
}
return &url.URL{
Scheme: scheme,
Host: fmt.Sprintf("%s.%s.svc:%d", name, namespace, hostPort),
Path: path,
}
}
func setCABundle(caBundle []byte) error {
// We can have multiple fleetautoscalers with different CABundles defined,
// so we switch client.Transport before each POST request
rootCAs := x509.NewCertPool()
if ok := rootCAs.AppendCertsFromPEM(caBundle); !ok {
return errors.New("no certs were appended from caBundle")
}
client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: rootCAs,
},
}
return nil
}
func applyWebhookPolicy(w *autoscalingv1.WebhookPolicy, f *agonesv1.Fleet) (replicas int32, limited bool, err error) {
if w == nil {
return 0, false, errors.New("webhookPolicy parameter must not be nil")
}
if f == nil {
return 0, false, errors.New("fleet parameter must not be nil")
}
u, err := buildURLFromWebhookPolicy(w)
if err != nil {
return 0, false, err
}
faReq := autoscalingv1.FleetAutoscaleReview{
Request: &autoscalingv1.FleetAutoscaleRequest{
UID: uuid.NewUUID(),
Name: f.Name,
Namespace: f.Namespace,
Status: f.Status,
},
Response: nil,
}
b, err := json.Marshal(faReq)
if err != nil {
return 0, false, err
}
res, err := client.Post(
u.String(),
"application/json",
strings.NewReader(string(b)),
)
if err != nil {
return 0, false, err
}
defer func() {
if cerr := res.Body.Close(); cerr != nil {
if err != nil {
err = errors.Wrap(err, cerr.Error())
} else {
err = cerr
}
}
}()
if res.StatusCode != http.StatusOK {
return 0, false, fmt.Errorf("bad status code %d from the server: %s", res.StatusCode, u.String())
}
result, err := ioutil.ReadAll(res.Body)
if err != nil {
return 0, false, err
}
var faResp autoscalingv1.FleetAutoscaleReview
err = json.Unmarshal(result, &faResp)
if err != nil {
return 0, false, err
}
if faResp.Response.Scale {
return faResp.Response.Replicas, false, nil
}
return f.Status.Replicas, false, nil
}
func applyBufferPolicy(b *autoscalingv1.BufferPolicy, f *agonesv1.Fleet) (int32, bool, error) {
var replicas int32
if b.BufferSize.Type == intstr.Int {
replicas = f.Status.AllocatedReplicas + int32(b.BufferSize.IntValue())
} else {
// the percentage value is a little more complex, as we can't apply
// the desired percentage to any current value, but to the future one
// Example: we have 8 allocated replicas, 10 total replicas and bufferSize set to 30%
// 30% means that we must have 30% ready instances in the fleet
// Right now there are 20%, so we must increase the fleet until we reach 30%
// To compute the new size, we start from the other end: if ready must be 30%
// it means that allocated must be 70% and adjust the fleet size to make that true.
bufferPercent, err := intstr.GetValueFromIntOrPercent(&b.BufferSize, 100, true)
if err != nil {
return 0, false, err
}
// use Math.Ceil to round the result up
replicas = int32(math.Ceil(float64(f.Status.AllocatedReplicas*100) / float64(100-bufferPercent)))
}
limited := false
if replicas < b.MinReplicas {
replicas = b.MinReplicas
limited = true
}
if replicas > b.MaxReplicas {
replicas = b.MaxReplicas
limited = true
}
return replicas, limited, nil
}