-
Notifications
You must be signed in to change notification settings - Fork 777
/
controller.go
208 lines (179 loc) · 6.72 KB
/
controller.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
// 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 gameserverallocations
import (
"context"
"io/ioutil"
"mime"
"net/http"
"time"
"github.com/heptiolabs/healthcheck"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sruntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/record"
allocationv1 "agones.dev/agones/pkg/apis/allocation/v1"
"agones.dev/agones/pkg/client/clientset/versioned"
"agones.dev/agones/pkg/client/informers/externalversions"
"agones.dev/agones/pkg/gameservers"
"agones.dev/agones/pkg/util/apiserver"
"agones.dev/agones/pkg/util/https"
"agones.dev/agones/pkg/util/runtime"
)
// Controller is a the GameServerAllocation controller
type Controller struct {
api *apiserver.APIServer
baseLogger *logrus.Entry
recorder record.EventRecorder
allocator *Allocator
}
// NewController returns a controller for a GameServerAllocation
func NewController(apiServer *apiserver.APIServer,
health healthcheck.Handler,
counter *gameservers.PerNodeCounter,
kubeClient kubernetes.Interface,
kubeInformerFactory informers.SharedInformerFactory,
agonesClient versioned.Interface,
agonesInformerFactory externalversions.SharedInformerFactory,
remoteAllocationTimeout time.Duration,
totalAllocationTimeout time.Duration,
allocationBatchWaitTime time.Duration,
) *Controller {
c := &Controller{
api: apiServer,
allocator: NewAllocator(
agonesInformerFactory.Multicluster().V1().GameServerAllocationPolicies(),
kubeInformerFactory.Core().V1().Secrets(),
agonesClient.AgonesV1(),
kubeClient,
NewAllocationCache(agonesInformerFactory.Agones().V1().GameServers(), counter, health),
remoteAllocationTimeout,
totalAllocationTimeout,
allocationBatchWaitTime),
}
c.baseLogger = runtime.NewLoggerWithType(c)
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(c.baseLogger.Debugf)
eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeClient.CoreV1().Events("")})
c.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: "GameServerAllocation-controller"})
return c
}
// registers the api resource for gameserverallocation
func (c *Controller) registerAPIResource(ctx context.Context) {
resource := metav1.APIResource{
Name: "gameserverallocations",
SingularName: "gameserverallocation",
Namespaced: true,
Kind: "GameServerAllocation",
Verbs: []string{
"create",
},
ShortNames: []string{"gsa"},
}
c.api.AddAPIResource(allocationv1.SchemeGroupVersion.String(), resource, func(w http.ResponseWriter, r *http.Request, n string) error {
return c.processAllocationRequest(ctx, w, r, n)
})
}
// Run runs this controller. Will block until stop is closed.
// Ignores threadiness, as we only needs 1 worker for cache sync
func (c *Controller) Run(ctx context.Context, _ int) error {
if err := c.allocator.Run(ctx); err != nil {
return err
}
c.registerAPIResource(ctx)
return nil
}
func (c *Controller) processAllocationRequest(ctx context.Context, w http.ResponseWriter, r *http.Request, namespace string) (err error) {
if r.Body != nil {
defer r.Body.Close() // nolint: errcheck
}
log := https.LogRequest(c.baseLogger, r)
if r.Method != http.MethodPost {
log.Warn("allocation handler only supports POST")
http.Error(w, "Method not supported", http.StatusMethodNotAllowed)
return
}
gsa, err := c.allocationDeserialization(r, namespace)
if err != nil {
return err
}
result, err := c.allocator.Allocate(ctx, gsa)
if err != nil {
return err
}
var code int
switch obj := result.(type) {
case *metav1.Status:
code = int(obj.Code)
case *allocationv1.GameServerAllocation:
code = http.StatusCreated
default:
code = http.StatusOK
}
err = c.serialisation(r, w, result, code, scheme.Codecs)
return err
}
// allocationDeserialization processes the request and namespace, and attempts to deserialise its values
// into a GameServerAllocation. Returns an error if it fails for whatever reason.
func (c *Controller) allocationDeserialization(r *http.Request, namespace string) (*allocationv1.GameServerAllocation, error) {
gsa := &allocationv1.GameServerAllocation{}
gvks, _, err := scheme.Scheme.ObjectKinds(gsa)
if err != nil {
return gsa, errors.Wrap(err, "error getting objectkinds for gameserverallocation")
}
gsa.TypeMeta = metav1.TypeMeta{Kind: gvks[0].Kind, APIVersion: gvks[0].Version}
mediaTypes := scheme.Codecs.SupportedMediaTypes()
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return gsa, errors.Wrap(err, "error parsing mediatype from a request header")
}
info, ok := k8sruntime.SerializerInfoForMediaType(mediaTypes, mt)
if !ok {
return gsa, errors.New("Could not find deserializer")
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return gsa, errors.Wrap(err, "could not read body")
}
gvk := allocationv1.SchemeGroupVersion.WithKind("GameServerAllocation")
_, _, err = info.Serializer.Decode(b, &gvk, gsa)
if err != nil {
c.baseLogger.WithField("body", string(b)).Error("error decoding body")
return gsa, errors.Wrap(err, "error decoding body")
}
gsa.ObjectMeta.Namespace = namespace
gsa.ObjectMeta.CreationTimestamp = metav1.Now()
gsa.ApplyDefaults()
return gsa, nil
}
// serialisation takes a runtime.Object, and serialise it to the ResponseWriter in the requested format
func (c *Controller) serialisation(r *http.Request, w http.ResponseWriter, obj k8sruntime.Object, statusCode int, codecs serializer.CodecFactory) error {
info, err := apiserver.AcceptedSerializer(r, codecs)
if err != nil {
return errors.Wrapf(err, "failed to find serialisation info for %T object", obj)
}
w.Header().Set("Content-Type", info.MediaType)
// we have to do this here, so that the content type is set before we send a HTTP status header, as the WriteHeader
// call will send data to the client.
w.WriteHeader(statusCode)
err = info.Serializer.Encode(obj, w)
return errors.Wrapf(err, "error encoding %T", obj)
}