|
| 1 | +################################################################################ |
| 2 | +# THIS SOFTWARE IS PROVIDED BY NETAPP "AS IS" AND ANY EXPRESS OR IMPLIED |
| 3 | +# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 4 | +# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO |
| 5 | +# EVENT SHALL NETAPP BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
| 6 | +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 7 | +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; |
| 8 | +# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, |
| 9 | +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR' |
| 10 | +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF |
| 11 | +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 12 | +################################################################################ |
| 13 | + |
| 14 | +################################################################################ |
| 15 | +# This Lambda function is used to set the auto size feature to 'grow' on a |
| 16 | +# volume that was created in an AWS FSx for NetApp ONTAP file system. It is |
| 17 | +# expected to be triggered by a CloudWatch event that is generated when a |
| 18 | +# volume is created. The function uses the ONTAP API to set the auto size |
| 19 | +# mode to 'grow' on the volume therefore it most run within the VPC where the |
| 20 | +# FSx for ONTAP file system is located. |
| 21 | +################################################################################ |
| 22 | + |
| 23 | +import json |
| 24 | +import time |
| 25 | +import urllib3 |
| 26 | +from urllib3.util import Retry |
| 27 | +import logging |
| 28 | +import boto3 |
| 29 | +# |
| 30 | +# Create a table of secret names and keys for the username and password for each of the FSxIds. |
| 31 | +secretsTable = [ |
| 32 | + {"id": "fs-0e8d9172fa545ef3b", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"}, |
| 33 | + {"id": "fs-020de2687bd98ccf7", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"}, |
| 34 | + {"id": "fs-07bcb7ad84ac75e43", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"}, |
| 35 | + {"id": "fs-077b5ff41951c57b2", "secretName": "mon-fsxn-credentials", "usernameKey": "mon-fsxn-username", "passwordKey": "mon-fsxn-password"} |
| 36 | + ] |
| 37 | +# |
| 38 | +# Set the region where the secrets are stored. |
| 39 | +secretsManagerRegion="us-west-2" |
| 40 | +# |
| 41 | +# Set the auto size mode. Supported values are "grow", "grow_shrink", and "off". |
| 42 | +autoSizeMode = "grow" |
| 43 | +# |
| 44 | +# Set the grow-threshold-percentage for the volume. This is the percentage of the volume that must be used before it grows. |
| 45 | +growThresholdPercentage = 85 |
| 46 | +# |
| 47 | +# Set the maximum grow size for the volume in terms of the percentage of the provisioned size. |
| 48 | +maxGrowSizePercentage = 120 |
| 49 | +# |
| 50 | +# Set the shrink-threshold-percentage for the volume. This is the percentage of the volume that must be free before it shrinks. |
| 51 | +shrinkThresholdPercentage = 50 |
| 52 | +# |
| 53 | +# Set the minimum shirtk size for the volume in terms of the percentage of the provisioned size. |
| 54 | +minShrinkSizePercentage = 100 |
| 55 | +# |
| 56 | +# Set the iime to wait for a volume to get created. This Lambda function will |
| 57 | +# loop waiting for the volume to be created on the ONTAP side so it can set |
| 58 | +# the auto size parameters. It will wait up to the number of seconds specified |
| 59 | +# below before giving up. NOTE: You must set the timeout of this function |
| 60 | +# to at least the number of seconds specified here, and probably two times |
| 61 | +# the number here to account for the time it takes to do the API call, |
| 62 | +# otherwise the Lambda timeout feature will kill it before it is able to |
| 63 | +# iterate as many times as you want it to. Also note that the main reason for |
| 64 | +# it to take a while for a volume to get created is when multiple are being |
| 65 | +# created at the same time, so if you have automation that might create a lot of |
| 66 | +# volumes at the same time, you might need to either adjust this number really |
| 67 | +# high, or come up with another way to get the auto size mode. |
| 68 | +maxWaitTime=60 |
| 69 | + |
| 70 | +################################################################################ |
| 71 | +# This function is used to obtain the username and password from AWS's Secrets |
| 72 | +# Manager for the fsxnId passed in. It returns empty strings if it can't |
| 73 | +# find the credentials. |
| 74 | +################################################################################ |
| 75 | +def getCredentials(secretsManagerClient, fsxnId): |
| 76 | + |
| 77 | + for secretItem in secretsTable: |
| 78 | + if secretItem['id'] == fsxnId: |
| 79 | + secretsInfo = secretsManagerClient.get_secret_value(SecretId=secretItem['secretName']) |
| 80 | + secrets = json.loads(secretsInfo['SecretString']) |
| 81 | + username = secrets[secretItem['usernameKey']] |
| 82 | + password = secrets[secretItem['passwordKey']] |
| 83 | + return (username, password) |
| 84 | + return ("", "") |
| 85 | + |
| 86 | +################################################################################ |
| 87 | +# This function returns the AWS structure for a FSxN volume based on the |
| 88 | +# volumeId passed it. It confirms that the volume has been created on the ONTAP |
| 89 | +# side by checking that the ResourceARN field equals the volumeARN passed in |
| 90 | +# that came from the volume creation event and that the UUID field has been |
| 91 | +# populated. It returns None if it can't find the volume. |
| 92 | +################################################################################ |
| 93 | +def getVolumeData(fsxClient, volumeId, volumeARN): |
| 94 | + |
| 95 | + global logger |
| 96 | + |
| 97 | + cnt = 0 |
| 98 | + while cnt < maxWaitTime: |
| 99 | + awsVolume = fsxClient.describe_volumes(VolumeIds=[volumeId])['Volumes'][0] |
| 100 | + if awsVolume['ResourceARN'] == volumeARN and awsVolume['OntapConfiguration'].get("UUID") != None: |
| 101 | + return awsVolume |
| 102 | + logger.debug(f'Looping, getting the UUID {cnt}') |
| 103 | + cnt += 1 |
| 104 | + time.sleep(1) |
| 105 | + |
| 106 | + return None |
| 107 | + |
| 108 | +################################################################################ |
| 109 | +################################################################################ |
| 110 | +def lambda_handler(event, context): |
| 111 | + |
| 112 | + global logger |
| 113 | + # |
| 114 | + # Set up "logging" to appropriately display messages. It can be set it up |
| 115 | + # to send messages to a syslog server. |
| 116 | + logging.basicConfig(datefmt='%Y-%m-%d_%H:%M:%S', format='%(asctime)s:%(name)s:%(levelname)s:%(message)s', encoding='utf-8') |
| 117 | + logger = logging.getLogger("set_fsxn_volume_auto_size") |
| 118 | +# logger.setLevel(logging.DEBUG) |
| 119 | + logger.setLevel(logging.INFO) |
| 120 | + # |
| 121 | + # Set the logging level higher for these noisy modules to mute thier messages. |
| 122 | + logging.getLogger("botocore").setLevel(logging.WARNING) |
| 123 | + logging.getLogger("boto3").setLevel(logging.WARNING) |
| 124 | + logging.getLogger("urllib3").setLevel(logging.WARNING) |
| 125 | + # |
| 126 | + # Create a Secrets Manager client. |
| 127 | + session = boto3.session.Session() |
| 128 | + secretsManagerClient = session.client(service_name='secretsmanager', region_name=secretsManagerRegion) |
| 129 | + # |
| 130 | + # Disable warning about connecting to servers with self-signed SSL certificates. |
| 131 | + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) |
| 132 | + # |
| 133 | + # Set the https retries to 1. |
| 134 | + retries = Retry(total=None, connect=1, read=1, redirect=10, status=0, other=0) # pylint: disable=E1123 |
| 135 | + http = urllib3.PoolManager(cert_reqs='CERT_NONE', retries=retries) |
| 136 | + # |
| 137 | + # Get the FSxN ID, region, volume name, volume ID, and volume ARN from the CloudWatch event. |
| 138 | + fsxId = event['detail']['responseElements']['volume']['fileSystemId'] |
| 139 | + regionName = event['detail']['awsRegion'] |
| 140 | + volumeName = event['detail']['requestParameters']['name'] |
| 141 | + volumeId = event['detail']['responseElements']['volume']['volumeId'] |
| 142 | + volumeARN = event['detail']['responseElements']['volume']['resourceARN'] |
| 143 | + if fsxId == "" or regionName == "" or volumeId == "" or volumeName == "" or volumeARN == "": |
| 144 | + message = "Couldn't obtain the fsxId, region, volume name, volume ID or volume ARN from the CloudWatch evevnt." |
| 145 | + logger.critcal(message) |
| 146 | + raise Exception(message) |
| 147 | + |
| 148 | + logger.debug(f'Data from CloudWatch event: FSxID={fsxId}, Region={regionName}, VolumeName={volumeName}, volumeId={volumeId}.') |
| 149 | + # |
| 150 | + # Get the username and password for the FSxN ID. |
| 151 | + (username, password) = getCredentials(secretsManagerClient, fsxId) |
| 152 | + if username == "" or password == "": |
| 153 | + message = f'No credentials for FSxN ID: {fsxId}.' |
| 154 | + logger.critical(message) |
| 155 | + raise Exception(message) |
| 156 | + # |
| 157 | + # Build a header that is used for all the ONTAP API requests. |
| 158 | + auth = urllib3.make_headers(basic_auth=f'{username}:{password}') |
| 159 | + headers = { **auth } |
| 160 | + # |
| 161 | + # Get the management IP of the FSxN file system. |
| 162 | + fsxClient = boto3.client('fsx', region_name = regionName) |
| 163 | + fs = fsxClient.describe_file_systems(FileSystemIds = [fsxId])['FileSystems'][0] |
| 164 | + fsxnIp = fs['OntapConfiguration']['Endpoints']['Management']['IpAddresses'][0] |
| 165 | + if fsxnIp == "": |
| 166 | + message = f"Can't find management IP for FSxN file system with an ID of '{fsxId}'." |
| 167 | + logger.critical(message) |
| 168 | + raise Exception(message) |
| 169 | + # |
| 170 | + # Get the volume UUID and volume size based on the volume ID. |
| 171 | + volumeData = getVolumeData(fsxClient, volumeId, volumeARN) |
| 172 | + if volumeData == None: |
| 173 | + message=f'Failed to get volume information for volumeID: {volumeId}.' |
| 174 | + logger.critical(message) |
| 175 | + raise Exception(message) |
| 176 | + volumeUUID = volumeData["OntapConfiguration"]["UUID"] |
| 177 | + volumeSizeInMegabytes = volumeData["OntapConfiguration"]["SizeInMegabytes"] |
| 178 | + # |
| 179 | + # Set the auto grow feature. |
| 180 | + try: |
| 181 | + endpoint = f'https://{fsxnIp}/api/storage/volumes/{volumeUUID}' |
| 182 | + maximum = volumeSizeInMegabytes * maxGrowSizePercentage / 100 * 1024 * 1024 |
| 183 | + minimum = volumeSizeInMegabytes * minShrinkSizePercentage / 100 * 1024 * 1024 |
| 184 | + data = json.dumps({"autosize": {"mode": autoSizeMode, "grow_threshold": growThresholdPercentage, "maximum": maximum, "minimum": minimum, "shrink_threshold": shrinkThresholdPercentage}}) |
| 185 | + logger.debug(f'Trying {endpoint} with {data}.') |
| 186 | + response = http.request('PATCH', endpoint, headers=headers, timeout=5.0, body=data) |
| 187 | + if response.status >= 200 and response.status <= 299: |
| 188 | + logger.info(f"Updated the auto size parameters for volume name {volumeName}.") |
| 189 | + else: |
| 190 | + logger.error(f'API call to {endpoint} failed. HTTP status code: {response.status}. Error message: {response.data}.') |
| 191 | + except Exception as err: |
| 192 | + logger.critical(f'Failed to issue API against {fsxnIp}. The error messages received: "{err}".') |
0 commit comments