-
Notifications
You must be signed in to change notification settings - Fork 39
/
entry_point.go
326 lines (281 loc) · 11.6 KB
/
entry_point.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
326
package awsverifier
import (
"encoding/base64"
"fmt"
"os"
"strconv"
awsTools "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2Types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
handledErrors "github.com/openshift/osd-network-verifier/pkg/errors"
"github.com/openshift/osd-network-verifier/pkg/helpers"
"github.com/openshift/osd-network-verifier/pkg/output"
"github.com/openshift/osd-network-verifier/pkg/verifier"
)
const (
// Base path of the config file
CONFIG_PATH_FSTRING = "/app/build/config/%s.yaml"
DEBUG_KEY_NAME = "onv-debug-key"
DEFAULT_INSTANCE_TYPE = "t3.micro"
)
// ValidateEgress performs validation process for egress
// Basic workflow is:
// - prepare for ec2 instance creation
// - create instance and wait till it gets ready, wait for userdata script execution
// - find unreachable endpoints & parse output, then terminate instance
// - return `a.output` which stores the execution results
func (a *AwsVerifier) ValidateEgress(vei verifier.ValidateEgressInput) *output.Output {
a.writeDebugLogs(vei.Ctx, fmt.Sprintf("Using configured timeout of %s for each egress request", vei.Timeout.String()))
// Set default instance type if none is found
if vei.InstanceType == "" {
vei.InstanceType = DEFAULT_INSTANCE_TYPE
}
// Validates the provided instance type will work with the verifier
// NOTE a "nitro" EC2 instance type is required to be used
if err := a.validateInstanceType(vei.Ctx, vei.InstanceType); err != nil {
a.writeDebugLogs(vei.Ctx, fmt.Sprintf("Cannot use specified instance type: %s. Falling back to instance type %s", err, DEFAULT_INSTANCE_TYPE))
vei.InstanceType = DEFAULT_INSTANCE_TYPE
}
// Select config file based on platform type
platformTypeStr, err := helpers.GetPlatformType(vei.PlatformType)
if err != nil {
return a.Output.AddError(err)
}
configPath := fmt.Sprintf(CONFIG_PATH_FSTRING, platformTypeStr)
if platformTypeStr == "" {
// Default to AWS
configPath = fmt.Sprintf(CONFIG_PATH_FSTRING, helpers.PlatformAWS)
}
a.Logger.Debug(vei.Ctx, fmt.Sprintf("using config file: %s", configPath))
var debugPubKey []byte
// Check if Import-keypair flag has been passed
if vei.ImportKeyPair != "" {
//Read the pubkey file content into a variable
PubKey, err := os.ReadFile(vei.ImportKeyPair)
debugPubKey = PubKey
if err != nil {
return a.Output.AddError(err)
}
//Import Keypair into aws keypairs to be attached later to the created debug instance
_, err = a.AwsClient.ImportKeyPair(vei.Ctx, &ec2.ImportKeyPairInput{
KeyName: awsTools.String(DEBUG_KEY_NAME),
PublicKeyMaterial: debugPubKey,
})
if err != nil {
return a.Output.AddError(err)
}
//If we have imported a pubkey for debug we would like debug intance to stay up.
//Thus we set SkipInstanceTermination = true
vei.SkipInstanceTermination = true
}
// Terminate a debug instance leftover from a previous run
if vei.TerminateDebugInstance != "" {
//Terminate the debug instance
if err := a.AwsClient.TerminateEC2Instance(vei.Ctx, vei.TerminateDebugInstance); err != nil {
a.Output.AddError(err)
}
//Check if a keypair was uploaded
searchKeys := []string{DEBUG_KEY_NAME}
_, err := a.AwsClient.DescribeKeyPairs(vei.Ctx, &ec2.DescribeKeyPairsInput{
KeyNames: searchKeys,
})
if err != nil {
//if no key was found continue without executing deletion code
fmt.Printf("Debug KeyPair %v not found \n", DEBUG_KEY_NAME)
} else {
//if there was a key found, then delete it.
_, err = a.AwsClient.DeleteKeyPair(vei.Ctx, &ec2.DeleteKeyPairInput{
KeyName: awsTools.String(DEBUG_KEY_NAME),
})
//if there was any issues deleting the keypair.
if err != nil {
a.Output.AddError(err)
}
}
return &a.Output
}
// Generate the userData file
// As expand replaces all ${var} (using empty string for unknown ones), adding the env variables used in userdata.yaml
userDataVariables := map[string]string{
"AWS_REGION": a.AwsClient.Region,
"USERDATA_BEGIN": "USERDATA BEGIN",
"USERDATA_END": userdataEndVerifier,
"VALIDATOR_START_VERIFIER": "VALIDATOR START",
"VALIDATOR_END_VERIFIER": "VALIDATOR END",
"VALIDATOR_IMAGE": networkValidatorImage,
"VALIDATOR_REPO": networkValidatorRepo,
"TIMEOUT": vei.Timeout.String(),
"HTTP_PROXY": vei.Proxy.HttpProxy,
"HTTPS_PROXY": vei.Proxy.HttpsProxy,
"CACERT": base64.StdEncoding.EncodeToString([]byte(vei.Proxy.Cacert)),
"NOTLS": strconv.FormatBool(vei.Proxy.NoTls),
"IMAGE": "$IMAGE",
"CONFIG_PATH": configPath,
"DELAY": "5",
}
if vei.SkipInstanceTermination {
userDataVariables["DELAY"] = "60"
}
userData, err := generateUserData(userDataVariables)
if err != nil {
return a.Output.AddError(err)
}
a.writeDebugLogs(vei.Ctx, fmt.Sprintf("base64-encoded generated userdata script:\n---\n%s\n---", userData))
err = setCloudImage(&vei.CloudImageID, a.AwsClient.Region)
if err != nil {
return a.Output.AddError(err) // fatal
}
vpcId, err := a.GetVpcIdFromSubnetId(vei.Ctx, vei.SubnetID)
if err != nil {
return a.Output.AddError(err)
}
// If security group not given, create a temporary one
if vei.AWS.SecurityGroupId == "" && len(vei.AWS.SecurityGroupIDs) == 0 || vei.ForceTempSecurityGroup {
createSecurityGroupOutput, err := a.CreateSecurityGroup(vei.Ctx, vei.Tags, "osd-network-verifier", vpcId)
if err != nil {
return a.Output.AddError(err)
}
vei.AWS.TempSecurityGroup = *createSecurityGroupOutput.GroupId
// Now that security group has been created, ensure we clean it up
defer CleanupSecurityGroup(vei, a)
// If proxy information given, add rules for it to the security group
if vei.Proxy.HttpProxy != "" || vei.Proxy.HttpsProxy != "" {
// Build a slice of proxy URLs (up to 2)
proxyUrls := make([]string, 0, 2)
if vei.Proxy.HttpProxy != "" {
proxyUrls = append(proxyUrls, vei.Proxy.HttpProxy)
}
if vei.Proxy.HttpsProxy != "" {
proxyUrls = append(proxyUrls, vei.Proxy.HttpsProxy)
}
// Add the new rules to the temp security group
_, err := a.AllowSecurityGroupProxyEgress(vei.Ctx, vei.AWS.TempSecurityGroup, proxyUrls)
if err != nil {
return a.Output.AddError(err)
}
}
}
// Create EC2 instance
instanceID, err := a.createEC2Instance(createEC2InstanceInput{
amiID: vei.CloudImageID,
SubnetID: vei.SubnetID,
userdata: userData,
KmsKeyID: vei.AWS.KmsKeyID,
instanceCount: instanceCount,
ctx: vei.Ctx,
instanceType: vei.InstanceType,
tags: vei.Tags,
securityGroupId: vei.AWS.SecurityGroupId,
securityGroupIDs: vei.AWS.SecurityGroupIDs,
tempSecurityGroupID: vei.AWS.TempSecurityGroup,
keyPair: vei.ImportKeyPair,
})
if err != nil {
return a.Output.AddError(err)
}
// Run the result fetcher, which will store egress failures in a.Output.failures
if err := a.findUnreachableEndpoints(vei.Ctx, instanceID); err != nil {
a.Output.AddError(err)
// Don't return yet; still need to terminate instance
}
// Terminate the EC2 instance (unless user requests otherwise)
if !vei.SkipInstanceTermination {
//Replaced the SGs attached to the network-verifier-instance by the default SG in order to allow
//deletion of temporary SGs created
//Getting a list of the SGs for the current VPC of our instance
var defaultSecurityGroupID = ""
describeSGOutput, err := a.AwsClient.DescribeSecurityGroups(vei.Ctx, &ec2.DescribeSecurityGroupsInput{
Filters: []ec2Types.Filter{
{
Name: awsTools.String("vpc-id"),
Values: []string{vpcId},
},
{
Name: awsTools.String("group-name"),
Values: []string{"default"},
},
},
})
if err != nil {
a.Output.AddError(err)
a.Logger.Info(vei.Ctx, "Unable to describe security groups. Falling back to slower cloud resource cleanup method.")
}
if describeSGOutput != nil {
//Fetch default Security Group ID.
for _, SG := range describeSGOutput.SecurityGroups {
if *SG.GroupName == "default" {
defaultSecurityGroupID = *SG.GroupId
}
}
//Replacing the SGs attach to instance by the default one. This is to clean the SGs created in case the instance
//termination times out
_, err = a.AwsClient.ModifyInstanceAttribute(vei.Ctx, &ec2.ModifyInstanceAttributeInput{
InstanceId: &instanceID,
Groups: []string{defaultSecurityGroupID},
})
if err != nil {
a.Logger.Info(vei.Ctx, "Unable to detach instance from security group. Falling back to slower cloud resource cleanup method.")
a.writeDebugLogs(vei.Ctx, fmt.Sprintf("Error encountered while trying to detach instance: %s.", err))
}
}
a.Logger.Info(vei.Ctx, "Deleting instance with ID: %s", instanceID)
if err := a.AwsClient.TerminateEC2Instance(vei.Ctx, instanceID); err != nil {
a.Output.AddError(err)
}
}
return &a.Output
}
// VerifyDns performs verification process for VPC's DNS
// Basic workflow is:
// - ask AWS API for VPC attributes
// - ensure they're set correctly
func (a *AwsVerifier) VerifyDns(vdi verifier.VerifyDnsInput) *output.Output {
a.Logger.Info(vdi.Ctx, "Verifying DNS config for VPC %s", vdi.VpcID)
// Request boolean values from AWS API
dnsSprtResult, err := a.AwsClient.DescribeVpcAttribute(vdi.Ctx, &ec2.DescribeVpcAttributeInput{
Attribute: ec2Types.VpcAttributeNameEnableDnsSupport,
VpcId: awsTools.String(vdi.VpcID),
})
if err != nil {
a.Output.AddError(handledErrors.NewGenericError(err))
a.Output.AddException(handledErrors.NewGenericError(
fmt.Errorf("failed to validate the %s attribute on VPC: %s is true", ec2Types.VpcAttributeNameEnableDnsSupport, vdi.VpcID)),
)
return &a.Output
}
dnsHostResult, err := a.AwsClient.DescribeVpcAttribute(vdi.Ctx, &ec2.DescribeVpcAttributeInput{
Attribute: "enableDnsHostnames",
VpcId: awsTools.String(vdi.VpcID),
})
if err != nil {
a.Output.AddError(handledErrors.NewGenericError(err))
a.Output.AddException(handledErrors.NewGenericError(
fmt.Errorf("failed to validate the %s attribute on VPC: %s is true", ec2Types.VpcAttributeNameEnableDnsHostnames, vdi.VpcID),
))
return &a.Output
}
// Verify results
a.Logger.Info(vdi.Ctx, "DNS Support for VPC %s: %t", vdi.VpcID, *dnsSprtResult.EnableDnsSupport.Value)
a.Logger.Info(vdi.Ctx, "DNS Hostnames for VPC %s: %t", vdi.VpcID, *dnsHostResult.EnableDnsHostnames.Value)
if !(*dnsSprtResult.EnableDnsSupport.Value) {
a.Output.AddException(handledErrors.NewGenericError(
fmt.Errorf("the %s attribute on VPC: %s is %t, must be true", ec2Types.VpcAttributeNameEnableDnsSupport, vdi.VpcID, *dnsSprtResult.EnableDnsSupport.Value),
))
}
if !(*dnsHostResult.EnableDnsHostnames.Value) {
a.Output.AddException(handledErrors.NewGenericError(
fmt.Errorf("the %s attribute on VPC: %s is %t, must be true", ec2Types.VpcAttributeNameEnableDnsHostnames, vdi.VpcID, *dnsHostResult.EnableDnsHostnames.Value),
))
}
return &a.Output
}
// Cleans up the security groups created by network-verifier
func CleanupSecurityGroup(vei verifier.ValidateEgressInput, a *AwsVerifier) *output.Output {
a.Logger.Info(vei.Ctx, "Deleting security group with ID: %s", vei.AWS.TempSecurityGroup)
_, err := a.AwsClient.DeleteSecurityGroup(vei.Ctx, &ec2.DeleteSecurityGroupInput{GroupId: awsTools.String(vei.AWS.TempSecurityGroup)})
if err != nil {
a.Output.AddError(handledErrors.NewGenericError(err))
a.Output.AddException(handledErrors.NewGenericError(fmt.Errorf("unable to cleanup security group %s, please manually clean up", vei.AWS.TempSecurityGroup)))
}
return &a.Output
}