-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfn.go
264 lines (225 loc) · 8.23 KB
/
fn.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
package main
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi"
"github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi/types"
"github.com/crossplane/crossplane-runtime/pkg/errors"
runtimeresource "github.com/crossplane/crossplane-runtime/pkg/resource"
"github.com/crossplane/function-sdk-go/logging"
fnv1 "github.com/crossplane/function-sdk-go/proto/v1"
"github.com/crossplane/function-sdk-go/request"
"github.com/crossplane/function-sdk-go/resource"
"github.com/crossplane/function-sdk-go/response"
"github.com/gympass/function-aws-importer/input/v1beta1"
"github.com/gympass/function-aws-importer/internal"
)
const (
externalNameTag = "crossplane-external-name"
)
// Function returns whatever response you ask it to.
type Function struct {
fnv1.UnimplementedFunctionRunnerServiceServer
log logging.Logger
client resourcegroupstaggingapi.GetResourcesAPIClient
}
// RunFunction runs the Function.
func (f *Function) RunFunction(ctx context.Context, req *fnv1.RunFunctionRequest) (*fnv1.RunFunctionResponse, error) {
f.log.Info("Running function",
"tag", req.GetMeta().GetTag(),
)
rsp := response.To(req, response.DefaultTTL)
in := &v1beta1.Input{}
if err := request.GetInput(req, in); err != nil {
response.Fatal(rsp, errors.Wrapf(err, "cannot get Function input from %T", req))
return rsp, nil
}
f.log.Debug("Fetched input.",
"input", in,
)
if err := in.Validate(); err != nil {
response.Fatal(rsp, errors.Wrap(err, "invalid Function input"))
return rsp, nil
}
resources, err := internal.NewResources(req)
if err != nil {
f.log.Info("Failed to extract observed and desired composed resources.",
"error", err,
)
response.Fatal(rsp, fmt.Errorf("cannot extract observed and desired composed resources: %v", err))
return rsp, nil
}
if resources.LenDesired() == 0 {
f.log.Info("Empty desired composed resources")
response.Warning(rsp, errors.New("found no desired composed resources. Are you running the function before other steps that define the resources? It should always run after them."))
return rsp, nil
}
err = resources.EnsureExternalNameTags(externalNameTag)
if err != nil {
f.log.Info("Failed to ensure external name tags.",
"error", err,
)
response.Fatal(rsp, fmt.Errorf("cannot ensure external name tags: %v", err))
return rsp, nil
}
if resources.LenObserved() > 0 && resources.AllHaveExternalNamesSet() {
err := response.SetDesiredComposedResources(rsp, resources.DesiredComposedResources())
if err != nil {
f.log.Info("Failed to set desired composed resources.",
"error", err,
"desired", resources.DesiredComposedResources(),
)
response.Fatal(rsp, errors.Wrapf(err, "cannot set desired composed resources in %T", rsp))
return rsp, nil
}
externalNames := resources.ObservedExternalNames()
f.log.Debug("External name already set for all resources",
"externalNames", externalNames,
)
response.Normalf(rsp, "external name annotation already set for all resources: %v", externalNames)
return rsp, nil
}
err = resources.ForEachDesiredComposed(func(desiredComposed internal.Resource) error {
externalName, err := f.fetchExternalNameFromAWS(ctx, req, in, desiredComposed)
if err != nil {
return fmt.Errorf("fetching external name from AWS: %v", err)
}
return resources.SetDesiredExternalName(desiredComposed.CompositionName(), externalName)
})
if err != nil {
f.log.Info("Failed to reconcile desired managed resource.",
"error", err,
)
response.Fatal(rsp, fmt.Errorf("cannot reconcile desired managed resource: %v", err))
return rsp, nil
}
if !resources.FoundExistingResources() {
desiredResourcesCompName := resources.DesiredResourcesCompositionNames()
f.log.Info("External resources not found", "resources", desiredResourcesCompName)
response.Normalf(rsp, "external resources not found: %v", desiredResourcesCompName)
}
desiredMRs := resources.DesiredComposedResources()
if err := response.SetDesiredComposedResources(rsp, desiredMRs); err != nil {
f.log.Info("Failed to set desired composed resources.",
"error", err,
"desired", desiredMRs,
)
response.Fatal(rsp, errors.Wrapf(err, "cannot set desired composed resources in %T", rsp))
return rsp, nil
}
desiredExternalNames := resources.DesiredExternalNames()
response.Normalf(rsp, "added external name annotations: %v", desiredExternalNames)
f.log.Info("Added external name annotation.",
"externalNames", desiredExternalNames,
)
return rsp, nil
}
func (f *Function) fetchExternalNameFromAWS(ctx context.Context, req *fnv1.RunFunctionRequest, in *v1beta1.Input, desiredComposed internal.Resource) (string, error) {
tagFilters, err := f.extractTagFilters(desiredComposed, req, in)
if err != nil {
return "", fmt.Errorf("extracting tag filters: %v", err)
}
tagMappings, err := f.getResourceTagMappings(ctx, tagFilters)
if err != nil {
return "", fmt.Errorf("getting resource tag mappings: %v", err)
}
if len(tagMappings) > 1 {
f.log.Info("Cannot decide which resource to import.",
"error", errors.New("found more than one resource matching tag filters"),
"tagFilters", tagFilters,
"matchingResources", extractARNs(tagMappings),
)
return "", fmt.Errorf("found more than one resource matching tag filters: %v", extractARNs(tagMappings))
}
if len(tagMappings) == 0 {
f.log.Debug("External resource not found",
"tagFilters", tagFilters,
)
return "", nil
}
tags := tagMappings[0].Tags
f.log.Debug("Found resource with matching tags",
"tags", tags,
"tagFilters", tagFilters,
)
return f.extractExternalName(tags)
}
func (f *Function) extractExternalName(tags []types.Tag) (string, error) {
var externalName string
for _, t := range tags {
// TODO(lcaparelli): make this a parameter for the function, allow users to fetch external-name value from any tag
if aws.ToString(t.Key) == externalNameTag {
externalName = aws.ToString(t.Value)
break
}
}
if len(externalName) == 0 {
f.log.Info("Cannot fetch external name from tags.",
"error", errors.New("tag does not exist or is empty"),
"existingTags", tags,
"externalNameTagKey", externalNameTag,
)
return "", fmt.Errorf("found resource matching tag filters, but %q tag is not present or is empty", externalNameTag)
}
return externalName, nil
}
func (f *Function) getResourceTagMappings(ctx context.Context, tagFilters []types.TagFilter) ([]types.ResourceTagMapping, error) {
paginator := resourcegroupstaggingapi.NewGetResourcesPaginator(f.client, &resourcegroupstaggingapi.GetResourcesInput{
TagFilters: tagFilters,
})
var tagMappings []types.ResourceTagMapping
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("getting resources tag mappings: %v", err)
}
for _, t := range page.ResourceTagMappingList {
tagMappings = append(tagMappings, t)
}
}
return tagMappings, nil
}
func (f *Function) extractTagFilters(desiredComposed internal.Resource, req *fnv1.RunFunctionRequest, in *v1beta1.Input) ([]types.TagFilter, error) {
xr, err := request.GetObservedCompositeResource(req)
if err != nil {
return nil, fmt.Errorf("extracting observed XR from req: %v", err)
}
tagFilters, err := resolveTagFilters(in, xr, desiredComposed)
if err != nil {
f.log.Info("Failed to resolve tag filters.",
"error", err,
"tagFilters", in.TagFilters,
"xr", xr,
"managedResource", desiredComposed,
)
return nil, err
}
return tagFilters, nil
}
func resolveTagFilters(in *v1beta1.Input, xr *resource.Composite, res internal.Resource) ([]types.TagFilter, error) {
additionalFilters, err := in.ResolveTagFilters(xr)
if err != nil {
return nil, fmt.Errorf("resolving input tag filters: %v", err)
}
return append(additionalFilters, nameAndKindFilters(res)...), nil
}
func nameAndKindFilters(res internal.Resource) []types.TagFilter {
return []types.TagFilter{
{
Key: aws.String(runtimeresource.ExternalResourceTagKeyName),
Values: []string{res.K8sName()},
},
{
Key: aws.String(runtimeresource.ExternalResourceTagKeyKind),
Values: []string{res.GroupKind()},
},
}
}
func extractARNs(tagMappings []types.ResourceTagMapping) []string {
var arns []string
for _, t := range tagMappings {
arns = append(arns, aws.ToString(t.ResourceARN))
}
return arns
}