-
Notifications
You must be signed in to change notification settings - Fork 807
/
main.go
325 lines (287 loc) · 10.2 KB
/
main.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// 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.
// sidecar for the game server that the sdk connects to
package main
import (
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"agones.dev/agones/pkg"
"agones.dev/agones/pkg/client/clientset/versioned"
"agones.dev/agones/pkg/sdk"
sdkalpha "agones.dev/agones/pkg/sdk/alpha"
sdkbeta "agones.dev/agones/pkg/sdk/beta"
"agones.dev/agones/pkg/sdkserver"
serveralpha "agones.dev/agones/pkg/sdkserver/alpha"
serverbeta "agones.dev/agones/pkg/sdkserver/beta"
"agones.dev/agones/pkg/util/runtime"
"agones.dev/agones/pkg/util/signals"
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/pkg/errors"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"golang.org/x/net/context"
"google.golang.org/grpc"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const (
defaultGRPCPort = 9357
defaultHTTPPort = 9358
// specifically env vars
gameServerNameEnv = "GAMESERVER_NAME"
podNamespaceEnv = "POD_NAMESPACE"
// Flags (that can also be env vars)
localFlag = "local"
fileFlag = "file"
testFlag = "test"
addressFlag = "address"
delayFlag = "delay"
timeoutFlag = "timeout"
grpcPortFlag = "grpc-port"
httpPortFlag = "http-port"
)
var (
logger = runtime.NewLoggerWithSource("main")
)
func main() {
ctlConf := parseEnvFlags()
logger.WithField("version", pkg.Version).WithField("featureGates", runtime.EncodeFeatures()).
WithField("ctlConf", ctlConf).Info("Starting sdk sidecar")
if ctlConf.Delay > 0 {
logger.Infof("Waiting %d seconds before starting", ctlConf.Delay)
time.Sleep(time.Duration(ctlConf.Delay) * time.Second)
}
stop := signals.NewStopChannel()
timedStop := make(chan struct{})
grpcServer := grpc.NewServer()
// don't graceful stop, because if we get a kill signal
// then the gameserver is being shut down, and we no longer
// care about running RPC calls.
defer grpcServer.Stop()
mux := gwruntime.NewServeMux()
httpServer := &http.Server{
Addr: fmt.Sprintf("%s:%d", ctlConf.Address, ctlConf.HTTPPort),
Handler: mux,
}
defer httpServer.Close() // nolint: errcheck
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
switch {
case ctlConf.IsLocal:
cancel, err := registerLocal(grpcServer, ctlConf)
if err != nil {
logger.WithError(err).Fatal("Could not start local sdk server")
}
defer cancel()
if ctlConf.Timeout != 0 {
go func() {
time.Sleep(time.Duration(ctlConf.Timeout) * time.Second)
close(timedStop)
}()
}
case ctlConf.Test != "":
cancel, err := registerTestSdkServer(grpcServer, ctlConf)
if err != nil {
logger.WithError(err).Fatal("Could not start test sdk server")
}
defer cancel()
if ctlConf.Timeout != 0 {
go func() {
time.Sleep(time.Duration(ctlConf.Timeout) * time.Second)
close(timedStop)
}()
}
default:
var config *rest.Config
config, err := rest.InClusterConfig()
if err != nil {
logger.WithError(err).Fatal("Could not create in cluster config")
}
var kubeClient *kubernetes.Clientset
kubeClient, err = kubernetes.NewForConfig(config)
if err != nil {
logger.WithError(err).Fatal("Could not create the kubernetes clientset")
}
var agonesClient *versioned.Clientset
agonesClient, err = versioned.NewForConfig(config)
if err != nil {
logger.WithError(err).Fatalf("Could not create the agones api clientset")
}
var s *sdkserver.SDKServer
s, err = sdkserver.NewSDKServer(viper.GetString(gameServerNameEnv),
viper.GetString(podNamespaceEnv), kubeClient, agonesClient)
if err != nil {
logger.WithError(err).Fatalf("Could not start sidecar")
}
go func() {
err := s.Run(ctx.Done())
if err != nil {
logger.WithError(err).Fatalf("Could not run sidecar")
}
}()
sdk.RegisterSDKServer(grpcServer, s)
sdkalpha.RegisterSDKServer(grpcServer, serveralpha.NewSDKServer())
sdkbeta.RegisterSDKServer(grpcServer, serverbeta.NewSDKServer())
}
grpcEndpoint := fmt.Sprintf("%s:%d", ctlConf.Address, ctlConf.GRPCPort)
go runGrpc(grpcServer, grpcEndpoint)
go runGateway(ctx, grpcEndpoint, mux, httpServer)
select {
case <-stop:
case <-timedStop:
}
logger.Info("shutting down sdk server")
}
// registerLocal registers the local SDK servers, and returns a cancel func that
// closes all the SDK implementations
func registerLocal(grpcServer *grpc.Server, ctlConf config) (func(), error) {
filePath := ""
if ctlConf.LocalFile != "" {
filePath, err := filepath.Abs(ctlConf.LocalFile)
if err != nil {
return nil, err
}
if _, err = os.Stat(filePath); os.IsNotExist(err) {
return nil, errors.Errorf("Could not find file: %s", filePath)
}
}
stableSDK, err := sdkserver.NewLocalSDKServer(filePath)
if err != nil {
return nil, err
}
alphaSDK := serveralpha.NewLocalSDKServer()
betaSDK := serverbeta.NewLocalSDKServer()
sdk.RegisterSDKServer(grpcServer, stableSDK)
sdkalpha.RegisterSDKServer(grpcServer, alphaSDK)
sdkbeta.RegisterSDKServer(grpcServer, betaSDK)
return func() {
alphaSDK.Close()
betaSDK.Close()
stableSDK.Close()
}, err
}
// registerLocal registers the local test SDK servers, and returns a cancel func that
// closes all the SDK implementations
func registerTestSdkServer(grpcServer *grpc.Server, ctlConf config) (func(), error) {
stableSDK, err := sdkserver.NewLocalSDKServer("")
if err != nil {
return nil, err
}
alphaSDK := serveralpha.NewLocalSDKServer()
betaSDK := serverbeta.NewLocalSDKServer()
stableSDK.SetTestMode(true)
stableSDK.GenerateUID()
expectedFuncs := strings.Split(ctlConf.Test, ",")
stableSDK.SetExpectedSequence(expectedFuncs)
sdk.RegisterSDKServer(grpcServer, stableSDK)
sdkalpha.RegisterSDKServer(grpcServer, alphaSDK)
sdkbeta.RegisterSDKServer(grpcServer, betaSDK)
return func() {
alphaSDK.Close()
betaSDK.Close()
stableSDK.Close()
}, err
}
// runGrpc runs the grpc service
func runGrpc(grpcServer *grpc.Server, grpcEndpoint string) {
lis, err := net.Listen("tcp", grpcEndpoint)
if err != nil {
logger.WithField("grpcEndpoint", grpcEndpoint).Fatal("Could not listen on grpc endpoint")
}
logger.WithField("grpcEndpoint", grpcEndpoint).Info("Starting SDKServer grpc service...")
if err := grpcServer.Serve(lis); err != nil {
logger.WithError(err).Fatal("Could not serve grpc server")
}
}
// runGateway runs the grpc-gateway
func runGateway(ctx context.Context, grpcEndpoint string, mux *gwruntime.ServeMux, httpServer *http.Server) {
conn, err := grpc.DialContext(ctx, grpcEndpoint, grpc.WithBlock(), grpc.WithInsecure())
if err != nil {
logger.WithError(err).Fatal("Could not dial grpc server...")
}
if err = sdk.RegisterSDKHandler(ctx, mux, conn); err != nil {
logger.WithError(err).Fatal("Could not register grpc-gateway")
}
logger.WithField("httpEndpoint", httpServer.Addr).Info("Starting SDKServer grpc-gateway...")
if err := httpServer.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
logger.WithError(err).Info("http server closed")
} else {
logger.WithError(err).Fatal("Could not serve http server")
}
}
}
// parseEnvFlags parses all the flags and environment variables and returns
// a configuration structure
func parseEnvFlags() config {
viper.AllowEmptyEnv(true)
viper.SetDefault(localFlag, false)
viper.SetDefault(fileFlag, "")
viper.SetDefault(testFlag, "")
viper.SetDefault(addressFlag, "localhost")
viper.SetDefault(delayFlag, 0)
viper.SetDefault(timeoutFlag, 0)
viper.SetDefault(grpcPortFlag, defaultGRPCPort)
viper.SetDefault(httpPortFlag, defaultHTTPPort)
pflag.Bool(localFlag, viper.GetBool(localFlag),
"Set this, or LOCAL env, to 'true' to run this binary in local development mode. Defaults to 'false'")
pflag.StringP(fileFlag, "f", viper.GetString(fileFlag), "Set this, or FILE env var to the path of a local yaml or json file that contains your GameServer resoure configuration")
pflag.String(addressFlag, viper.GetString(addressFlag), "The Address to bind the server grpcPort to. Defaults to 'localhost'")
pflag.Int(grpcPortFlag, viper.GetInt(grpcPortFlag), fmt.Sprintf("Port on which to bind the gRPC server. Defaults to %d", defaultGRPCPort))
pflag.Int(httpPortFlag, viper.GetInt(httpPortFlag), fmt.Sprintf("Port on which to bind the HTTP server. Defaults to %d", defaultHTTPPort))
pflag.Int(delayFlag, viper.GetInt(delayFlag), "Time to delay (in seconds) before starting to execute main. Useful for tests")
pflag.Int(timeoutFlag, viper.GetInt(timeoutFlag), "Time of execution (in seconds) before close. Useful for tests")
pflag.String(testFlag, viper.GetString(testFlag), "List functions which shoud be called during the SDK Conformance test run.")
runtime.FeaturesBindFlags()
pflag.Parse()
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
runtime.Must(viper.BindEnv(localFlag))
runtime.Must(viper.BindEnv(addressFlag))
runtime.Must(viper.BindEnv(testFlag))
runtime.Must(viper.BindEnv(gameServerNameEnv))
runtime.Must(viper.BindEnv(podNamespaceEnv))
runtime.Must(viper.BindEnv(delayFlag))
runtime.Must(viper.BindEnv(timeoutFlag))
runtime.Must(viper.BindEnv(grpcPortFlag))
runtime.Must(viper.BindEnv(httpPortFlag))
runtime.Must(viper.BindPFlags(pflag.CommandLine))
runtime.Must(runtime.FeaturesBindEnv())
runtime.Must(runtime.ParseFeaturesFromEnv())
return config{
IsLocal: viper.GetBool(localFlag),
Address: viper.GetString(addressFlag),
LocalFile: viper.GetString(fileFlag),
Delay: viper.GetInt(delayFlag),
Timeout: viper.GetInt(timeoutFlag),
Test: viper.GetString(testFlag),
GRPCPort: viper.GetInt(grpcPortFlag),
HTTPPort: viper.GetInt(httpPortFlag),
}
}
// config is all the configuration for this program
type config struct {
Address string
IsLocal bool
LocalFile string
Delay int
Timeout int
Test string
GRPCPort int
HTTPPort int
}