-
Notifications
You must be signed in to change notification settings - Fork 22
/
secretsync.go
250 lines (221 loc) · 9.55 KB
/
secretsync.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
package secret
import (
"context"
"fmt"
"regexp"
"time"
"github.com/IBM/go-sdk-core/v5/core"
"github.com/IBM/platform-services-go-sdk/resourcemanagerv2"
operatorv1 "github.com/openshift/api/operator/v1"
"github.com/openshift/ibm-vpc-block-csi-driver-operator/pkg/util"
"github.com/openshift/library-go/pkg/controller/factory"
"github.com/openshift/library-go/pkg/operator/events"
"github.com/openshift/library-go/pkg/operator/resource/resourceapply"
"github.com/openshift/library-go/pkg/operator/v1helpers"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
corelisters "k8s.io/client-go/listers/core/v1"
"k8s.io/klog/v2"
)
// This SecretSyncController translates Secret provided by cloud-credential-operator into
// format required by the CSI driver.
type SecretSyncController struct {
operatorClient v1helpers.OperatorClient
kubeClient kubernetes.Interface
secretLister corelisters.SecretLister
configMapLister corelisters.ConfigMapLister
eventRecorder events.Recorder
getResourceID func(resourceName, accountID, apiKey, resourceManagerEndpoint, iamEndpoint string) (string, error)
}
const (
// Name of key with ibmcloud_api_key in Secret provided by cloud-credentials-operator.
cloudSecretKey = "ibmcloud_api_key"
// Name of key with cloud.conf in ConfigMap provided by cloud-credentials-operator.
CloudConfigmapKey = "cloud.conf"
// Name of the key in secret storage-secret-store creating on operator namespace
StorageSecretStoreKey = "slclient.toml"
// defaultTokenExchangeURL is used as fallback for g2_token_exchange_endpoint_url, if iamEndpointOverride isn't provided in the cloud-conf configmap.
defaultTokenExchangeURL = "https://iam.cloud.ibm.com"
// defaultRIAASEndpointURL is used as fallback for g2_riaas_endpoint_url, if g2EndpointOverride in the cloud-conf configmap.
defaultRIAASEndpointURL = "https://%s.iaas.cloud.ibm.com"
// defaultResourceManagerEndpoint is used as fallback if rmEndpointOverride is not provided in the cloud-conf configmap.
defaultResourceManagerEndpoint = "https://resource-controller.cloud.ibm.com"
// iamEndpointOverride is the key expected in cloud conf config map, for the g2_token_exchange_endpoint_url to be overriden.
iamEndpointOverride = "iamEndpointOverride"
// g2EndpointOverride is the key expected in cloud conf config map, for the g2_riaas_endpoint_url to be overriden.
g2EndpointOverride = "g2EndpointOverride"
// rmEndpointOverride is the key expected in cloud conf config map for resource manager endpoint.
rmEndpointOverride = "rmEndpointOverride"
// storage-secret-store data format
StorageSecretTomlTemplate = `[vpc]
iam_client_id = "bx"
iam_client_secret = "bx"
g2_token_exchange_endpoint_url = "%s"
g2_riaas_endpoint_url = "%s"
g2_resource_group_id = "%s"
g2_api_key = "%s"
provider_type = "g2"
`
)
func NewSecretSyncController(
operatorClient v1helpers.OperatorClient,
kubeClient kubernetes.Interface,
informers v1helpers.KubeInformersForNamespaces,
resync time.Duration,
eventRecorder events.Recorder) factory.Controller {
// Read secret from operator namespace and save the translated one to the operand namespace
secretInformer := informers.InformersFor(util.OperatorNamespace)
configMapInformer := informers.InformersFor(util.ConfigMapNamespace)
c := &SecretSyncController{
operatorClient: operatorClient,
kubeClient: kubeClient,
secretLister: secretInformer.Core().V1().Secrets().Lister(),
configMapLister: configMapInformer.Core().V1().ConfigMaps().Lister(),
eventRecorder: eventRecorder.WithComponentSuffix("SecretSync"),
getResourceID: defaultGetResourceID,
}
return factory.New().WithSync(c.sync).ResyncEvery(resync).WithSyncDegradedOnError(operatorClient).WithInformers(
operatorClient.Informer(),
secretInformer.Core().V1().Secrets().Informer(),
configMapInformer.Core().V1().Secrets().Informer(),
).ToController("SecretSync", eventRecorder)
}
func (c *SecretSyncController) sync(ctx context.Context, syncCtx factory.SyncContext) error {
opSpec, _, _, err := c.operatorClient.GetOperatorState()
if err != nil {
klog.V(2).ErrorS(err, "Error while getting operator state")
return err
}
if opSpec.ManagementState != operatorv1.Managed {
klog.V(2).Info("Operator management state is not managed")
return nil
}
cloudSecret, err := c.secretLister.Secrets(util.OperatorNamespace).Get(util.CloudCredentialSecretName)
if err != nil {
if errors.IsNotFound(err) {
// TODO: report error after some while?
klog.V(2).Infof("Waiting for secret %s from %s", util.CloudCredentialSecretName, util.OperatorNamespace)
return nil
}
klog.V(2).ErrorS(err, "Secret listener failed to get secret details")
return err
}
cloudConfConfigMap, err := c.configMapLister.ConfigMaps(util.ConfigMapNamespace).Get(util.ConfigMapName)
if err != nil {
if errors.IsNotFound(err) {
// TODO: report error after some while?
klog.V(2).Infof("Waiting for configmap %s from %s", util.ConfigMapName, util.ConfigMapNamespace)
return nil
}
klog.V(2).ErrorS(err, "Configmap listener failed to get cm details")
return err
}
// Get the storage-secret-store secret to be created from ibm-cloud-credential secret and clod-conf configmap
driverSecret, err := c.translateSecret(cloudSecret, cloudConfConfigMap)
if err != nil {
klog.V(2).ErrorS(err, "Error while extracting data from secret/cm")
return err
}
_, _, err = resourceapply.ApplySecret(ctx, c.kubeClient.CoreV1(), c.eventRecorder, driverSecret)
if err != nil {
klog.V(2).ErrorS(err, "Error while creating the secret")
return err
}
klog.V(2).Infof("%s secret created successfully", util.IBMCSIDriverSecretName)
return nil
}
func (c *SecretSyncController) translateSecret(cloudSecret *v1.Secret, cloudConf *v1.ConfigMap) (*v1.Secret, error) {
apiKey, ok := cloudSecret.Data[cloudSecretKey]
if !ok {
return nil, fmt.Errorf("cloud-credential-operator secret %s did not contain key %s", util.CloudCredentialSecretName, cloudSecretKey)
}
conf, ok := cloudConf.Data[CloudConfigmapKey]
if !ok {
return nil, fmt.Errorf("cloud-credential-operator configmap %s did not contain key %s", util.ConfigMapName, cloudSecretKey)
}
var re *regexp.Regexp
var match []string
// Extracting the region from configmap
re = regexp.MustCompile("region = (.*?)\n")
match = re.FindStringSubmatch(conf)
if len(match) <= 0 {
return nil, fmt.Errorf("cloud-credential-operator configmap %s did not contain region", util.ConfigMapName)
}
region := match[1]
re = regexp.MustCompile("g2ResourceGroupName = (.*?)\n")
match = re.FindStringSubmatch(conf)
if len(match) <= 1 {
return nil, fmt.Errorf("cloud-credential-operator configmap %s did not contain resourcegroupname", util.ConfigMapName)
}
resourceGroupName := match[1]
re = regexp.MustCompile("accountID = (.*?)\n")
match = re.FindStringSubmatch(conf)
if len(match) <= 1 {
return nil, fmt.Errorf("cloud-credential-operator configmap %s did not contain accountID", util.ConfigMapName)
}
accountID := match[1]
iamEndpoint := fetchEndpoint(iamEndpointOverride, conf, defaultTokenExchangeURL)
riaasEndpoint := fetchEndpoint(g2EndpointOverride, conf, fmt.Sprintf(defaultRIAASEndpointURL, region))
resourceManagerEndpoint := fetchEndpoint(rmEndpointOverride, conf, defaultResourceManagerEndpoint)
resourceId, err := c.getResourceID(resourceGroupName, accountID, string(apiKey), resourceManagerEndpoint, iamEndpoint)
if err != nil {
return nil, err
}
// Creating secret data storage-secret-store
tomlData := fmt.Sprintf(StorageSecretTomlTemplate, iamEndpoint, riaasEndpoint, resourceId, apiKey)
data := make(map[string][]byte)
data[StorageSecretStoreKey] = []byte(tomlData)
secret := v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: util.IBMCSIDriverSecretName,
Namespace: util.OperatorNamespace,
},
Type: v1.SecretTypeOpaque,
Data: data,
}
return &secret, nil
}
// fetchEndpoint fetches the url provided against endpointkey
func fetchEndpoint(endpointkey, conf, defaultEndpointValue string) string {
var re *regexp.Regexp
var match []string
// Fetch url provided against endpointkey
re = regexp.MustCompile(fmt.Sprintf("%s = (.*?)\n", endpointkey))
match = re.FindStringSubmatch(conf)
// If the url doesn't exist return default value
if len(match) <= 1 || match[1] == "" {
klog.V(2).Infof("%s is not provided", endpointkey)
return defaultEndpointValue
}
return match[1]
}
func defaultGetResourceID(resourceName, accountID, apiKey, rmEndpoint, iamEndpoint string) (string, error) {
serviceClientOptions := &resourcemanagerv2.ResourceManagerV2Options{
URL: rmEndpoint,
Authenticator: &core.IamAuthenticator{ApiKey: apiKey, URL: iamEndpoint},
}
serviceClient, err := resourcemanagerv2.NewResourceManagerV2UsingExternalConfig(serviceClientOptions)
if err != nil {
return "", err
}
listResourceGroupsOptions := serviceClient.NewListResourceGroupsOptions()
listResourceGroupsOptions.SetAccountID(accountID)
listResourceGroupsOptions.SetName(resourceName)
resourceGroupList, detailedResponse, err := serviceClient.ListResourceGroups(listResourceGroupsOptions)
if err != nil {
return "", err
}
if len(resourceGroupList.Resources) > 0 {
for _, v := range resourceGroupList.Resources {
if v.Name != nil && *v.Name == resourceName {
resourceID := *v.ID
return resourceID, nil
}
}
}
transactionId := detailedResponse.Headers.Get("Transaction-Id")
klog.V(2).Infof("%s TransactionId for the resource group %s", transactionId, resourceName)
return "", fmt.Errorf("Resource group '%s' could not locate at the moment, controller will retry after %s.", resourceName, util.Resync.String())
}