|
| 1 | +import json |
| 2 | +import argparse |
| 3 | +import tempfile |
| 4 | +from azureml.core import Workspace |
| 5 | +from azureml.exceptions import WebserviceException |
| 6 | +from azureml._model_management._util import _get_mms_url, get_requests_session |
| 7 | +from azureml._model_management._constants import ( |
| 8 | + AKS_WEBSERVICE_TYPE, |
| 9 | + ACI_WEBSERVICE_TYPE, |
| 10 | + UNKNOWN_WEBSERVICE_TYPE, |
| 11 | + MMS_SYNC_TIMEOUT_SECONDS, |
| 12 | +) |
| 13 | +from azureml.core.webservice import Webservice, AciWebservice, AksWebservice |
| 14 | +from azureml._restclient.clientbase import ClientBase |
| 15 | + |
| 16 | +MIGRATION_WEBSERVICE_TYPES = [AKS_WEBSERVICE_TYPE, ACI_WEBSERVICE_TYPE] |
| 17 | + |
| 18 | + |
| 19 | +def export( |
| 20 | + ws: Workspace, |
| 21 | + service_name: str = None, |
| 22 | + timeout_seconds: int = None, |
| 23 | + show_output: bool = True, |
| 24 | +): |
| 25 | + """ |
| 26 | + Export all services under target workspace into template and parameters. |
| 27 | + :param ws: Target workspace. |
| 28 | + :param service_name: the service name to be migrated. |
| 29 | + :param show_output: Whether print outputs. |
| 30 | + :param timeout_seconds: Timeout settings for waiting export. |
| 31 | + """ |
| 32 | + base_url = _get_mms_url(ws) |
| 33 | + mms_endpoint = base_url + "/services/" + service_name |
| 34 | + headers = {"Content-Type": "application/json"} |
| 35 | + headers.update(ws._auth_object.get_authentication_header()) |
| 36 | + try: |
| 37 | + resp = ClientBase._execute_func( |
| 38 | + get_requests_session().get, |
| 39 | + mms_endpoint, |
| 40 | + headers=headers, |
| 41 | + timeout=MMS_SYNC_TIMEOUT_SECONDS, |
| 42 | + ) |
| 43 | + except: |
| 44 | + raise WebserviceException(f"Cannot get service {service_name}") |
| 45 | + |
| 46 | + if resp.status_code == 404: |
| 47 | + raise WebserviceException(f"Service {service_name} does not exist.") |
| 48 | + |
| 49 | + content = resp.content |
| 50 | + if isinstance(resp.content, bytes): |
| 51 | + content = resp.content.decode("utf-8") |
| 52 | + service = json.loads(content) |
| 53 | + if service["state"] != "Healthy": |
| 54 | + raise WebserviceException( |
| 55 | + f"service {service_name} is unhealthy, migration with this tool is not supported." |
| 56 | + ) |
| 57 | + compute_type = service["computeType"] |
| 58 | + if compute_type.upper() not in MIGRATION_WEBSERVICE_TYPES: |
| 59 | + raise WebserviceException( |
| 60 | + 'Invalid compute type "{}". Valid compute types are "{}"'.format( |
| 61 | + compute_type, ",".join(MIGRATION_WEBSERVICE_TYPES) |
| 62 | + ) |
| 63 | + ) |
| 64 | + compute_name = service_name |
| 65 | + if compute_type.upper() == AKS_WEBSERVICE_TYPE: |
| 66 | + compute_name = service["computeName"] |
| 67 | + |
| 68 | + mms_endpoint = base_url + "/services/export" |
| 69 | + export_payload = {"serviceName": service_name} |
| 70 | + try: |
| 71 | + resp = ClientBase._execute_func( |
| 72 | + get_requests_session().post, |
| 73 | + mms_endpoint, |
| 74 | + headers=headers, |
| 75 | + json=export_payload, |
| 76 | + ) |
| 77 | + except: |
| 78 | + raise WebserviceException(f"Cannot get service {service_name}") |
| 79 | + |
| 80 | + if resp.status_code == 202: |
| 81 | + service_entity = None |
| 82 | + if compute_type.upper() == AKS_WEBSERVICE_TYPE: |
| 83 | + service_entity = AksWebservice(ws, service_name) |
| 84 | + elif compute_type.upper() == ACI_WEBSERVICE_TYPE: |
| 85 | + service_entity = AciWebservice(ws, service_name) |
| 86 | + service_entity.state = "Exporting" |
| 87 | + service_entity._operation_endpoint = ( |
| 88 | + _get_mms_url(service_entity.workspace) |
| 89 | + + f'/operations/{resp.content.decode("utf-8")}' |
| 90 | + ) |
| 91 | + state, _, operation = service_entity._wait_for_operation_to_complete( |
| 92 | + show_output, timeout_seconds |
| 93 | + ) |
| 94 | + if state == "Succeeded": |
| 95 | + export_folder = operation.get("resourceLocation").split("/")[-1] |
| 96 | + storage_account = service_entity.workspace.get_details().get( |
| 97 | + "storageAccount" |
| 98 | + ) |
| 99 | + if show_output: |
| 100 | + print( |
| 101 | + f"Services have been exported to storage account: {storage_account} \n" |
| 102 | + f"Folder path: azureml/{export_folder}" |
| 103 | + ) |
| 104 | + return storage_account.split("/")[-1], export_folder, compute_name |
| 105 | + else: |
| 106 | + raise WebserviceException( |
| 107 | + "Received bad response from Model Management Service:\n" |
| 108 | + "Response Code: {}\n" |
| 109 | + "Headers: {}\n" |
| 110 | + "Content: {}".format(resp.status_code, resp.headers, resp.content) |
| 111 | + ) |
| 112 | + |
| 113 | + |
| 114 | +def overwrite_parameters( |
| 115 | + parms: dict, endpoint_name: str = None, deployment_name: str = None |
| 116 | +): |
| 117 | + """ |
| 118 | + Overwrite parameters |
| 119 | + :param deployment_name: v2 online-deployment name. Default will be v1 service name. |
| 120 | + :param endpoint_name: v2 online-endpoint name. Default will be v1 service name. |
| 121 | + :param parms: parameters as dict: loaded v2 parameters. |
| 122 | + """ |
| 123 | + properties = parms["onlineEndpointProperties"]["value"] |
| 124 | + traffic = parms["onlineEndpointPropertiesTrafficUpdate"]["value"] |
| 125 | + properties.pop("keys") |
| 126 | + traffic.pop("keys") |
| 127 | + if endpoint_name: |
| 128 | + parms["onlineEndpointName"]["value"] = endpoint_name |
| 129 | + |
| 130 | + # this is optional |
| 131 | + if deployment_name: |
| 132 | + parms["onlineDeployments"]["value"][0]["name"] = deployment_name |
| 133 | + traffic["traffic"][deployment_name] = traffic["traffic"].pop( |
| 134 | + list(traffic["traffic"].keys())[0] |
| 135 | + ) |
| 136 | + |
| 137 | + temp_file = tempfile.NamedTemporaryFile(mode="w+", suffix=".json", delete=False) |
| 138 | + json.dump(online_endpoint_deployment, temp_file) |
| 139 | + temp_file.flush() |
| 140 | + print(temp_file.name) |
| 141 | + |
| 142 | + |
| 143 | +if __name__ == "__main__": |
| 144 | + |
| 145 | + def parse_args(): |
| 146 | + parser = argparse.ArgumentParser(description="Export v1 service script") |
| 147 | + parser.add_argument( |
| 148 | + "--export", action="store_true", help="using script for export services" |
| 149 | + ) |
| 150 | + parser.add_argument( |
| 151 | + "--overwrite-parameters", |
| 152 | + action="store_true", |
| 153 | + help="using script for overwrite parameters purpose", |
| 154 | + ) |
| 155 | + parser.add_argument("-w", "--workspace", type=str, help="workspace name") |
| 156 | + parser.add_argument( |
| 157 | + "-g", "--resource-group", type=str, help="resource group name" |
| 158 | + ) |
| 159 | + parser.add_argument("-s", "--subscription", type=str, help="subscription id") |
| 160 | + parser.add_argument( |
| 161 | + "-sn", |
| 162 | + "--service-name", |
| 163 | + default=None, |
| 164 | + type=str, |
| 165 | + help="service name to be migrated", |
| 166 | + ) |
| 167 | + parser.add_argument( |
| 168 | + "-e", |
| 169 | + "--export-json", |
| 170 | + action="store_true", |
| 171 | + dest="export_json", |
| 172 | + help="show export result in json", |
| 173 | + ) |
| 174 | + parser.add_argument( |
| 175 | + "-mp", "--parameters-path", type=str, help="parameters file path" |
| 176 | + ) |
| 177 | + parser.add_argument( |
| 178 | + "-me", |
| 179 | + "--migrate-endpoint-name", |
| 180 | + type=str, |
| 181 | + default=None, |
| 182 | + help="v2 online-endpoint name, default is v1 service name", |
| 183 | + ) |
| 184 | + parser.add_argument( |
| 185 | + "-md", |
| 186 | + "--migrate-deployment-name", |
| 187 | + type=str, |
| 188 | + default=None, |
| 189 | + help="v2 online-deployment name, default is v1 service name", |
| 190 | + ) |
| 191 | + parser.set_defaults(compute_type=None) |
| 192 | + return parser.parse_args() |
| 193 | + |
| 194 | + # parse args |
| 195 | + args = parse_args() |
| 196 | + |
| 197 | + if args.export: |
| 198 | + workspace = Workspace.get( |
| 199 | + name=args.workspace, |
| 200 | + resource_group=args.resource_group, |
| 201 | + subscription_id=args.subscription, |
| 202 | + ) |
| 203 | + storage_account, blob_folder, v1_compute = export( |
| 204 | + workspace, args.service_name, show_output=not args.export_json |
| 205 | + ) |
| 206 | + if args.export_json: |
| 207 | + print( |
| 208 | + json.dumps( |
| 209 | + { |
| 210 | + "storage_account": storage_account, |
| 211 | + "blob_folder": blob_folder, |
| 212 | + "v1_compute": v1_compute, |
| 213 | + } |
| 214 | + ) |
| 215 | + ) |
| 216 | + |
| 217 | + if args.overwrite_parameters: |
| 218 | + with open(args.parameters_path) as f: |
| 219 | + online_endpoint_deployment = json.load(f) |
| 220 | + overwrite_parameters( |
| 221 | + online_endpoint_deployment, |
| 222 | + args.migrate_endpoint_name, |
| 223 | + args.migrate_deployment_name, |
| 224 | + ) |
0 commit comments