+ def set_closed_loop_policy(self, policy_template_file):
+ # Gather policy services cluster ips
+ p_api_cluster_ip = self.get_k8s_service_cluster_ip(self.policy_api_service_name)
+ p_pap_cluster_ip = self.get_k8s_service_cluster_ip(self.policy_pap_service_name)
+
+ # Read policy json from file
+ with open(policy_template_file) as f:
+ try:
+ policy_json = json.load(f)
+ except ValueError:
+ self.logger.error(policy_template_file + " doesn't seem to contain valid JSON data")
+ sys.exit(1)
+
+ # Check policy already applied
+ policy_exists_req = requests.get(self.policy_pap_get_url.format(
+ p_pap_cluster_ip), auth=self.policy_userpass,
+ verify=False, headers=self.policy_headers)
+ if policy_exists_req.status_code != 200:
+ self.logger.error('Failure in checking CL policy existence. '
+ 'Policy-pap responded with HTTP code {0}'.format(
+ policy_exists_req.status_code))
+ sys.exit(1)
+
+ try:
+ policy_exists_json = policy_exists_req.json()
+ except ValueError as e:
+ self.logger.error('Policy-pap request failed: ' + e.message)
+ sys.exit(1)
+
+ try:
+ assert policy_exists_json['groups'][0]['pdpSubgroups'] \
+ [1]['policies'][0]['name'] != 'operational.vcpe'
+ except AssertionError:
+ self.logger.info('vCPE closed loop policy already exists, not applying')
+ return
+ except IndexError:
+ pass # policy doesn't exist
+
+ # Create policy
+ policy_create_req = requests.post(self.policy_api_url.format(
+ p_api_cluster_ip), auth=self.policy_userpass,
+ json=policy_json, verify=False,
+ headers=self.policy_headers)
+ # Get the policy id from policy-api response
+ if policy_create_req.status_code != 200:
+ self.logger.error('Failed creating policy. Policy-api responded'
+ ' with HTTP code {0}'.format(policy_create_req.status_code))
+ sys.exit(1)
+
+ try:
+ policy_version = json.loads(policy_create_req.text)['policy-version']
+ except (KeyError, ValueError):
+ self.logger.error('Policy API response not understood:')
+ self.logger.debug('\n' + str(policy_create_req.text))
+
+ # Inject the policy into Policy PAP
+ self.policy_pap_json['policies'].append({'policy-version': policy_version})
+ policy_insert_req = requests.post(self.policy_pap_post_url.format(
+ p_pap_cluster_ip), auth=self.policy_userpass,
+ json=self.policy_pap_json, verify=False,
+ headers=self.policy_headers)
+ if policy_insert_req.status_code != 200:
+ self.logger.error('Policy PAP request failed with HTTP code'
+ '{0}'.format(policy_insert_req.status_code))
+ sys.exit(1)
+ self.logger.info('Successully pushed closed loop Policy')
+