Sample coding for downloading a file (backing up encryption keys)

REST API Reference Guide for Virtual Storage Platform 5000, Virtual Storage Platform E Series, and Virtual Storage Platform G/F Series

Version
93-07-0x
90-09-0x
88-08-10
Audience
anonymous
Part Number
MK-98RD9014-17
This section provides the sample coding for backing up encryption keys. This sample coding includes the procedure for downloading an encryption key backup file to a client.

Sample coding operation flow for backing up encryption keys

The following table shows the sample coding operation flow for backing up encryption keys and the corresponding code constructs.
Step

Sample coding operation flow

Code constructs

1

Import necessary libraries and set parameters.

-

2

Define headers.

Specifying request headers (for the default HTTP headers)

3

Check the version of the REST API.

Getting information about the version of the REST API by performing a GET operation

4

Download the encryption key backup file.

Getting the URLs of the resources (when fixed object IDs such as those for single instances are specified)

Running actions for objects by using the POST operation

5

Output error messages.

Outputting error messages

Values to be specified for the parameters in the sample coding

The following table shows the values specified for the parameters in the sample coding. If necessary, change the settings to match the system environment and requirements.

Parameter

Value

Description

USER_CREDENTIAL

("user1","pass1")

This information is used for authentication by the storage system. In the sample coding, the user ID is user1, and the password is pass1. The user must have the Security Administrator (View & Modify) role.

BACKUP_PASSWORD

backuppassword

The password for the encryption key backup file

ENCRYPTION_KEY_BACKUP_FILE_PATH

D:\encryption\\

The path where the encryption key backup file is stored

ENCRYPTION_KEY_BACKUP_FILE_NAME

backupfile.ekf

The name of the encryption key backup file

Contents of the sample coding

This subsection explains the sample coding.

  1. Import necessary libraries and set parameters.

    Before starting the volume allocation processing, the sample coding imports the required libraries or classes. In addition to the common libraries, the sample coding also imports the BlockStorageAPI class that defines the function that generates URLs.

    # coding:utf-8
    
    """
    backup_encryption_keys
    
    This program requires API version 1.12.0 or newer.
    """
    
    import requests
    import json
    import sys
    import http.client
    import traceback
    import rest_server_param
    import storage_param
    
    from block_storage_api import BlockStorageAPI
    

    Set parameters to be used in the sample coding.

    # #################Initialize parameters################# #
    # Change the following parameters to fit your environment
    
    # An user id and password of the target storage
    USER_CREDENTIAL = ("user1", "pass1")
    
    # A backup password
    BACKUP_PASSWORD = "backuppassword"
    
    # A path of encryption key backup file
    ENCRYPTION_KEY_BACKUP_FILE_PATH = "D:\encryption\\"
    
    # A encryption key backup file name
    ENCRYPTION_KEY_BACKUP_FILE_NAME = "backupfile.ekf"
    
    ###########################################################
    
  2. Define headers.

    Define the HTTP request header. In addition to the JSON format, which is the standard format for the REST API, define the header information so that the stream data format, which is used in the API function for file downloading, can also be handled.

    # ###You don't have to change the following parameters### #
    block_storage_api = BlockStorageAPI(
        rest_server_param.REST_SERVER_IP_ADDR,
        rest_server_param.REST_SERVER_PORT,
        storage_param.STORAGE_MODEL,
        storage_param.SERIAL_NUMBER)
    
    headers = {"content-type": "application/json",
               "accept": "application/json"}
    
    file_download_headers = {"content-type": "application/json",
                             "accept": "application/octet-stream"}
    
    REQUIRED_MAJOR_VERSION = 1
    REQUIRED_MINOR_VERSION = 12
    
    ###########################################################
    
  3. Check the version of the REST API.

    Get information about the version of the REST API to make sure that the version is supported.

    """
    Check whether this API version allows the REST
     Server to execute this program
    
    @param api_version api version of this REST Server
    @param required_major_version the lowest number of
           the major version that this program requires
    @param required_minor_version the lowest number of
           the minor version that this program requires
    
    """
    
    
    def check_api_version(api_version, required_major_version,
                          required_minor_version):
        version = api_version.split(".")
        major_version = int(version[0])
        minor_version = int(version[1])
        if not ((major_version == required_major_version and
                 minor_version >= required_minor_version) or
                major_version >= required_major_version + 1):
            sys.exit("This program requires API Version " +
                     str(required_major_version) + "." +
                     str(required_minor_version) +
                     "." + "x or newer.\n")
    
    try:
        # step1 Check the API version #
        print("Check the API version")
        url = block_storage_api.api_version()
        r = requests.get(url, headers=headers, verify=False)
        if r.status_code != http.client.OK:
            raise requests.HTTPError(r)
        check_api_version(
            r.json()["apiVersion"],
            REQUIRED_MAJOR_VERSION,
            REQUIRED_MINOR_VERSION)
    
    
  4. Download the encryption key backup file.

    Download the encryption key backup file to a specified path.

        # step2 Get the encryption keys backup #
        print("Get the encryption keys backup")
        url = block_storage_api.encryption_key_file_backup()
        body = {
            "parameters": {
                "password": BACKUP_PASSWORD
            }
        }
        r = requests.post(url, headers=file_download_headers,
                          auth=USER_CREDENTIAL, data=json.dumps(body),
                          verify=False)
        if r.status_code != http.client.OK:
            raise requests.HTTPError(r)
        with open(ENCRYPTION_KEY_BACKUP_FILE_PATH + ENCRYPTION_KEY_BACKUP_FILE_NAME, 'wb') as saveFile:
            saveFile.write(r.content)
    
  5. Output error messages.

    In the sample coding, processing for communication errors, HTTP request errors, and job execution errors is described. If a communication error occurs, an error message is output. If an HTTP request error occurs, the error code, the error message, and the response body are output. If a job execution error occurs, all of the contents included in the job execution result are output.

    except requests.ConnectionError:
        sys.stderr.write("Connection Error!\n")
        sys.stderr.write(traceback.format_exc())
    except requests.HTTPError as he:
        sys.stderr.write("HTTP Error! status code : ")
        sys.stderr.write(str(he.args[0].status_code) + "\n")
        sys.stderr.write(he.args[0].text + "\n")
    except Exception as e:
        sys.stderr.write(traceback.format_exc())
        for msg in e.args:
            sys.stderr.write(str(msg) + "\n")
    finally:
        print("Operation was completed.")
        sys.exit()