This repository has been archived by the owner on Feb 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
237 lines (186 loc) · 6.99 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
// Copyright 2020 MongoDB Inc
//
// 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 main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io/ioutil"
"net/http"
"os"
"runtime"
"github.com/TheZeroSlave/zapsentry"
"github.com/alexflint/go-arg"
"github.com/gorilla/mux"
"github.com/mongodb/atlas-osb/pkg/broker"
"github.com/mongodb/atlas-osb/pkg/broker/credentials"
"github.com/pivotal-cf/brokerapi"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const toolName = "atlas-aosb"
// releaseVersion should be set by the linker at compile time.
var releaseVersion = "0.0.0+devbuild." + getBinaryFootprint()
// command-line arguments and env variables with default values
type Args struct {
LogLevel zapcore.Level `arg:"-l,env:BROKER_LOG_LEVEL" default:"INFO"`
SentryDSN string `arg:"env:SENTRY_DSN"`
SentryLevel zapcore.Level `arg:"env:SENTRY_LEVEL" default:"ERROR"`
BrokerConfig
}
type BrokerConfig struct {
AtlasURL string `arg:"-a,env:ATLAS_BASE_URL" default:"https://cloud.mongodb.com/api/atlas/v1.0/"`
RealmURL string `arg:"-r,env:REALM_BASE_URL" default:"https://realm.mongodb.com/api/admin/v3.0/"`
Host string `arg:"-h,env:BROKER_HOST" default:"127.0.0.1"`
Port uint16 `arg:"-p,env:BROKER_PORT" default:"4000"`
CertPath string `arg:"-c,env:BROKER_TLS_CERT_FILE"`
KeyPath string `arg:"-k,env:BROKER_TLS_KEY_FILE"`
ServiceName string `arg:"env:BROKER_OSB_SERVICE_NAME" default:"atlas"`
ServiceDisplayName string `arg:"env:BROKER_OSB_SERVICE_DISPLAY_NAME" default:"Template Services"`
ServiceDesc string `arg:"env:BROKER_OSB_SERVICE_DESC" default:"MongoDB Atlas Plan Template Deployments"`
ServiceTags string `arg:"env:BROKER_OSB_SERVICE_TAGS" default:"mongodb"`
ImageURL string `arg:"env:BROKER_OSB_IMAGE_URL" default:"https://webassets.mongodb.com/_com_assets/cms/vectors-anchor-circle-mydmar539a.svg"`
DocumentationURL string `arg:"env:BROKER_OSB_DOCS_URL" default:"https://support.mongodb.com/welcome"`
ProviderDisplayName string `arg:"env:BROKER_OSB_PROVIDER_DISPLAY_NAME" default:"MongoDB"`
LongDescription string `arg:"env:BROKER_OSB_LONG_DESC" default:"Complete MongoDB Atlas deployments managed through resource templates. See https://github.com/mongodb/atlas-osb"`
}
// FIXME: update links
func (*Args) Description() string {
const helpMessage = `This is a Service Broker which provides access to MongoDB deployments running
in MongoDB Atlas. It conforms to the Open Service Broker specification and can
be used with any compatible platform, for example the Kubernetes Service Catalog.
For instructions on how to install and use the Service Broker please refer to
the documentation: https://github.com/mongodb/atlas-osb/blob/master/README.md
Github: https://github.com/mongodb/atlas-osb
Docker Image: https://TBD
`
return helpMessage
}
func (*Args) Version() string {
return fmt.Sprintf("MongoDB Atlas Service Broker v%s", releaseVersion)
}
var args Args
func main() {
p := arg.MustParse(&args)
hasCertPath := args.CertPath != ""
hasKeyPath := args.KeyPath != ""
// Bail if only one of the cert and key has been provided.
if hasCertPath != hasKeyPath {
p.Fail("Both a certificate and private key are necessary to enable TLS")
}
startBrokerServer()
}
func deduceCredentials(logger *zap.SugaredLogger, atlasURL string) *credentials.Credentials {
logger.Info("Deducing credentials source...")
logger.Info("Trying Multi-Project credentials from env...")
creds, err := credentials.FromEnv(atlasURL)
switch {
case err == nil && creds == nil:
logger.Infow("Rejected Multi-Project (env): no credentials in env")
case err == nil:
logger.Info("Selected Multi-Project (env)")
return creds
default:
logger.Fatalw("Error while loading env credentials", "error", err)
}
logger.Info("Trying Multi-Project credentials from CredHub...")
creds, err = credentials.FromCredHub(atlasURL)
switch {
case err == nil && creds == nil:
logger.Infow("Rejected Multi-Project (CredHub): not in CF")
case err == nil:
logger.Info("Selected Multi-Project (CredHub)")
return creds
default:
logger.Fatalw("Error while loading CredHub credentials", "error", err)
}
logger.Info("Selected Basic Auth")
logger.Fatal("Basic Auth credentials are not implemented yet")
return nil
}
func createBroker(logger *zap.SugaredLogger) *broker.Broker {
logger.Infow("Creating broker", "atlas_base_url", args.AtlasURL)
creds := deduceCredentials(logger, args.AtlasURL)
userAgent := fmt.Sprintf("%s/%s (%s;%s)", toolName, releaseVersion, runtime.GOOS, runtime.GOARCH)
return broker.New(logger, creds, broker.Config(args.BrokerConfig), userAgent)
}
func startBrokerServer() {
logger, err := createLogger()
if err != nil {
panic(err)
}
defer func() {
err := logger.Sync() // Flushes buffer, if any
if err != nil {
panic(err)
}
}()
b := createBroker(logger)
router := mux.NewRouter()
brokerapi.AttachRoutes(router, b, NewLagerZapLogger(logger))
router.Use(b.AuthMiddleware())
tlsEnabled := args.CertPath != ""
logger.Infow("Starting API server", "releaseVersion", releaseVersion, "host", args.Host, "port", args.Port, "tls", tlsEnabled)
// Start broker HTTP server.
address := args.Host + ":" + fmt.Sprint(args.Port)
var serverErr error
if tlsEnabled {
serverErr = http.ListenAndServeTLS(address, args.CertPath, args.KeyPath, router)
} else {
logger.Warn("TLS is disabled")
serverErr = http.ListenAndServe(address, router)
}
if serverErr != nil {
logger.Fatal(serverErr)
}
}
func addSentryLogger(log *zap.Logger) *zap.Logger {
cfg := zapsentry.Configuration{
Level: args.SentryLevel,
Tags: map[string]string{
"component": "system",
"releaseVersion": releaseVersion,
},
}
core, err := zapsentry.NewCore(cfg, zapsentry.NewSentryClientFromDSN(args.SentryDSN))
if err != nil {
log.Fatal("failed to init zap", zap.Error(err))
}
return zapsentry.AttachCoreToLogger(core, log)
}
// createLogger will create a zap sugared logger with the specified log level.
func createLogger() (*zap.SugaredLogger, error) {
config := zap.NewProductionConfig()
config.Level.SetLevel(args.LogLevel)
// https://github.com/uber-go/zap/issues/584
config.OutputPaths = []string{"stdout"}
logger, err := config.Build()
if err != nil {
return nil, err
}
if args.SentryDSN != "" {
logger = addSentryLogger(logger)
}
return logger.Sugar(), nil
}
func getBinaryFootprint() string {
fname := os.Args[0]
f, err := ioutil.ReadFile(fname)
if err != nil {
return "unknown"
}
cs := sha256.Sum256(f)
bcs := hex.EncodeToString(cs[:])
return bcs[:16]
}