This repository has been archived by the owner on Nov 30, 2023. It is now read-only.
/
subnet_collector.go
247 lines (197 loc) · 6.93 KB
/
subnet_collector.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
package ipam
import (
"context"
"fmt"
"net"
"reflect"
"sync"
"github.com/giantswarm/apiextensions/pkg/apis/provider/v1alpha1"
"github.com/giantswarm/ipam"
"github.com/giantswarm/k8sclient/v3/pkg/k8sclient"
"github.com/giantswarm/microerror"
"github.com/giantswarm/micrologger"
"golang.org/x/sync/errgroup"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
client2 "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/giantswarm/azure-operator/v4/client"
"github.com/giantswarm/azure-operator/v4/pkg/credential"
"github.com/giantswarm/azure-operator/v4/service/controller/key"
)
type SubnetCollectorConfig struct {
CredentialProvider credential.Provider
K8sClient k8sclient.Interface
InstallationName string
Logger micrologger.Logger
NetworkRange net.IPNet
}
type SubnetCollector struct {
credentialProvider credential.Provider
k8sclient k8sclient.Interface
installationName string
logger micrologger.Logger
networkRange net.IPNet
}
func NewSubnetCollector(config SubnetCollectorConfig) (*SubnetCollector, error) {
if config.CredentialProvider == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.CredentialProvider must not be empty", config)
}
if config.K8sClient == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.K8sClient must not be empty", config)
}
if config.InstallationName == "" {
return nil, microerror.Maskf(invalidConfigError, "%T.InstallationName must not be empty", config)
}
if config.Logger == nil {
return nil, microerror.Maskf(invalidConfigError, "%T.Logger must not be empty", config)
}
if reflect.DeepEqual(config.NetworkRange, net.IPNet{}) {
return nil, microerror.Maskf(invalidConfigError, "%T.NetworkRange must not be empty", config)
}
c := &SubnetCollector{
credentialProvider: config.CredentialProvider,
k8sclient: config.K8sClient,
installationName: config.InstallationName,
logger: config.Logger,
networkRange: config.NetworkRange,
}
return c, nil
}
func (c *SubnetCollector) Collect(ctx context.Context) ([]net.IPNet, error) {
var err error
var mutex sync.Mutex
var reservedSubnets []net.IPNet
g := &errgroup.Group{}
g.Go(func() error {
c.logger.LogCtx(ctx, "level", "debug", "message", "finding allocated subnets from AzureConfig CRs")
subnets, err := c.getSubnetsFromAzureConfigs(ctx)
if err != nil {
return microerror.Mask(err)
}
mutex.Lock()
reservedSubnets = append(reservedSubnets, subnets...)
mutex.Unlock()
c.logger.LogCtx(ctx, "level", "debug", "message", "found allocated subnets from AzureConfig CRs")
return nil
})
g.Go(func() error {
c.logger.LogCtx(ctx, "level", "debug", "message", "finding allocated subnets from all resource groups in the subscription")
subnets, err := c.getSubnetsFromAllSubscriptions(ctx)
if err != nil {
return microerror.Mask(err)
}
mutex.Lock()
reservedSubnets = append(reservedSubnets, subnets...)
mutex.Unlock()
c.logger.LogCtx(ctx, "level", "debug", "message", "found allocated subnets from all resource groups in the subscription")
return nil
})
err = g.Wait()
if err != nil {
return nil, microerror.Mask(err)
}
reservedSubnets = ipam.CanonicalizeSubnets(c.networkRange, reservedSubnets)
return reservedSubnets, nil
}
func (c *SubnetCollector) getSubnetsFromAzureConfigs(ctx context.Context) ([]net.IPNet, error) {
tenantClusterList, err := c.getAllTenantClusters(ctx)
if err != nil {
return nil, microerror.Mask(err)
}
var results []net.IPNet
for _, ac := range tenantClusterList.Items {
cidr := key.AzureConfigNetworkCIDR(ac)
if cidr == "" {
continue
}
_, n, err := net.ParseCIDR(cidr)
if err != nil {
return nil, microerror.Mask(err)
}
results = append(results, *n)
}
return results, nil
}
func (c *SubnetCollector) getSubnetsFromAllSubscriptions(ctx context.Context) ([]net.IPNet, error) {
tenantClusterList, err := c.getAllTenantClusters(ctx)
if err != nil {
return nil, microerror.Mask(err)
}
var doneSubscriptions []string
var ret []net.IPNet
for _, cluster := range tenantClusterList.Items {
organizationAzureClientCredentialsConfig, subscriptionID, partnerID, err := c.credentialProvider.GetOrganizationAzureCredentials(ctx, key.CredentialNamespace(cluster), key.CredentialName(cluster))
if err != nil {
return nil, microerror.Mask(err)
}
organizationAzureClientSet, err := client.NewAzureClientSet(organizationAzureClientCredentialsConfig, subscriptionID, partnerID)
if err != nil {
return nil, microerror.Mask(err)
}
// We want to check only once per subscription.
if inArray(doneSubscriptions, organizationAzureClientSet.SubscriptionID) {
continue
}
nets, err := c.getSubnetsFromSubscription(ctx, organizationAzureClientSet)
if err != nil {
// We can't use this Azure credentials. Might be wrong in the Secret file.
// We shouldn't block the network calculation for this reason.
c.logger.LogCtx(ctx, "level", "warning", "message", fmt.Sprintf("Error getting used subnets for subscription %s: %s", organizationAzureClientSet.SubscriptionID, err))
continue
}
doneSubscriptions = append(doneSubscriptions, organizationAzureClientSet.SubscriptionID)
ret = append(ret, nets...)
}
return ret, nil
}
func (c *SubnetCollector) getSubnetsFromSubscription(ctx context.Context, clientSet *client.AzureClientSet) ([]net.IPNet, error) {
groupsClient := clientSet.GroupsClient
vnetClient := clientSet.VirtualNetworkClient
// Look for all resource groups that have a tag named 'GiantSwarmInstallation' with installation name as value.
iterator, err := groupsClient.ListComplete(ctx, fmt.Sprintf("tagName eq 'GiantSwarmInstallation' and tagValue eq '%s'", c.installationName), nil)
if err != nil {
return nil, microerror.Mask(err)
}
var ret []net.IPNet
for iterator.NotDone() {
group := iterator.Value()
// Search a VNET with any of the expected names.
vnetCandidates := []string{
fmt.Sprintf("%s-VirtualNetwork", *group.Name),
c.installationName,
}
for _, vnetName := range vnetCandidates {
vnet, err := vnetClient.Get(ctx, *group.Name, vnetName, "")
if IsNotFound(err) {
// VNET with desired name not found, ignore this resource group.
} else if err != nil {
return nil, microerror.Mask(err)
} else {
for _, cidr := range *vnet.AddressSpace.AddressPrefixes {
_, n, err := net.ParseCIDR(cidr)
if err != nil {
return nil, microerror.Mask(err)
}
ret = append(ret, *n)
}
}
}
err = iterator.NextWithContext(ctx)
if err != nil {
return nil, microerror.Mask(err)
}
}
return ret, nil
}
func inArray(a []string, s string) bool {
for _, x := range a {
if x == s {
return true
}
}
return false
}
func (c *SubnetCollector) getAllTenantClusters(ctx context.Context) (*v1alpha1.AzureConfigList, error) {
tenantClusterList := &v1alpha1.AzureConfigList{}
err := c.k8sclient.CtrlClient().List(ctx, tenantClusterList, client2.InNamespace(metav1.NamespaceAll))
return tenantClusterList, err
}