Skip to content

Commit

Permalink
Add samples for MySQL flexible servers SDK (#286)
Browse files Browse the repository at this point in the history
* Simple sample sceleton for mysql & postgresql

* Test basic operations

* Fixed issue with confusing git mod name between current and forked branch

* Fix typo

* Fix malformed Example_ test name

* Change sample file names. Add README.md files

* Properly delete old files, add necessary parameters for server creation

* Update README.md files

* Refactor FirewallRule call in the clients. Fix invalid name

* Update postgresql sample to reflect newest sdk changes

* Fix package names for mysql,postgresql flexible server samples

* Add the mysql samples

* Remove own go.mod dependencies

* Fix build issue
  • Loading branch information
gechris authored Nov 10, 2020
1 parent 41e83c0 commit ffcdafe
Show file tree
Hide file tree
Showing 6 changed files with 514 additions and 1 deletion.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ require (
github.com/Azure/azure-amqp-common-go v1.1.4
github.com/Azure/azure-event-hubs-go v1.3.0
github.com/Azure/azure-pipeline-go v0.1.9 // indirect
github.com/Azure/azure-sdk-for-go v46.4.0+incompatible
github.com/Azure/azure-sdk-for-go v48.0.0+incompatible
github.com/Azure/azure-storage-blob-go v0.0.0-20181023070848-cf01652132cc
github.com/Azure/go-autorest/autorest v0.11.10
github.com/Azure/go-autorest/autorest/adal v0.9.5
Expand Down
70 changes: 70 additions & 0 deletions go.sum

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions mysql/.env.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
AZURE_BASE_GROUP_NAME=az-samples-go
AZURE_LOCATION_DEFAULT=westus2
AZURE_SAMPLES_KEEP_RESOURCES=0

# create with:
# `az ad sp create-for-rbac --name 'my-sp' --output json`
# sp must have Contributor role on subscription
AZURE_TENANT_ID=
AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
AZURE_SUBSCRIPTION_ID=

# create with:
# `az ad sp create-for-rbac --name 'my-sp' --sdk-auth > $HOME/.azure/sdk_auth.json`
# sp must have Contributor role on subscription
AZURE_AUTH_LOCATION=$HOME/.azure/sdk_auth.json

AZURE_STORAGE_ACCOUNT_NAME=
AZURE_STORAGE_ACCOUNT_GROUP_NAME=
69 changes: 69 additions & 0 deletions mysql/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
services: mysql
platforms: go
author: gechris
---

# Azure mysql Samples

This package demonstrates how to manage Azure VMs, their disks and container
instances with the Go SDK.

The child package "hybrid" demonstrates how to manage Azure VMs using Azure's
Hybrid profile.

## Contents

* [How to run all samples](#run)
* Management
* CreateServer - Create a PostgreSQL.
* UpdateServer - Updates a PostgreSQL server.
* DeleteServer - Deletes an existing PostgreSQL server.
* CreateOrUpdateFirewallRules - Creates or updates a firewall rule on the server.
* GetConfiguration - Get the configuration value that is set on the server.
* UpdateConfiguration - Updates a configuration on the server.

<a id="run"></a>
## How to run all samples

1. Get this package and all dependencies.

```bash
export PROJECT=github.com/Azure-Samples/azure-sdk-for-go-samples/mysql
go get -u $PROJECT
cd ${GOPATH}/src/${PROJECT}
dep ensure
```
1. Create an Azure service principal with the [Azure CLI][] command `az ad sp
create-for-rbac --output json` and set the following environment variables
per that command's output. You can also copy `.env.tpl` to `.env` and fill
it in; the configuration system will utilize this.

```bash
AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
AZURE_TENANT_ID=
AZURE_SUBSCRIPTION_ID=
AZURE_BASE_GROUP_NAME=
AZURE_LOCATION_DEFAULT=westus2
```

1. TODO(joshgav): grant this principal all-powerful rights to your AAD tenant to faciliate identity-related operations.
1. Run the tests: `go test -v -timeout 12h`

The timeout is optional, but some tests take longer than then default 10m to complete.

<a id="info"></a>
## More information

Please refer to [Azure SDK for Go](https://github.com/Azure/azure-sdk-for-go)
for more information.

---

This project has adopted the [Microsoft Open Source Code of
Conduct](https://opensource.microsoft.com/codeofconduct/). For more information
see the [Code of Conduct
FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact
[[email protected]](mailto:[email protected]) with any additional
questions or comments.
173 changes: 173 additions & 0 deletions mysql/mysql_client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package mysqlsamples

import (
"context"
"fmt"

"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/config"
"github.com/Azure-Samples/azure-sdk-for-go-samples/internal/iam"
mysql "github.com/Azure/azure-sdk-for-go/services/preview/mysql/mgmt/2020-07-01-preview/mysqlflexibleservers"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
)

// GetServersClient returns
func getServersClient() mysql.ServersClient {
serversClient := mysql.NewServersClient(config.SubscriptionID())
a, _ := iam.GetResourceManagementAuthorizer()
serversClient.Authorizer = a
serversClient.AddToUserAgent(config.UserAgent())
return serversClient
}

// CreateServer creates a new MySQL Server
func CreateServer(ctx context.Context, serverName, dbLogin, dbPassword string) (server mysql.Server, err error) {
serversClient := getServersClient()

// Create the server
future, err := serversClient.Create(
ctx,
config.GroupName(),
serverName,
mysql.Server{
Location: to.StringPtr(config.Location()),
Sku: &mysql.Sku{
Name: to.StringPtr("Standard_D16ds_v4"),
Tier: "GeneralPurpose",
},
ServerProperties: &mysql.ServerProperties{
AdministratorLogin: to.StringPtr(dbLogin),
AdministratorLoginPassword: to.StringPtr(dbPassword),
Version: mysql.FiveFullStopSeven, // 5.7
StorageProfile: &mysql.StorageProfile{
StorageMB: to.Int32Ptr(524288),
},
},
})

if err != nil {
return server, fmt.Errorf("cannot create mysql server: %v", err)
}

err = future.WaitForCompletionRef(ctx, serversClient.Client)
if err != nil {
return server, fmt.Errorf("cannot get the mysql server create or update future response: %v", err)
}

return future.Result(serversClient)
}

// UpdateServerStorageCapacity given the server name and the new storage capacity it updates the server's storage capacity.
func UpdateServerStorageCapacity(ctx context.Context, serverName string, storageCapacity int32) (server mysql.Server, err error) {
serversClient := getServersClient()

future, err := serversClient.Update(
ctx,
config.GroupName(),
serverName,
mysql.ServerForUpdate{
ServerPropertiesForUpdate: &mysql.ServerPropertiesForUpdate{
StorageProfile: &mysql.StorageProfile{
StorageMB: &storageCapacity,
},
},
},
)
if err != nil {
return server, fmt.Errorf("cannot update mysql server: %v", err)
}

err = future.WaitForCompletionRef(ctx, serversClient.Client)
if err != nil {
return server, fmt.Errorf("cannot get the mysql server update future response: %v", err)
}

return future.Result(serversClient)
}

// DeleteServer deletes the MySQL server.
func DeleteServer(ctx context.Context, serverName string) (resp autorest.Response, err error) {
serversClient := getServersClient()

future, err := serversClient.Delete(ctx, config.GroupName(), serverName)
if err != nil {
return resp, fmt.Errorf("cannot delete the mysql server: %v", err)
}

err = future.WaitForCompletionRef(ctx, serversClient.Client)
if err != nil {
return resp, fmt.Errorf("cannot get the mysql server update future response: %v", err)
}

return future.Result(serversClient)
}

// GetFwRulesClient returns the FirewallClient
func getFwRulesClient() mysql.FirewallRulesClient {
fwrClient := mysql.NewFirewallRulesClient(config.SubscriptionID())
a, _ := iam.GetResourceManagementAuthorizer()
fwrClient.Authorizer = a
fwrClient.AddToUserAgent(config.UserAgent())
return fwrClient
}

// CreateOrUpdateFirewallRule given the firewallname and new properties it updates the firewall rule.
func CreateOrUpdateFirewallRule(ctx context.Context, serverName, firewallRuleName, startIPAddr, endIPAddr string) error {
fwrClient := getFwRulesClient()

_, err := fwrClient.CreateOrUpdate(
ctx,
config.GroupName(),
serverName,
firewallRuleName,
mysql.FirewallRule{
FirewallRuleProperties: &mysql.FirewallRuleProperties{
StartIPAddress: &startIPAddr,
EndIPAddress: &endIPAddr,
},
},
)

return err
}

// GetConfigurationsClient creates and returns the configuration client for the server.
func getConfigurationsClient() mysql.ConfigurationsClient {
configClient := mysql.NewConfigurationsClient(config.SubscriptionID())
a, _ := iam.GetResourceManagementAuthorizer()
configClient.Authorizer = a
configClient.AddToUserAgent(config.UserAgent())
return configClient
}

// GetConfiguration given the server name and configuration name it returns the configuration.
func GetConfiguration(ctx context.Context, serverName, configurationName string) (mysql.Configuration, error) {
configClient := getConfigurationsClient()

// Get the configuration.
configuration, err := configClient.Get(ctx, config.GroupName(), serverName, configurationName)

if err != nil {
return configuration, fmt.Errorf("cannot get the configuration with name %s", configurationName)
}

return configuration, err
}

// UpdateConfiguration given the name of the configuation and the configuration object it updates the configuration for the given server.
func UpdateConfiguration(ctx context.Context, serverName string, configurationName string, configuration mysql.Configuration) (updatedConfig mysql.Configuration, err error) {
configClient := getConfigurationsClient()

future, err := configClient.Update(ctx, config.GroupName(), serverName, configurationName, configuration)

if err != nil {
return updatedConfig, fmt.Errorf("cannot update the configuration with name %s", configurationName)
}

err = future.WaitForCompletionRef(ctx, configClient.Client)
if err != nil {
return updatedConfig, fmt.Errorf("cannot get the mysql configuration update future response: %v", err)
}

return future.Result(configClient)
}
Loading

0 comments on commit ffcdafe

Please sign in to comment.