This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
/
reconcile_trunk_enis.go
370 lines (318 loc) · 12.3 KB
/
reconcile_trunk_enis.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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package service
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/Netflix/titus-executor/logger"
"github.com/Netflix/titus-executor/vpc/service/data"
"github.com/Netflix/titus-executor/vpc/service/ec2wrapper"
"github.com/Netflix/titus-executor/vpc/service/metrics"
"github.com/Netflix/titus-executor/vpc/tracehelpers"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/lib/pq"
"github.com/pkg/errors"
"go.opencensus.io/stats"
"go.opencensus.io/trace"
"k8s.io/apimachinery/pkg/util/sets"
)
const (
timeBetweenTrunkENIReconcilation = time.Minute
)
func (vpcService *vpcService) reconcileTrunkENIsForRegionAccountLoop(ctx context.Context, protoItem data.KeyedItem) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
item := protoItem.(*regionAccount)
ctx = logger.WithFields(ctx, map[string]interface{}{
"region": item.region,
"accountID": item.accountID,
})
for {
start := time.Now()
err := vpcService.reconcileTrunkENIsForRegionAccount(ctx, item)
if err != nil {
logger.G(ctx).WithError(err).Error("Failed to reconcile trunk ENIs")
stats.Record(ctx, metrics.ErrorReconcileTrunkENIsCount.M(1))
} else {
stats.Record(ctx, metrics.ReconcileTrunkENIsLatency.M(time.Since(start).Milliseconds()))
}
err = waitFor(ctx, timeBetweenTrunkENIReconcilation)
if err != nil {
return err
}
}
}
func (vpcService *vpcService) reconcileTrunkENIsForRegionAccount(ctx context.Context, account *regionAccount) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx, span := trace.StartSpan(ctx, "reconcileTrunkENIsForRegionAccount")
defer span.End()
span.AddAttributes(trace.StringAttribute("region", account.region), trace.StringAttribute("account", account.accountID))
session, err := vpcService.ec2.GetSessionFromAccountAndRegion(ctx, ec2wrapper.Key{
AccountID: account.accountID,
Region: account.region,
})
if err != nil {
logger.G(ctx).WithError(err).Error("Could not get session")
tracehelpers.SetStatus(err, span)
return err
}
// Reconciling AWS -> DB
// 1. Find all trunk ENIs in AWS
// 2. If a trunk ENI has delete on terminate set, unset it
// 3. If it is attached, insert it into the database (or set deleting to = f)
// 4. If it is not attached run the "safe" delete operation on it [if this fails, hopefully on the next reconcilation something good will happen?]
//
// Why do we do multi-phasic deletes, and not just delete from our db and then delete in AWS?
//
// Play out this example:
// 1. I create and attach the interface
// 2. Reconcilation runs and gets an eventual consistent reply from AWS saying that the interface is not attached
// 3. We delete it from the db entirely (no tombstone)
// 4. If we used this branch ENI for any associations, we just blew away those associations
//
// Another aspect is in order to see if a network interface really does not exist, we have to do some intrusive
// (expensive) probing. I'd rather not do that
//
//
// Reconcilation of DB -> AWS [How do we deal with ENIs which got deleted outside of titus]
// 1. If the ENI was not in the describe call above
// 2. If there is a tombstone, then delete the row from the database table, and all the associations associated with it
// 3. If there is not a tombstone, we try and ModifyNetworkInterfaceAttribute to see if it exists. If it exists, we leave it alone,
// and hope it comes back later, if not, blow it away from the db, otherwise hardDelete
//
// Also, unmark all tombstones > 24 hours old
//
logger.G(ctx).Info("Beginning reconcilation of trunk ENIs")
describeNetworkInterfacesInput := ec2.DescribeNetworkInterfacesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("description"),
Values: aws.StringSlice([]string{vpcService.config.TrunkNetworkInterfaceDescription}),
},
{
Name: aws.String("owner-id"),
Values: aws.StringSlice([]string{account.accountID}),
},
},
MaxResults: aws.Int64(1000),
}
networkInterfaces := []*ec2.NetworkInterface{}
for {
describeNetworkInterfacesOutput, err := session.DescribeNetworkInterfaces(ctx, describeNetworkInterfacesInput)
if err != nil {
err = errors.Wrap(err, "Cannot describe network interfaces")
tracehelpers.SetStatus(err, span)
return err
}
networkInterfaces = append(networkInterfaces, describeNetworkInterfacesOutput.NetworkInterfaces...)
if describeNetworkInterfacesOutput.NextToken == nil {
break
}
describeNetworkInterfacesInput.NextToken = describeNetworkInterfacesOutput.NextToken
}
enis := sets.NewString()
for idx := range networkInterfaces {
ni := networkInterfaces[idx]
networkInterfaceID := aws.StringValue(ni.NetworkInterfaceId)
enis.Insert(networkInterfaceID)
ctx2 := logger.WithField(ctx, "eni", networkInterfaceID)
if ni.Attachment != nil {
err = vpcService.reconcileAttachedTrunkENI(ctx2, session, ni)
if err != nil {
logger.G(ctx2).WithError(err).Error("Cannot reconcile attached trunk ENI")
}
} else {
err = vpcService.reconcileUnattachedTrunkENI(ctx2, session, ni)
if err != nil {
logger.G(ctx2).WithError(err).Error("Cannot reconcile unattached trunk ENI")
}
}
}
err = vpcService.reconcileTrunkENIsForRegionAccountInDatabase(ctx, account, session, enis)
tracehelpers.SetStatus(err, span)
return err
}
func (vpcService *vpcService) reconcileTrunkENIsForRegionAccountInDatabase(ctx context.Context, account *regionAccount, session *ec2wrapper.EC2Session, enis sets.String) error {
if enis.Len() == 0 {
return nil
}
ctx, span := trace.StartSpan(ctx, "reconcileTrunkENIsForRegionAccountInDatabase")
defer span.End()
databaseOrphanedTrunkENIs, err := vpcService.getDatabaseOrphanedTrunkENIs(ctx, account, enis)
if err != nil {
logger.G(ctx).WithError(err).Error("Cannot find orphaned ENIs")
}
logger.G(ctx).WithField("enis", databaseOrphanedTrunkENIs).Debug("Found orphaned ENIs")
for _, eni := range databaseOrphanedTrunkENIs.UnsortedList() {
ctx2 := logger.WithField(ctx, "eni", eni)
err = vpcService.reconcileOrphanedTrunkENI(ctx2, session, eni)
if err != nil {
logger.G(ctx2).WithError(err).Error("Cannot reconcile orphaned ENI")
}
}
return nil
}
func (vpcService *vpcService) reconcileOrphanedTrunkENI(ctx context.Context, session *ec2wrapper.EC2Session, eni string) error {
ctx, span := trace.StartSpan(ctx, "reconcileOrphanedTrunkENI")
defer span.End()
span.AddAttributes(trace.StringAttribute("eni", eni))
exists, tombstone, err := vpcService.getTrunkNetworkInterfaceTombstone(ctx, eni)
if err != nil {
err = errors.Wrap(err, "Could not get tombstone for network interface")
tracehelpers.SetStatus(err, span)
return err
}
if !exists {
err = fmt.Errorf("Oprhaned ENI %s could not be found in the database", eni)
tracehelpers.SetStatus(err, span)
return err
}
if tombstone != nil {
logger.G(ctx).Info("Hard deleting ENI, as tombstone is set, meaning that (we may) have tried deleting it in the past")
err = vpcService.hardDeleteTrunkInterface(ctx, eni)
if err != nil {
err = errors.Wrap(err, "Could not hard delete ENI")
tracehelpers.SetStatus(err, span)
}
return err
}
eniExists, err := doesENIExist(ctx, session, eni, vpcService.config.TrunkNetworkInterfaceDescription)
if err != nil {
err = errors.Wrap(err, "Could not find out if branch ENI exists")
return ec2wrapper.HandleEC2Error(err, span)
}
if eniExists {
logger.G(ctx).Warning("ENI actually exists in AWS according to modify call")
return nil
}
logger.G(ctx).Info("Hard deleting ENI, as could not find it in AWS")
err = vpcService.hardDeleteTrunkInterface(ctx, eni)
if err != nil {
err = errors.Wrap(err, "Could not hard delete ENI")
return ec2wrapper.HandleEC2Error(err, span)
}
return nil
}
func (vpcService *vpcService) getDatabaseOrphanedTrunkENIs(ctx context.Context, account *regionAccount, enis sets.String) (sets.String, error) {
ctx, span := trace.StartSpan(ctx, "getDatabaseOrphanedTrunkENIs")
defer span.End()
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
tx, err := vpcService.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
err = errors.Wrap(err, "Could not start database transaction")
tracehelpers.SetStatus(err, span)
return nil, err
}
defer func() {
_ = tx.Rollback()
}()
rows, err := tx.QueryContext(ctx,
`SELECT trunk_eni FROM trunk_enis WHERE trunk_eni != all($1) AND region = $2 AND account_id = $3`,
pq.Array(enis.UnsortedList()), account.region, account.accountID)
if err != nil {
err = errors.Wrap(err, "Could not query for orphaned trunk ENIs")
tracehelpers.SetStatus(err, span)
return nil, err
}
orphanedENIs := sets.NewString()
for rows.Next() {
var trunkENI string
err = rows.Scan(&trunkENI)
if err != nil {
err = errors.Wrap(err, "Cannot scan trunk ENI")
tracehelpers.SetStatus(err, span)
return nil, err
}
orphanedENIs.Insert(trunkENI)
}
err = tx.Commit()
if err != nil {
err = errors.Wrap(err, "Could commit transaction")
tracehelpers.SetStatus(err, span)
return nil, err
}
return orphanedENIs, nil
}
func (vpcService *vpcService) reconcileAttachedTrunkENI(ctx context.Context, session *ec2wrapper.EC2Session, networkInterface *ec2.NetworkInterface) error {
ctx, span := trace.StartSpan(ctx, "reconcileAttachedTrunkENI")
defer span.End()
span.AddAttributes(trace.StringAttribute("eni", aws.StringValue(networkInterface.NetworkInterfaceId)))
if aws.BoolValue(networkInterface.Attachment.DeleteOnTermination) {
logger.G(ctx).WithField("attachment", networkInterface.Attachment).Info("Modifying attachment not to delete on termination")
_, err := session.ModifyNetworkInterfaceAttribute(ctx, ec2.ModifyNetworkInterfaceAttributeInput{
Attachment: &ec2.NetworkInterfaceAttachmentChanges{
AttachmentId: networkInterface.Attachment.AttachmentId,
DeleteOnTermination: aws.Bool(false),
},
NetworkInterfaceId: networkInterface.NetworkInterfaceId,
})
if err != nil {
err = errors.Wrap(err, "Cannot turn delete on terminate off")
tracehelpers.SetStatus(err, span)
return err
}
}
// Make sure the trunk ENI is in the database.
tx, err := vpcService.db.BeginTx(ctx, &sql.TxOptions{})
if err != nil {
err = errors.Wrap(err, "Could not start database transaction")
tracehelpers.SetStatus(err, span)
return err
}
defer func() {
_ = tx.Rollback()
}()
// Generation is only set at ENI creation time, not updated
err = insertTrunkENIIntoDB(ctx, tx, networkInterface, 0)
if err != nil {
err = errors.Wrap(err, "Cannot update trunk enis")
tracehelpers.SetStatus(err, span)
return err
}
err = tx.Commit()
if err != nil {
err = errors.Wrap(err, "Cannot commit transaction")
tracehelpers.SetStatus(err, span)
return err
}
return nil
}
func (vpcService *vpcService) reconcileUnattachedTrunkENI(ctx context.Context, session *ec2wrapper.EC2Session, networkInterface *ec2.NetworkInterface) error {
ctx, span := trace.StartSpan(ctx, "reconcileUnattachedTrunkENI")
defer span.End()
span.AddAttributes(trace.StringAttribute("eni", aws.StringValue(networkInterface.NetworkInterfaceId)))
exists, tombstone, err := vpcService.getTrunkNetworkInterfaceTombstone(ctx, aws.StringValue(networkInterface.NetworkInterfaceId))
if err != nil {
err = errors.Wrap(err, "Cannot get network interface tombstone")
tracehelpers.SetStatus(err, span)
return err
}
if !exists {
logger.G(ctx).Info("Found unattached branch ENI not in database, attempting to delete")
_, err = session.DeleteNetworkInterface(ctx, ec2.DeleteNetworkInterfaceInput{NetworkInterfaceId: networkInterface.NetworkInterfaceId})
if err != nil {
err = errors.Wrap(err, "Could not delete dangling trunk interface")
}
tracehelpers.SetStatus(err, span)
return err
}
logger.G(ctx).Info("Found unattached branch ENI, attempting to delete gracefully")
if tombstone != nil {
logger.G(ctx).WithField("tombstone", tombstone).Info("Found tombstoned ENI on reconcilation, likely leak")
}
err = vpcService.deleteTrunkInterface(ctx, session, aws.StringValue(networkInterface.NetworkInterfaceId))
if err != nil {
logger.G(ctx).WithError(err).Error("Cannot delete unattached network interface")
}
return nil
}
func (vpcService *vpcService) reconcileTrunkENIsLongLivedTask() longLivedTask {
return longLivedTask{
taskName: "reconcile_trunk_enis",
itemLister: vpcService.getTrunkENIRegionAccounts,
workFunc: vpcService.reconcileTrunkENIsForRegionAccountLoop,
}
}