-
Notifications
You must be signed in to change notification settings - Fork 66
/
corge.go
219 lines (193 loc) · 8.29 KB
/
corge.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
// Code generated by zanzibar
// @generated
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package corgeclient
import (
"context"
"errors"
"strconv"
"strings"
"time"
"github.com/afex/hystrix-go/hystrix"
"go.uber.org/zap"
tchannel "github.com/uber/tchannel-go"
zanzibar "github.com/uber/zanzibar/runtime"
module "github.com/uber/zanzibar/examples/example-gateway/build/clients/corge/module"
clientsCorgeCorge "github.com/uber/zanzibar/examples/example-gateway/build/gen-code/clients/corge/corge"
)
// Client defines corge client interface.
type Client interface {
EchoString(
ctx context.Context,
reqHeaders map[string]string,
args *clientsCorgeCorge.Corge_EchoString_Args,
) (string, map[string]string, error)
}
// NewClient returns a new TChannel client for service corge.
func NewClient(deps *module.Dependencies) Client {
serviceName := deps.Default.Config.MustGetString("clients.corge.serviceName")
var routingKey string
if deps.Default.Config.ContainsKey("clients.corge.routingKey") {
routingKey = deps.Default.Config.MustGetString("clients.corge.routingKey")
}
var requestUUIDHeaderKey string
if deps.Default.Config.ContainsKey("tchannel.clients.requestUUIDHeaderKey") {
requestUUIDHeaderKey = deps.Default.Config.MustGetString("tchannel.clients.requestUUIDHeaderKey")
}
sc := deps.Default.Channel.GetSubChannel(serviceName, tchannel.Isolated)
ip := deps.Default.Config.MustGetString("sidecarRouter.default.tchannel.ip")
port := deps.Default.Config.MustGetInt("sidecarRouter.default.tchannel.port")
sc.Peers().Add(ip + ":" + strconv.Itoa(int(port)))
var scAltName string
if deps.Default.Config.ContainsKey("clients.corge.staging.serviceName") {
scAltName = deps.Default.Config.MustGetString("clients.corge.staging.serviceName")
ipAlt := deps.Default.Config.MustGetString("clients.corge.staging.ip")
portAlt := deps.Default.Config.MustGetInt("clients.corge.staging.port")
scAlt := deps.Default.Channel.GetSubChannel(scAltName, tchannel.Isolated)
scAlt.Peers().Add(ipAlt + ":" + strconv.Itoa(int(portAlt)))
} else if deps.Default.Config.ContainsKey("clients.staging.all.serviceName") {
scAltName = deps.Default.Config.MustGetString("clients.staging.all.serviceName")
ipAlt := deps.Default.Config.MustGetString("clients.staging.all.ip")
portAlt := deps.Default.Config.MustGetInt("clients.staging.all.port")
scAlt := deps.Default.Channel.GetSubChannel(scAltName, tchannel.Isolated)
scAlt.Peers().Add(ipAlt + ":" + strconv.Itoa(int(portAlt)))
}
timeoutVal := int(deps.Default.Config.MustGetInt("clients.corge.timeout"))
timeout := time.Millisecond * time.Duration(
timeoutVal,
)
timeoutPerAttempt := time.Millisecond * time.Duration(
deps.Default.Config.MustGetInt("clients.corge.timeoutPerAttempt"),
)
methodNames := map[string]string{
"Corge::echoString": "EchoString",
}
circuitBreakerDisabled := configureCicruitBreaker(deps, timeoutVal)
client := zanzibar.NewTChannelClientContext(
deps.Default.Channel,
deps.Default.Logger,
deps.Default.ContextMetrics,
deps.Default.ContextExtractor,
&zanzibar.TChannelClientOption{
ServiceName: serviceName,
ClientID: "corge",
MethodNames: methodNames,
Timeout: timeout,
TimeoutPerAttempt: timeoutPerAttempt,
RoutingKey: &routingKey,
AltSubchannelName: scAltName,
RequestUUIDHeaderKey: requestUUIDHeaderKey,
},
)
return &corgeClient{
client: client,
circuitBreakerDisabled: circuitBreakerDisabled,
}
}
func configureCicruitBreaker(deps *module.Dependencies, timeoutVal int) bool {
// circuitBreakerDisabled sets whether circuit-breaker should be disabled
circuitBreakerDisabled := false
if deps.Default.Config.ContainsKey("clients.corge.circuitBreakerDisabled") {
circuitBreakerDisabled = deps.Default.Config.MustGetBoolean("clients.corge.circuitBreakerDisabled")
}
// sleepWindowInMilliseconds sets the amount of time, after tripping the circuit,
// to reject requests before allowing attempts again to determine if the circuit should again be closed
sleepWindowInMilliseconds := 5000
if deps.Default.Config.ContainsKey("clients.corge.sleepWindowInMilliseconds") {
sleepWindowInMilliseconds = int(deps.Default.Config.MustGetInt("clients.corge.sleepWindowInMilliseconds"))
}
// maxConcurrentRequests sets how many requests can be run at the same time, beyond which requests are rejected
maxConcurrentRequests := 20
if deps.Default.Config.ContainsKey("clients.corge.maxConcurrentRequests") {
maxConcurrentRequests = int(deps.Default.Config.MustGetInt("clients.corge.maxConcurrentRequests"))
}
// errorPercentThreshold sets the error percentage at or above which the circuit should trip open
errorPercentThreshold := 20
if deps.Default.Config.ContainsKey("clients.corge.errorPercentThreshold") {
errorPercentThreshold = int(deps.Default.Config.MustGetInt("clients.corge.errorPercentThreshold"))
}
// requestVolumeThreshold sets a minimum number of requests that will trip the circuit in a rolling window of 10s
// For example, if the value is 20, then if only 19 requests are received in the rolling window of 10 seconds
// the circuit will not trip open even if all 19 failed.
requestVolumeThreshold := 20
if deps.Default.Config.ContainsKey("clients.corge.requestVolumeThreshold") {
requestVolumeThreshold = int(deps.Default.Config.MustGetInt("clients.corge.requestVolumeThreshold"))
}
if !circuitBreakerDisabled {
hystrix.ConfigureCommand("corge", hystrix.CommandConfig{
MaxConcurrentRequests: maxConcurrentRequests,
ErrorPercentThreshold: errorPercentThreshold,
SleepWindow: sleepWindowInMilliseconds,
RequestVolumeThreshold: requestVolumeThreshold,
Timeout: timeoutVal,
})
}
return circuitBreakerDisabled
}
// corgeClient is the TChannel client for downstream service.
type corgeClient struct {
client *zanzibar.TChannelClient
circuitBreakerDisabled bool
}
// EchoString is a client RPC call for method "Corge::echoString"
func (c *corgeClient) EchoString(
ctx context.Context,
reqHeaders map[string]string,
args *clientsCorgeCorge.Corge_EchoString_Args,
) (string, map[string]string, error) {
var result clientsCorgeCorge.Corge_EchoString_Result
var resp string
logger := c.client.Loggers["Corge::echoString"]
caller := c.client.Call
if strings.EqualFold(reqHeaders["X-Zanzibar-Use-Staging"], "true") {
caller = c.client.CallThruAltChannel
}
var success bool
var respHeaders map[string]string
var err error
if c.circuitBreakerDisabled {
success, respHeaders, err = caller(
ctx, "Corge", "echoString", reqHeaders, args, &result,
)
} else {
err = hystrix.DoC(ctx, "corge", func(ctx context.Context) error {
success, respHeaders, err = caller(
ctx, "Corge", "echoString", reqHeaders, args, &result,
)
return err
}, nil)
}
if err == nil && !success {
switch {
default:
err = errors.New("corgeClient received no result or unknown exception for EchoString")
}
}
if err != nil {
logger.Warn("Client failure: TChannel client call returned error", zap.Error(err))
return resp, nil, err
}
resp, err = clientsCorgeCorge.Corge_EchoString_Helper.UnwrapResponse(&result)
if err != nil {
logger.Warn("Client failure: unable to unwrap client response", zap.Error(err))
}
return resp, respHeaders, err
}