Skip to content

Commit

Permalink
task#965#AddVnetToPostgreSQLServer
Browse files Browse the repository at this point in the history
  • Loading branch information
buhongw7583c authored and frodopwns committed Apr 28, 2020
1 parent c003029 commit 7df47b5
Show file tree
Hide file tree
Showing 13 changed files with 452 additions and 4 deletions.
3 changes: 3 additions & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ resources:
- group: azure
version: v1alpha1
kind: PostgreSQLFirewallRule
- group: azure
version: v1alpha1
kind: PostgreSQLVNetRule
- group: azure
version: v1alpha1
kind: APIMgmtAPI
Expand Down
47 changes: 47 additions & 0 deletions api/v1alpha1/postgresqlvnetrule_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

package v1alpha1

import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.

// PotgreSQLVNetRuleSpec defines the desired state of PostgreSQLVNetRule
type PostgreSQLVNetRuleSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
ResourceGroup string `json:"resourceGroup"`
Server string `json:"server"`
VNetResourceGroup string `json:"vNetResourceGroup"`
VNetName string `json:"vNetName"`
SubnetName string `json:"subnetName"`
IgnoreMissingServiceEndpoint bool `json:"ignoreMissingServiceEndpoint,omitempty"`
}

// +kubebuilder:object:root=true

// PostgreSQLVNetRule is the Schema for the PostgreSQLVNetRules API
type PostgreSQLVNetRule struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`

Spec PostgreSQLVNetRuleSpec `json:"spec,omitempty"`
Status ASOStatus `json:"status,omitempty"`
}

// +kubebuilder:object:root=true

// PostgreSQLVNetRuleList contains a list of PostgreSQLVNetRule
type PostgreSQLVNetRuleList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []PostgreSQLVNetRule `json:"items"`
}

func init() {
SchemeBuilder.Register(&PostgreSQLVNetRule{}, &PostgreSQLVNetRuleList{})
}
3 changes: 3 additions & 0 deletions config/crd/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ resources:
- bases/azure.microsoft.com_postgresqlservers.yaml
- bases/azure.microsoft.com_postgresqldatabases.yaml
- bases/azure.microsoft.com_postgresqlfirewallrules.yaml
- bases/azure.microsoft.com_postgresqlvnetrules.yaml
- bases/azure.microsoft.com_apimservices.yaml
- bases/azure.microsoft.com_apimgmtapis.yaml
- bases/azure.microsoft.com_virtualnetworks.yaml
Expand Down Expand Up @@ -54,6 +55,7 @@ resources:
#- patches/webhook_in_postgresqlservers.yaml
#- patches/webhook_in_postgresqldatabases.yaml
#- patches/webhook_in_postgresqlfirewallrules.yaml
#- patches/webhook_in_postgresqlvnetrules.yaml
#- patches/webhook_in_apimservices.yaml
#- patches/webhook_in_apimgmtapis.yaml
#- patches/webhook_in_virtualnetworks.yaml
Expand Down Expand Up @@ -86,6 +88,7 @@ resources:
#- patches/cainjection_in_postgresqlservers.yaml
#- patches/cainjection_in_postgresqldatabases.yaml
#- patches/cainjection_in_postgresqlfirewallrules.yaml
#- patches/cainjection_in_postgresqlvnetrules.yaml
#- patches/cainjection_in_apimservices.yaml
#- patches/cainjection_in_apimgmtapis.yaml
#- patches/cainjection_in_virtualnetworks.yaml
Expand Down
8 changes: 8 additions & 0 deletions config/crd/patches/cainjection_in_postgresqlvnetrules.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# The following patch adds a directive for certmanager to inject CA into the CRD
# CRD conversion requires k8s 1.13 or later.
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
annotations:
certmanager.k8s.io/inject-ca-from: $(CERTIFICATE_NAMESPACE)/$(CERTIFICATE_NAME)
name: postgresqlvnetrules.azure.microsoft.com
17 changes: 17 additions & 0 deletions config/crd/patches/webhook_in_postgresqlvnetrules.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# The following patch enables conversion webhook for CRD
# CRD conversion requires k8s 1.13 or later.
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: postgresqlvnetrules.azure.microsoft.com
spec:
conversion:
strategy: Webhook
webhookClientConfig:
# this is "\n" used as a placeholder, otherwise it will be rejected by the apiserver for being blank,
# but we're going to set it later using the cert-manager (or potentially a patch if not using cert-manager)
caBundle: Cg==
service:
namespace: system
name: webhook-service
path: /convert
8 changes: 4 additions & 4 deletions config/samples/azure_v1alpha1_postgresqlserver.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ kind: PostgreSQLServer
metadata:
name: postgresqlserver-sample
spec:
location: westus2
location: eastus
resourceGroup: resourcegroup-azure-operators
serverVersion: "10"
sslEnforcement: Enabled
sku:
name: B_Gen5_2
tier: Basic
name: GP_Gen5_4 # tier + family + cores eg. - B_Gen4_1, GP_Gen5_4
tier: GeneralPurpose # possible values - 'Basic', 'GeneralPurpose', 'MemoryOptimized'
family: Gen5
size: "51200"
capacity: 2
capacity: 4
# Use the field below to optionally specify a different keyvault
# to store the server admin credential secrets in
#keyVaultToStoreSecrets: asoSecretKeyVault
11 changes: 11 additions & 0 deletions config/samples/azure_v1alpha1_postgresqlvnetrule.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
apiVersion: azure.microsoft.com/v1alpha1
kind: PostgreSQLVNetRule
metadata:
name: postgresqlvnetrule-sample1
spec:
resourceGroup: resourcegroup-azure-operators
server: postgresqlserver-sample
vNetResourceGroup: resourcegroup-azure-operators
vNetName: virtualnetwork-sample
subnetName: test1
ignoreMissingServiceEndpoint: true
28 changes: 28 additions & 0 deletions controllers/postgresqlvnetrule_controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

package controllers

import (
ctrl "sigs.k8s.io/controller-runtime"

azurev1alpha1 "github.com/Azure/azure-service-operator/api/v1alpha1"
)

// PostgreSQLVNetRuleReconciler reconciles a PostgreSQLVNetRule object
type PostgreSQLVNetRuleReconciler struct {
Reconciler *AsyncReconciler
}

// +kubebuilder:rbac:groups=azure.microsoft.com,resources=postgresqlvnetrules,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=azure.microsoft.com,resources=postgresqlvnetrules/status,verbs=get;update;patch

func (r *PostgreSQLVNetRuleReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
return r.Reconciler.Reconcile(req, &azurev1alpha1.PostgreSQLVNetRule{})
}

func (r *PostgreSQLVNetRuleReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&azurev1alpha1.PostgreSQLVNetRule{}).
Complete(r)
}
17 changes: 17 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
psqldatabase "github.com/Azure/azure-service-operator/pkg/resourcemanager/psql/database"
psqlfirewallrule "github.com/Azure/azure-service-operator/pkg/resourcemanager/psql/firewallrule"
psqlserver "github.com/Azure/azure-service-operator/pkg/resourcemanager/psql/server"
psqlvnetrule "github.com/Azure/azure-service-operator/pkg/resourcemanager/psql/vnetrule"
resourcemanagerrediscache "github.com/Azure/azure-service-operator/pkg/resourcemanager/rediscaches"
resourcemanagerresourcegroup "github.com/Azure/azure-service-operator/pkg/resourcemanager/resourcegroups"
blobContainerManager "github.com/Azure/azure-service-operator/pkg/resourcemanager/storages/blobcontainer"
Expand Down Expand Up @@ -669,6 +670,22 @@ func main() {
os.Exit(1)
}

if err = (&controllers.PostgreSQLVNetRuleReconciler{
Reconciler: &controllers.AsyncReconciler{
Client: mgr.GetClient(),
AzureClient: psqlvnetrule.NewPostgreSQLVNetRuleClient(),
Telemetry: telemetry.InitializeTelemetryDefault(
"PostgreSQLVNetRule",
ctrl.Log.WithName("controllers").WithName("PostgreSQLVNetRule"),
),
Recorder: mgr.GetEventRecorderFor("PostgreSQLVNetRule-controller"),
Scheme: scheme,
},
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "PostgreSQLVNetRule")
os.Exit(1)
}

// +kubebuilder:scaffold:builder

setupLog.Info("starting manager")
Expand Down
1 change: 1 addition & 0 deletions pkg/errhelp/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const (
NetworkAclsValidationFailure = "NetworkAclsValidationFailure"
SubnetHasServiceEndpointWithInvalidServiceName = "SubnetHasServiceEndpointWithInvalidServiceName"
InvalidAddressPrefixFormat = "InvalidAddressPrefixFormat"
FeatureNotSupportedForEdition = "FeatureNotSupportedForEdition"
)

func NewAzureError(err error) error {
Expand Down
114 changes: 114 additions & 0 deletions pkg/resourcemanager/psql/vnetrule/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

package server

import (
"context"

network "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-09-01/network"
psql "github.com/Azure/azure-sdk-for-go/services/postgresql/mgmt/2017-12-01/postgresql"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/config"
"github.com/Azure/azure-service-operator/pkg/resourcemanager/iam"
)

type PostgreSQLVNetRuleClient struct {
}

func NewPostgreSQLVNetRuleClient() *PostgreSQLVNetRuleClient {
return &PostgreSQLVNetRuleClient{}
}

func GetPostgreSQLVNetRulesClient() psql.VirtualNetworkRulesClient {
VNetRulesClient := psql.NewVirtualNetworkRulesClientWithBaseURI(config.BaseURI(), config.SubscriptionID())
a, _ := iam.GetResourceManagementAuthorizer()
VNetRulesClient.Authorizer = a
VNetRulesClient.AddToUserAgent(config.UserAgent())
return VNetRulesClient
}

// retrieves the Subnetclient
func GetGoNetworkSubnetClient() network.SubnetsClient {
SubnetsClient := network.NewSubnetsClientWithBaseURI(config.BaseURI(), config.SubscriptionID())
a, _ := iam.GetResourceManagementAuthorizer()
SubnetsClient.Authorizer = a
SubnetsClient.AddToUserAgent(config.UserAgent())
return SubnetsClient
}

// GetPostgreSQLVNetRule returns a VNet rule
func (vr *PostgreSQLVNetRuleClient) GetPostgreSQLVNetRule(
ctx context.Context,
resourceGroupName string,
serverName string,
ruleName string) (result psql.VirtualNetworkRule, err error) {

VNetRulesClient := GetPostgreSQLVNetRulesClient()

return VNetRulesClient.Get(
ctx,
resourceGroupName,
serverName,
ruleName,
)
}

// deletes a VNet rule
func (vr *PostgreSQLVNetRuleClient) DeletePostgreSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error) {

// check to see if the rule exists, if it doesn't then short-circuit
_, err = vr.GetPostgreSQLVNetRule(ctx, resourceGroupName, serverName, ruleName)
if err != nil {
return nil
}

VNetRulesClient := GetPostgreSQLVNetRulesClient()
_, err = VNetRulesClient.Delete(
ctx,
resourceGroupName,
serverName,
ruleName,
)

return err
}

// creates or updates a VNet rule
func (vr *PostgreSQLVNetRuleClient) CreateOrUpdatePostgreSQLVNetRule(
ctx context.Context,
resourceGroupName string,
serverName string,
ruleName string,
VNetRG string,
VNetName string,
SubnetName string,
IgnoreServiceEndpoint bool) (vnr psql.VirtualNetworkRule, err error) {

VNetRulesClient := GetPostgreSQLVNetRulesClient()
SubnetClient := GetGoNetworkSubnetClient()

// Get ARM Resource ID of Subnet based on the VNET name, Subnet name and Subnet Address Prefix
subnet, err := SubnetClient.Get(ctx, VNetRG, VNetName, SubnetName, "")
if err != nil {
return vnr, err
}
subnetResourceID := *subnet.ID

// Populate parameters with the right ID
parameters := psql.VirtualNetworkRule{
VirtualNetworkRuleProperties: &psql.VirtualNetworkRuleProperties{
VirtualNetworkSubnetID: &subnetResourceID,
IgnoreMissingVnetServiceEndpoint: &IgnoreServiceEndpoint,
},
}

// Call CreateOrUpdate
result, err := VNetRulesClient.CreateOrUpdate(
ctx,
resourceGroupName,
serverName,
ruleName,
parameters,
)
return result.Result(VNetRulesClient)
}
26 changes: 26 additions & 0 deletions pkg/resourcemanager/psql/vnetrule/manager.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

package server

import (
"context"

psql "github.com/Azure/azure-sdk-for-go/services/postgresql/mgmt/2017-12-01/postgresql"
"github.com/Azure/azure-service-operator/pkg/resourcemanager"
)

type PostgreSqlVNetRuleManager interface {
CreateOrUpdatePostgreSQLVNetRule(
ctx context.Context,
resourceGroupName string,
serverName string,
ruleName string,
VNetRG string,
VNetName string,
SubnetName string,
IgnoreServiceEndpoint bool) (result psql.VirtualNetworkRule, err error)
DeletePostgreSQLVNetRule(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (err error)
GetPostgreSQLVNetRulesClient(ctx context.Context, resourceGroupName string, serverName string, ruleName string) (result psql.VirtualNetworkRule, err error)
resourcemanager.ARMClient
}
Loading

0 comments on commit 7df47b5

Please sign in to comment.