API Doc: Add examples
[policy/engine.git] / docs / platform / offeredapis.rst
1 .. This work is licensed under a Creative Commons Attribution 4.0 International License.
2 .. http://creativecommons.org/licenses/by/4.0
3
4
5 Offered APIs
6 ============
7
8 .. contents:: 
9     :depth: 2
10
11 The Policy subsystem of ONAP maintains, distributes, and operates on the set of rules that underlie ONAP’s control, orchestration, and management functions. Policy provides a centralized environment for the creation and management of easily-updatable conditional rules. It enables users to validate policies and rules, identify and resolve overlaps and conflicts, and derive additional policies where needed.  The following operations are supported by the policy API:
12
13 * Create policies on the PAP 
14 * Update policies on the PAP
15 * Delete policies on the PAP or PDP
16 * Push policies from the PAP to the PDP
17 * List policies on the PDP
18 * Get config data of policies on the PDP
19 * Create Dictionary Items
20 * Update Dictionary Items
21 * Retrieve Dictionary Items
22 * Import Micro Services Models
23 * Retrieve Metrics for policy counts from PDP and PAP
24
25
26 POLICY Engine Services
27 ^^^^^^^^^^^^^^^^^^^^^^
28
29 .. image:: PolicyEngineApiList.png
30
31 POLICY API Details
32 ^^^^^^^^^^^^^^^^^^
33
34 .. swaggerv2doc:: api-docs.json
35
36 Examples
37 ^^^^^^^^
38
39 **SAMPLE JAVA CLIENT CODE**
40
41     .. code-block:: java
42        :caption: Get Config Example
43        :linenos:
44
45         package org.onap.policyEngine;
46           
47         import java.util.Collection;
48           
49         import org.onap.policy.api.ConfigRequestParameters;
50         import org.onap.policy.api.PolicyConfig;
51         import org.onap.policy.api.PolicyEngine;
52           
53         public class GetConfigSample {
54           
55             public static void main(String[] args) throws Exception {
56                 PolicyEngine pe = new PolicyEngine("config.properties");
57                 ConfigRequestParameters configRequestParams = new ConfigRequestParameters();
58                 configRequestParams.setPolicyName(".*");
59                 Collection<PolicyConfig> configs = pe.getConfig(configRequestParams);
60                 for (PolicyConfig config: configs){
61                     System.out.println(config.getPolicyConfigMessage());
62                     System.out.println(config.getPolicyConfigStatus());
63                 }
64             }
65         }
66
67
68     .. code-block:: java
69        :caption: Create Config FIrewall Policy Example
70        :linenos:
71
72         package org.onap.policyEngine;
73           
74         import java.io.File;
75         import java.io.FileInputStream;
76         import java.io.FileNotFoundException;
77         import java.io.IOException;
78         import java.io.InputStream;
79         import java.io.StringReader;
80         import java.nio.file.Path;
81         import java.nio.file.Paths;
82         import java.text.SimpleDateFormat;
83         import java.util.Date;
84         import java.util.UUID;
85           
86         import javax.json.Json;
87         import javax.json.JsonObject;
88         import javax.json.JsonReader;
89           
90         import org.onap.policy.api.PolicyChangeResponse;
91         import org.onap.policy.api.PolicyConfigType;
92         import org.onap.policy.api.PolicyEngine;
93         import org.onap.policy.api.PolicyParameters;
94         import org.onap.policy.api.PolicyType;
95           
96         public class ConfigFirewallPolicyClient {
97             static Boolean isEdit = false;
98             public static void main(String[] args) {
99                 try{    
100                     PolicyEngine policyEngine = new PolicyEngine("config.properties");
101                     PolicyParameters policyParameters = new PolicyParameters();
102                     // Set Policy Type
103                     policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); //required
104                     policyParameters.setPolicyName("MikeAPItesting.testConfigFirewallPolicy1607_1"); //required
105                     //policyParameters.setPolicyScope("MikeAPItesting");
106                     //Directory will be created where the Policies are saved... this displays a subscope on the GUI
107                     policyParameters.setRequestID(UUID.randomUUID());
108                       
109                     // Set Safe Policy value for Risk Type
110                     SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
111                     Date date = dateformat3.parse("15/10/2016");
112                     policyParameters.setTtlDate(date);
113                     // Set Safe Policy value for Guard
114                     policyParameters.setGuard(true);
115                     // Set Safe Policy value for Risk Level
116                     policyParameters.setRiskLevel("5");
117                     // Set Safe Policy value for Risk Type
118                     policyParameters.setRiskType("PROD");
119                     File jsonFile = null;
120                     String jsonRuleList = null;
121                     Path file = Paths.get("C:\\policyAPI\\firewallRulesJSON\\Config_FW_Sample.json");
122                     jsonFile = file.toFile();
123                       
124                     //buildJSON(jsonFile, jsonRuleList);
125                     policyParameters.setConfigBody(buildJSON(jsonFile, jsonRuleList).toString());       
126                     policyParameters.setConfigBodyType(PolicyType.JSON);
127                     // API method to create Policy or update policy
128                     PolicyChangeResponse response = null;
129                     if (!isEdit) {
130                         response = policyEngine.createPolicy(policyParameters);
131                     } else {
132                         response = policyEngine.updatePolicy(policyParameters);
133                     }
134                       
135                     if(response.getResponseCode()==200){
136                         System.out.println(response.getResponseMessage());
137                         System.out.println("Policy Created Successfully!");
138                     }else{
139                         System.out.println("Error! " + response.getResponseMessage());
140                     }
141                 } catch (Exception e) {
142                     System.err.println(e.getMessage());
143                 }
144                   
145         }
146               
147             private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
148                 JsonObject json = null;
149                 JsonReader jsonReader = null;
150                 if (jsonString != null && jsonInput == null) {
151                     StringReader in = null;
152                     in = new StringReader(jsonString);
153                     jsonReader = Json.createReader(in);
154                     json = jsonReader.readObject();
155                     in.close();
156                 } else {
157                     InputStream in = null;
158                     in = new FileInputStream(jsonInput); 
159                     jsonReader = Json.createReader(in);
160                     json = jsonReader.readObject();
161                     try {
162                         in.close();
163                     } catch (IOException e) {
164                         System.err.println("Exception Occured while closing input stream"+e);
165                     }
166                 }
167                 jsonReader.close();
168                 return json;
169             }
170           
171         }
172
173     .. code-block:: java
174        :caption: Sample JSON file - Config_FW_Sample.json
175        :linenos:
176
177         {
178               "serviceTypeId": "/v0/firewall/pan",
179               "configName": "AFTTFwPolicy1Config",
180               "deploymentOption": {
181                     "deployNow": false
182               },
183               "securityZoneId": "cloudsite:dev1a",
184               "serviceGroups": [{
185                     "name": "SSH",
186                     "description": "Ssh service entry in service list",
187                     "type": "SERVICE",
188                     "transportProtocol": "tcp",
189                     "appProtocol": null,
190                     "ports": "22"
191               }],
192               "addressGroups": [{
193                     "name": "CiscoVCE",
194                     "description": "Destination CiscoCVE",
195                     "members": [{
196                           "type": "SUBNET",
197                           "value": "12.63.31.61/12"
198                     }]
199               }, {
200                     "name": "HOHOServers",
201                     "description": "Source HOHOServers for first testing",
202                     "members": [{
203                           "type": "SUBNET",
204                           "value": "12.60.32.11/23"
205                     }]
206               }],
207               "firewallRuleList": [{
208                     "position": "1",
209                     "ruleName": "FWRuleHOHOServerToCiscoVCE",
210                     "fromZones": ["UntrustedZoneCiscoCVEName"],
211                     "toZones": ["TrustedZoneHOHOName"],
212                     "negateSource": false,
213                     "negateDestination": false,
214                     "sourceList": [{
215                           "type": "REFERENCE",
216                           "name": "HOHOServers"
217                     }],
218                     "destinationList": [{
219                           "type": "REFERENCE",
220                           "name": "CiscoVCE"
221                     }],
222                     "sourceServices": [],
223                     "destServices": [{
224                           "type": "REFERENCE",
225                           "name": "SSH"
226                     }],
227                     "action": "accept",
228                     "description": "FW rule for HOHO source to CiscoVCE destination",
229                     "enabled": true,
230                     "log": true
231               }]
232         }
233
234     .. code-block:: java
235        :caption: Delete Policy Example
236        :linenos:
237
238         package org.onap.policyEngine;
239           
240         import org.onap.policy.api.DeletePolicyCondition;
241         import org.onap.policy.api.DeletePolicyParameters;
242         import org.onap.policy.api.PolicyChangeResponse;
243         import org.onap.policy.api.PolicyEngine;
244           
245         public class DeletePolicyClient {
246           
247             public static void main(String[] args) {
248                 try {
249           
250                     PolicyEngine policyEngine = new PolicyEngine("config.properties");
251                     DeletePolicyParameters policyParameters = new DeletePolicyParameters();         
252                                   
253                     //Parameter arguments
254                     policyParameters.setPolicyName("MikeConsole.Config_testDeleteAPI6.1.xml");
255                     policyParameters.setPolicyComponent("PDP");
256                     policyParameters.setPdpGroup("default");
257                     policyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
258                     policyParameters.setRequestID(null);
259                       
260                     // API method to Push Policy to PDP
261                     PolicyChangeResponse response = null;
262                     response = policyEngine.deletePolicy(policyParameters);
263           
264                     if(response.getResponseCode()==200){
265                         System.out.println(response.getResponseMessage());
266                         System.out.println("Policy Deleted Successfully!");
267                     }else{
268                         System.out.println("Error! " + response.getResponseMessage());
269                     }
270           
271                 } catch (Exception e) {
272                     System.err.println(e.getMessage());     
273                       
274                 }
275             }
276         }
277
278
279     .. code-block:: java
280        :caption: Push Policy Example
281        :linenos:
282
283         package org.onap.policyEngine;
284           
285         import org.onap.policy.api.PolicyChangeResponse;
286         import org.onap.policy.api.PolicyEngine;
287         import org.onap.policy.api.PushPolicyParameters;
288           
289         public class PushPoliciesToPDP {
290             public static void main(String[] args) {
291                 try {
292           
293                     PolicyEngine policyEngine = new PolicyEngine("config.properties");
294                     PushPolicyParameters policyParameters = new PushPolicyParameters();         
295                                   
296                     //Parameter arguments
297                     policyParameters.setPolicyName("Mike.testCase1");
298                     policyParameters.setPolicyType("Base");
299                     //policyParameters.setPolicyScope("MikeAPItesting");
300                     policyParameters.setPdpGroup("default");            
301                     policyParameters.setRequestID(null);
302                       
303                     // API method to Push Policy to PDP
304                     PolicyChangeResponse response = null;
305                     response = policyEngine.pushPolicy(policyParameters);
306           
307                     if(response.getResponseCode()==204){
308                         System.out.println(response.getResponseMessage());
309                         System.out.println("Policy Pushed Successfully!");
310                     }else{
311                         System.out.println("Error! " + response.getResponseMessage());
312                     }
313           
314                 } catch (Exception e) {
315                     System.err.println(e.getMessage());     
316                       
317                 }
318             }
319         }
320
321
322     .. code-block:: java
323        :caption: Decision Policy Example
324        :linenos:
325
326         package org.onap.policyEngine;
327           
328         import java.util.Arrays;
329         import java.util.HashMap;
330         import java.util.LinkedList;
331         import java.util.List;
332         import java.util.Map;
333         import java.util.UUID;
334           
335         import org.onap.policy.api.AttributeType;
336         import org.onap.policy.api.PolicyChangeResponse;
337         import org.onap.policy.api.PolicyClass;
338         import org.onap.policy.api.PolicyEngine;
339         import org.onap.policy.api.PolicyParameters;
340           
341         public class DecisionPolicyClient {
342             static Boolean isEdit = true;
343             public static void main(String[] args) {
344                 try {
345                     PolicyEngine policyEngine = new PolicyEngine("config.properties");
346                     PolicyParameters policyParameters = new PolicyParameters();
347                     // Set Policy Type
348                     policyParameters.setPolicyClass(PolicyClass.Decision); //required
349                     policyParameters.setPolicyName("MikeAPItests.testDecisionAPI"); //required
350                     policyParameters.setOnapName("java"); //required
351                     policyParameters.setPolicyDescription("This is a sample Decision policy UPDATE example with Settings");  //optional
352                     //policyParameters.setPolicyScope("MikeAPItests");
353          //Directory will be created where the Policies are saved... this 
354         displays a a subscope on the GUI
355                       
356                     //Set the Component Attributes... These are Optional
357                     Map<String, String> configAttributes = new HashMap<>(); 
358                     configAttributes.put("Template", "UpdateTemplate");
359                     configAttributes.put("controller", "default"); 
360                     configAttributes.put("SamPoll", "30");
361                     configAttributes.put("value", "abcd"); 
362                       
363                     Map<AttributeType, Map<String,String>> attributes = new HashMap<>();
364                     attributes.put(AttributeType.MATCHING, configAttributes);
365                       
366                     //Set the settings... These are Optional
367                     Map<String, String> settingsMap = new HashMap<>();
368                     settingsMap.put("server", "5");
369                       
370                     attributes.put(AttributeType.SETTINGS, settingsMap);
371                     policyParameters.setAttributes(attributes);
372           
373                       
374                     List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
375                     List<String> dynamicRuleAlgorithmFunctions = new LinkedList<>();
376                     List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
377                     List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
378                       
379                     //Example of a complex Rule algorithm using the settings in the Field1
380                     /* label    field1      function                field2
381                      * *****************************************************
382                      * A1       S_server    integer-equal               90
383                      * A2       cap         string-contains             ca
384                      * A3       cobal       integer-equal               90  
385                      * A4       A2          and                         A3
386                      * A5       Config      integer-greater-than        45
387                      * A6       A4  `       or                          A5
388                      * A7       A1          and                         A6
389                      */
390                     dynamicRuleAlgorithmLabels = Arrays.asList("A1","A2","A3","A4","A5","A6","A7");
391                     dynamicRuleAlgorithmField1 = Arrays.asList("S_server","cap","cobal","A2","Config","A4","A1");
392                     dynamicRuleAlgorithmFunctions = Arrays.asList("integer-equal","string-contains","integer-equal","and","integer-greater-than","or","and");
393                     dynamicRuleAlgorithmField2 = Arrays.asList("90","ca","90","A3","45","A5","A6");
394                               
395                     policyParameters.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
396                     policyParameters.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
397                     policyParameters.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions);
398                     policyParameters.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
399                       
400                     policyParameters.setRequestID(UUID.randomUUID());
401                       
402                     // API method to create Policy or update policy
403                     PolicyChangeResponse response = null;
404                     if (!isEdit) {
405                         response = policyEngine.createPolicy(policyParameters);
406                     } else {
407                         response = policyEngine.updatePolicy(policyParameters);
408                     }
409                       
410                     if(response.getResponseCode()==200){
411                         System.out.println(response.getResponseMessage());
412                         System.out.println("Policy Created Successfully!");
413                     }else{
414                         System.out.println("Error! " + response.getResponseMessage());
415                     }
416                 } catch (Exception e) {
417                     System.err.println(e.getMessage());
418                 }
419             }
420         }
421
422
423     .. code-block:: java
424        :caption: List Config Policy Example
425        :linenos:
426
427         package org.onap.policyEngine;
428           
429         import java.util.Collection;
430         import java.util.HashMap;
431         import java.util.Map;
432         import java.util.UUID;
433           
434         import org.onap.policy.api.ConfigRequestParameters;
435         import org.onap.policy.api.PolicyConfigException;
436         import org.onap.policy.api.PolicyEngine;
437         import org.onap.policy.api.PolicyEngineException;
438         import org.onap.policy.common.logging.flexlogger.FlexLogger;
439         import org.onap.policy.common.logging.flexlogger.Logger;
440           
441         public class ListConfigPoliciesClient {
442               
443             private static final Logger LOGGER  = FlexLogger.getLogger(ListConfigPoliciesClient.class);
444               
445             public static void main(String[] args) {
446                 PolicyEngine policyEngine;
447           
448                 // List Config Policies Example 
449                 try {
450                     policyEngine = new PolicyEngine("config.properties");
451                     ConfigRequestParameters parameters = new ConfigRequestParameters();
452                       
453                     parameters.setPolicyName(".*");
454                     parameters.setOnapName(".*");
455                     parameters.setConfigName(".*");
456                       
457                     Map<String, String> configAttributes = new HashMap<>();
458                     configAttributes.put("java", "java");
459                     configAttributes.put("peach", "Tar");
460                     configAttributes.put("true", "false");
461                     configAttributes.put("small", "testPass");
462                     parameters.setConfigAttributes(configAttributes);
463                       
464                     parameters.setRequestID(UUID.randomUUID());
465                       
466                     Collection<String> response = policyEngine.listConfig(parameters);
467                     if(response!=null && !response.contains("PE300")){
468                         for(String configList : response){
469                             System.out.println(configList.toString()+"\n");
470                         }
471                     }else{
472                         System.out.println("Error! " +response);
473                     }
474           
475                 } catch (PolicyConfigException e) {
476                     LOGGER.error("Exception Occured"+e);
477                 } catch (PolicyEngineException e) {
478                     LOGGER.error("Exception Occured"+e);
479                 }
480             }
481         }
482
483
484 **JSON EXAMPLES**
485
486     .. code-block:: java
487        :caption: Create Microservice Policy
488        :linenos:
489
490         API: createPolicy  
491         OPERATION: PUT
492         REQUEST BODY:
493         {
494             "configBody": "{
495                     \"service\":\"ControllerServiceSampleSdnlServiceInstance\",
496                     \"location\":\"Edge\",
497                     \"uuid\":\"TestUUID\",
498                     \"policyName\":\"testRestCreateMicroServicesNewParams\",
499                     \"description\":\"testing Create\",
500                     \"configName\":\"TestName\",
501                     \"templateVersion\":\"1604\",
502                     \"priority\":\"4\",
503                     \"version\":\"0.1.0-SNAPSHOT\",
504                     \"policyScope\":\"resource=F5,service=vSCP,type=configuration,closedLoopControlName=vSCP_F5_Firewall_d925ed73-8231-4d02-9545-db4e101f88f8\",
505                     \"content\":{
506                             \"taskOrchestratedConfiguration\":\"test\",
507                             \"taskCustomConfiguration\":\"set\",
508                             \"configuration\":\"test\",
509                             \"cdapUrl\":\"testurl\",
510                             \"taskName\":\"test\",
511                             \"taskNameTEST\":\"TEST\",
512                             \"users\":\"[tuser]\",
513                             \"adminUsers\":\"[lji]\",
514                             \"taskConfigFilePath\":\"test\",
515                             \"managerPortNumber\":\"999\",
516                             \"taskType\":\"test\",
517                             \"taskCommandFilePath\":\"tset\",
518                             \"contailIp\":\"test\",
519                             \"consoleUsers\":\"[odu-e2e]\",
520                             \"taskStatusFilePath\":\"test\"
521                     }
522             }",
523             "policyConfigType": "MicroService",
524             "policyName": "MikeAPITesting.testRestCreateMicroServicesNewParams",
525             "ecompName": "SDNC"
526         }
527
528
529     .. code-block:: java
530        :caption: Update Microservice Policy
531        :linenos:
532
533         API: updatePolicy  
534         OPERATION: PUT
535         REQUEST BODY:
536         {
537             "configBody": "{
538                     \"service\":\"ControllerServiceSampleSdnlServiceInstance\",
539                     \"location\":\"Edge\",
540                     \"uuid\":\"TestUUID\",
541                     \"policyName\":\"testRestCreateMicroServicesNewParams\",
542                     \"description\":\"testing Update\",
543                     \"configName\":\"TestName\",
544                     \"templateVersion\":\"1604\",
545                     \"priority\":\"4\",
546                     \"version\":\"0.1.0-SNAPSHOT\",
547                     \"policyScope\":\"resource=F5,service=vSCP,type=configuration,closedLoopControlName=vSCP_F5_Firewall_d925ed73-8231-4d02-9545-db4e101f88f8\",
548                     \"content\":{
549                             \"taskOrchestratedConfiguration\":\"test\",
550                             \"taskCustomConfiguration\":\"set\",
551                             \"configuration\":\"test\",
552                             \"cdapUrl\":\"testurl\",
553                             \"taskName\":\"test\",
554                             \"taskNameTEST\":\"TEST\",
555                             \"users\":\"[tuser]\",
556                             \"adminUsers\":\"[lji]\",
557                             \"taskConfigFilePath\":\"test\",
558                             \"managerPortNumber\":\"999\",
559                             \"taskType\":\"test\",
560                             \"taskCommandFilePath\":\"tset\",
561                             \"contailIp\":\"test\",
562                             \"consoleUsers\":\"[odu-e2e]\",
563                             \"taskStatusFilePath\":\"test\"
564                     }
565             }",
566             "policyConfigType": "MicroService",
567             "policyName": "MikeAPITesting.testRestUpdateMicroServicesNewParams",
568             "ecompName": "SDNC"
569         }
570
571
572 **CURL EXAMPLES**
573
574     .. code-block:: bash
575        :caption: Push Policy
576
577         echo "pushPolicy : PUT : com.vLoadBalancer"
578         echo "pushPolicy : PUT : com.vLoadBalancer"
579         curl -v --silent -X PUT --header 'Content-Type: application/json' --header 'Accept: text/plain' --header 'ClientAuth: XYZ' --header 'Authorization: Basic XYZ' --header 'Environment: TEST' -d '{
580           "pdpGroup": "default",
581           "policyName": "com.vLoadBalancer",
582           "policyType": "MicroService"
583         }' 'http://pdp:8081/pdp/api/pushPolicy'
584
585
586     .. code-block:: bash
587        :caption: Delete Policy
588
589         echo "deletePolicy : DELETE : com.vFirewall"
590         curl -v --silent -X DELETE --header 'Content-Type: application/json' --header 'Accept: text/plain' --header 'ClientAuth: XYZ' --header 'Authorization: Basic XYZ' --header 'Environment: TEST' -d '{
591           "pdpGroup": "default",
592           "policyComponent": "PDP",
593           "policyName": "com.vFirewall",
594           "policyType": "MicroService"
595         }' 'http://pdp:8081/pdp/api/deletePolicy'
596
597
598     .. code-block:: bash
599        :caption: Get Config 
600
601         echo "Get all Config Policy example"
602         curl -i -v -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'ClientAuth: XYZ' -H 'Authorization: Basic XYZ -H 'Environment: TEST' -X POST -d '{
603         "policyName": ".*"
604         }' http://${PDP_IP}:8081/pdp/api/getConfig
605
606
607 **ADDITIONAL EXAMPLES**
608
609     .. code-block:: bash
610        :caption: Deleting a Policy from PAP
611
612         // Deleting from PAP will remove the policy from the PolicyEntity & PolicyVersion tables (UI-Editor tab).
613         // This means that the policy is no longer be available in Policy System.
614          
615         // PayLoad:
616         {    "policyName": "com.testpolicy",    //scope.policyName   
617              "policyType": "Base",              //policy type   
618              "policyComponent": "PAP",          //component name   
619              "deleteCondition": "ALL"           //versions (ALL or CURRENT)
620         }
621
622
623     .. code-block:: bash
624        :caption: Deleting a Policy from PDP
625
626         // Deleting from PDP will delete the policy from the PDP Group.  The policy is still available in Policy System. 
627         // When the policy is needed again, the policy should be pushed to the PDP.
628          
629         // PayLoad:
630         {    "policyName": "com.testpolicy",   //scope.policyName   
631              "policyType": "Base",             //policy type   
632              "policyComponent": "PDP",         //component name   
633              "pdpGroup": "Default"             //group name
634         }
635
636
637 Additional Information
638 ^^^^^^^^^^^^^^^^^^^^^^
639
640 Additional information, including examples, can be found at `PolicyApi link`_.
641
642 .. _PolicyApi link: https://wiki.onap.org/display/DW/Policy+API
643
644
645
646
647
648 End of Document
649