Fix indentation issues as reported by pylint
[demo.git] / tutorials / vFWDT / workflow / workflow.py
index 1ddcde5..dd15e81 100755 (executable)
 '''
 
 import os
-import ssl
 import json
 import sys
 import uuid
 import time
 import copy
-import netifaces as ni
 import warnings
 import contextlib
 import requests
 import simplejson
 import http.server
 import threading
-import urllib3
 from datetime import datetime
 from datetime import timedelta
 from simple_rest_client.api import API
 from simple_rest_client.resource import Resource
 from basicauth import encode
-from pprint import pprint
-from random import randint
 from urllib3.exceptions import InsecureRequestWarning
 
 
@@ -164,7 +159,7 @@ def _get_aai_rel_link_data(data, related_to, search_key=None, match_dict=None):
         m_value = None
     rel_dict = data.get(rel_lst)
     if rel_dict:  # check if data has relationship lists
-        for key, rel_list in rel_dict.items():
+        for key, rel_list in rel_dict.items(): # pylint: disable=W0612
             for rel in rel_list:
                 if rel.get("related-to") == related_to:
                     dval = None
@@ -193,7 +188,7 @@ def _get_aai_rel_link_data(data, related_to, search_key=None, match_dict=None):
                         response.append(
                             {"link": link, "d_value": dval}
                         )
-    if len(response) == 0:
+    if response:
         response.append(
             {"link": None, "d_value": None}
         )
@@ -403,7 +398,7 @@ def _osdf_request(rancher_ip, onap_ip, aai_data, exclude, use_oof_cache):
     #print(json.dumps(template, indent=4))
 
     with _no_ssl_verification():
-        response = api.osdf.placement(body=template, params={}, headers={})
+        response = api.osdf.placement(body=template, params={}, headers={}) # pylint: disable=W0612
         #if response.body.get('error_message') is not None:
         #    raise Exception(response.body['error_message']['explanation'])
 
@@ -510,7 +505,7 @@ def _extract_has_appc_identifiers(has_result, demand, onap_ip):
         v_server['vserver-name'] = v_server['vserver-name'].replace("01", "02")
     hostname_cache.append(v_server['vserver-name'])
 
-    api = _init_python_aai_api(onap_ip)
+    api = _init_python_aai_api(onap_ip) # pylint: disable=W0612
     vnfc_type = demand.lower()
 #    with _no_ssl_verification():
 #        response = api.aai.vnfc(v_server['vserver-name'], body=None, params={}, headers={})
@@ -980,28 +975,189 @@ def _execute_lcm_requests(workflow, onap_ip, check_result):
     lcm_requests = workflow["requests"]
     print("WORKFLOW << {} >>".format(workflow["description"]))
     for i in range(len(lcm_requests)):
-       req = lcm_requests[i]["payload"]
-       #print(json.dumps(req, indent=4))
-       print("APPC LCM << {} >> [{}]".format(req['input']['action'], lcm_requests[i]["description"]))
-       _set_appc_lcm_timestamp(req)
-       conf_result = False
-       result = appc_lcm_request(onap_ip, req)
-       print("Result {}".format(result))
-
-       if result == 100:
-           conf_result = confirm_appc_lcm_action(onap_ip, req, check_result)
-           #time.sleep(30)
-       elif result == 400:
-           conf_result = True
-
-       if not conf_result:
-           if lcm_requests[i]["breakOnFailure"]:
-               raise Exception("APPC LCM << {} >> FAILED".format(req['input']['action']))
-           elif "workflow" in lcm_requests[i]:
-               print("WORKFLOW << {} >> SKIP".format(lcm_requests[i]["workflow"]["description"]))
-       elif "workflow" in lcm_requests[i]:
-           _execute_lcm_requests(lcm_requests[i]["workflow"], onap_ip, check_result)
+        req = lcm_requests[i]["payload"]
+        #print(json.dumps(req, indent=4))
+        print("APPC LCM << {} >> [{}]".format(req['input']['action'], lcm_requests[i]["description"]))
+        _set_appc_lcm_timestamp(req)
+        conf_result = False
+        result = appc_lcm_request(onap_ip, req)
+        print("Result {}".format(result))
+
+        if result == 100:
+            conf_result = confirm_appc_lcm_action(onap_ip, req, check_result)
+            #time.sleep(30)
+        elif result == 400:
+            conf_result = True
+
+        if not conf_result:
+            if lcm_requests[i]["breakOnFailure"]:
+                raise Exception("APPC LCM << {} >> FAILED".format(req['input']['action']))
+            elif "workflow" in lcm_requests[i]:
+                print("WORKFLOW << {} >> SKIP".format(lcm_requests[i]["workflow"]["description"]))
+        elif "workflow" in lcm_requests[i]:
+            _execute_lcm_requests(lcm_requests[i]["workflow"], onap_ip, check_result)
+
+
+def _generate_cdt_artifact_request(req_id, artifact, action, vnfc_type):
+    req = {
+      'input': {
+          'design-request': {
+              'request-id': req_id,
+              'action': "uploadArtifact",
+              'payload': json.dumps(artifact['payload'])
+          }
+       }
+    }
+
+    file = "{}_{}_{}.json".format(artifact['type'], action.lower(), vnfc_type)
+    dirname = "templates/cdt-requests"
+    #print(file)
+    if not os.path.exists(dirname):
+        os.makedirs(dirname)
+    f = open("{}/{}".format(dirname, file), 'w')
+    f.write(json.dumps(req, indent=4))
+    f.close()
+
+    return req
+
+
+def _get_name_of_artifact(prefix, action, vnf_type):
+    return "{}_{}_{}_0.0.1V.json".format(prefix, action, vnf_type)
+
+
+def _set_artifact_payload(vnf_type, vnfc_type, action, artifact):
+    sw_upgrade = False
+    if action == "DistributeTraffic" or action == "DistributeTrafficCheck" or action == "AllAction":
+        pass
+    elif action == "UpgradeSoftware" or action == "UpgradePreCheck" or action == "UpgradePostCheck":
+        sw_upgrade = True
+    else:
+        raise Exception("{} action not supported".format(action))
+
+    artifact_contents = ''
+    if artifact['type'] == 'config_template':
+        file = 'templates/cdt-templates/templates/action-template.json'
+        template_file = 'templates/cdt-templates/{}/{}'
+        if sw_upgrade:
+            template_file = template_file.format(vnfc_type, 'upgrade.json')
+        else:
+            template_file = template_file.format(vnfc_type, 'traffic.json')
+
+        artifact_contents = json.dumps(json.loads(open(template_file).read()))
+    elif artifact['type'] == 'parameter_definitions':
+        file = 'templates/cdt-templates/templates/{}'
+        if sw_upgrade:
+            file = file.format('upgrade-params.json')
+        else:
+            file = file.format('traffic-params.json')
+    elif artifact['type'] == 'param_values':
+        file = 'templates/cdt-templates/templates/{}'
+        if sw_upgrade:
+            file = file.format('upgrade-params-list.json')
+        else:
+            file = file.format('traffic-params-list.json')
+    elif artifact['type'] == 'reference_template':
+        file = 'templates/cdt-templates/templates/reference-all-actions.json'
+    else:
+        raise Exception("{} not supported artifact type".format(artifact['type']))
+
+    payload = json.loads(open(file).read())
+    payload['vnf-type'] = vnf_type
+    payload['artifact-name'] = artifact['name']
+    payload['action'] = action
+
+    if artifact['type'] == 'config_template':
+        artifact['artifact-contents'] = artifact_contents
+    artifact['payload'] = payload
+
+
+def _generate_artifacts_for_cdt(vnf_type, vnf_type_formatted, vnfc_type, action):
+    artifacts = []
+    artifacts.append({
+        'name': _get_name_of_artifact("template", action, vnf_type_formatted),
+        'type': 'config_template',
+        'payload': {'test': 'test'}
+    })
+    artifacts.append({
+        'name': _get_name_of_artifact("pd", action, vnf_type_formatted),
+        'type': 'parameter_definitions',
+        'payload': {'test': 'test'}
+    })
+    artifacts.append({
+        'name': _get_name_of_artifact("param", action, vnf_type_formatted),
+        'type': 'param_values',
+        'payload': {'test': 'test'}
+    })
+
+    _set_artifact_payload(vnf_type, vnfc_type, action, artifacts[0])
+    _set_artifact_payload(vnf_type, vnfc_type, action, artifacts[1])
+    _set_artifact_payload(vnf_type, vnfc_type, action, artifacts[2])
+
+    return artifacts
+
+
+def _generate_cdt_payloads_for_vnf(vnf_info, vnfc_type, actions):
+    req_id = str(uuid.uuid4()).replace('-','')
+    vnf_type_formatted = vnf_info['vnf-type'].replace(' ','').replace('/', '_')
+    artifacts = {
+        'AllAction': [{
+            'name': _get_name_of_artifact("reference", 'AllAction', vnf_type_formatted),
+            'type': 'reference_template'
+        }]
+    }
+
+    all_action_artifact = artifacts['AllAction'][0]
+
+    _set_artifact_payload(vnf_info['vnf-type'], vnfc_type, 'AllAction', all_action_artifact)
+
+    for action in actions:
+        action_artifacts = _generate_artifacts_for_cdt(vnf_info['vnf-type'], vnf_type_formatted, vnfc_type, action)
+        artifacts[action] = action_artifacts
 
+    all_action_artifacts = list()
+
+    for action in artifacts:
+        artifact_list = list()
+        action_info = {
+            'action': action,
+            'action-level': "vnf",
+            'scope': {
+                 'vnf-type': vnf_info['vnf-type'],
+                 'vnfc-type-list': [],
+                 'vnfc-type': ""
+            },
+            'artifact-list': artifact_list
+        }
+
+        if action != 'AllAction':
+            action_info.update({
+                'template': "Y",
+                'vm': [],
+                'device-protocol': "ANSIBLE",
+                'user-name': "admin",
+                'port-number': "8000",
+                'scopeType': "vnf-type"
+            })
+
+        for action_artifact in artifacts[action]:
+            artifact_list.append({'artifact-name': action_artifact['name'], 'artifact-type': action_artifact['type']})
+            if action != 'AllAction':
+                req = _generate_cdt_artifact_request(req_id, action_artifact, action, vnfc_type) # pylint: disable=W0612
+                #print(json.dumps(req, indent=4))
+
+        #print(json.dumps(action_info, indent=4))
+        all_action_artifacts.append(action_info)
+
+    all_action_artifact['payload']['artifact-contents'] = json.dumps({'reference_data': all_action_artifacts})
+    req = _generate_cdt_artifact_request(req_id, all_action_artifact, 'AllAction', vnfc_type)
+    #print(json.dumps(req, indent=4))
+
+
+def _generate_cdt_payloads(aai_data):
+    vfw_actions = ["DistributeTrafficCheck", "UpgradeSoftware", "UpgradePreCheck", "UpgradePostCheck", "UpgradeSoftware"]
+    vpgn_actions = ["DistributeTraffic", "DistributeTrafficCheck"]
+    _generate_cdt_payloads_for_vnf(aai_data["vfw-model-info"], "vfw-sink", vfw_actions)
+    _generate_cdt_payloads_for_vnf(aai_data["vpgn-model-info"], "vpgn", vpgn_actions)
 
 
 def execute_workflow(vfw_vnf_id, rancher_ip, onap_ip, use_oof_cache, if_close_loop_vfw, info_only, check_result, new_version=None):
@@ -1030,6 +1186,8 @@ def execute_workflow(vfw_vnf_id, rancher_ip, onap_ip, use_oof_cache, if_close_lo
     f.write(inventory)
     f.close()
 
+    _generate_cdt_payloads(aai_data)
+
     if info_only:
         return
     print("\nDistribute Traffic Workflow Execution:")