Merge "Add support for AAI Named Query error handling"
[policy/drools-applications.git] / controlloop / common / eventmanager / src / main / java / org / onap / policy / controlloop / eventmanager / ControlLoopOperationManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * controlloop operation manager
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.eventmanager;
22
23 import java.io.Serializable;
24 import java.sql.Timestamp;
25 import java.time.Instant;
26 import java.util.AbstractMap;
27 import java.util.LinkedList;
28 import java.util.Properties;
29
30 import javax.persistence.EntityManager;
31 import javax.persistence.Persistence;
32
33 import org.onap.policy.aai.util.AAIException;
34 import org.onap.policy.appc.Response;
35 import org.onap.policy.appc.ResponseCode;
36 import org.onap.policy.appclcm.LCMResponseWrapper;
37 import org.onap.policy.controlloop.ControlLoopEvent;
38 import org.onap.policy.controlloop.ControlLoopException;
39 import org.onap.policy.controlloop.ControlLoopOperation;
40 import org.onap.policy.controlloop.VirtualControlLoopEvent;
41 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
42 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
43 import org.onap.policy.controlloop.actor.so.SOActorServiceProvider;
44 import org.onap.policy.controlloop.actor.vfc.VFCActorServiceProvider;
45 import org.onap.policy.controlloop.policy.Policy;
46 import org.onap.policy.controlloop.policy.PolicyResult;
47 import org.onap.policy.drools.system.PolicyEngine;
48 import org.onap.policy.guard.Util;
49 import org.onap.policy.so.SOResponse;
50 import org.onap.policy.vfc.VFCResponse;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class ControlLoopOperationManager implements Serializable {
55
56         /**
57          *
58          */
59         private static final long serialVersionUID = -3773199283624595410L;
60         private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
61
62         @Override
63         public String toString() {
64                 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
65                                 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
66                                 + ", policyResult=" + policyResult
67                                 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
68                                 + "]";
69         }
70
71         //
72         // These properties are not changeable, but accessible
73         // for Drools Rule statements.
74         //
75         //public final ATTControlLoopEvent onset;
76         public final ControlLoopEvent onset;
77         public final transient Policy policy;
78
79         //
80         // Properties used to track the Operation
81         //
82         private int attempts = 0;
83         private transient Operation currentOperation = null;
84         private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
85         private PolicyResult policyResult = null;
86         private ControlLoopEventManager eventManager = null;
87
88         public ControlLoopEventManager getEventManager() {
89                 return eventManager;
90         }
91
92         public void setEventManager(ControlLoopEventManager eventManager) {
93                 this.eventManager = eventManager;
94         }
95
96
97         //
98         // Internal class used for tracking
99         //
100         private class Operation {
101                 public ControlLoopOperation operation = new ControlLoopOperation();
102                 public PolicyResult policyResult = null;
103                 public int attempt = 0;
104
105                 @Override
106                 public String toString() {
107                         return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
108                                         + "]";
109                 }
110         }
111
112         private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
113         private transient Object operationRequest;
114
115         public Object getOperationRequest() {
116                 return operationRequest;
117         }
118
119         public String getGuardApprovalStatus() {
120                 return guardApprovalStatus;
121         }
122         public void setGuardApprovalStatus(String guardApprovalStatus) {
123                 this.guardApprovalStatus = guardApprovalStatus;
124         }
125
126
127         public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
128                 this.onset = onset;
129                 this.policy = policy;
130                 this.guardApprovalStatus = "NONE";
131                 this.eventManager = em;
132
133                 //
134                 // Let's make a sanity check
135                 //
136                 switch (policy.getActor()) {
137                 case "APPC":
138                         break;
139                 case "SO":
140                         break;
141                 case "VFC":
142                         break;
143                 default:
144                         throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
145                 }
146         }
147
148         public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) throws AAIException {
149                 //
150                 // They shouldn't call us if we currently running something
151                 //
152                 if (this.currentOperation != null) {
153                         //
154                         // what do we do if we are already running an operation?
155                         //
156                         return null;
157                 }
158                 //
159                 // Check if we have maxed out on retries
160                 //
161                 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
162                         //
163                         // No retries are allowed, so check have we even made
164                         // one attempt to execute the operation?
165                         //
166                         if (this.attempts >= 1) {
167                                 //
168                                 // We have, let's ensure our PolicyResult is set
169                                 //
170                                 if (this.policyResult == null) {
171                                         this.policyResult = PolicyResult.FAILURE_RETRIES;
172                                 }
173                                 //
174                                 //
175                                 //
176                                 return null;
177                         }
178                 } else {
179                         //
180                         // Have we maxed out on retries?
181                         //
182                         if (this.attempts > this.policy.getRetry()) {
183                                 if (this.policyResult == null) {
184                                         this.policyResult = PolicyResult.FAILURE_RETRIES;
185                                 }
186                                 return null;
187                         }
188                 }
189                 //
190                 // Setup
191                 //
192                 this.policyResult = null;
193                 Operation operation = new Operation();
194                 operation.attempt = ++this.attempts;
195                 operation.operation.actor = this.policy.getActor();
196                 operation.operation.operation = this.policy.getRecipe();
197                 operation.operation.target = this.policy.getTarget().toString();
198                 operation.operation.subRequestId = Integer.toString(operation.attempt);
199                 //
200                 // Now determine which actor we need to construct a request for
201                 //
202                 switch (policy.getActor()) {
203                 case "APPC":
204                     /*
205                      * If the recipe is ModifyConfig, a legacy APPC
206                      * request is constructed. Otherwise an LCMRequest
207                      * is constructed.
208                      */
209                         this.currentOperation = operation;
210                     if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
211
212                     this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
213                     }
214                     else {
215                         this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
216                     }
217                         //
218                         // Save the operation
219                         //
220                         
221                         return operationRequest;
222                 case "SO":
223                         SOActorServiceProvider SOAsp = new SOActorServiceProvider();
224                         this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
225
226                         // Save the operation
227                         this.currentOperation = operation;
228
229                         if (this.operationRequest == null) {
230                                 this.policyResult = PolicyResult.FAILURE;
231                         }
232
233                         return operationRequest;
234                 case "VFC":
235                         this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse());
236                         this.currentOperation = operation;
237                         return operationRequest;
238
239                 }
240                 return null;
241         }
242
243         public PolicyResult     onResponse(Object response) {
244                 //
245                 // Which response is it?
246                 //
247                 if (response instanceof Response) {
248                         //
249                         // Cast it
250                         //
251                         Response appcResponse = (Response) response;
252                         //
253                         // Determine which subrequestID (ie. attempt)
254                         //
255                         Integer operationAttempt = null;
256                         try {
257                                 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
258                         } catch (NumberFormatException e) {
259                                 //
260                                 // We cannot tell what happened if this doesn't exist
261                                 //
262                                 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
263                                 return PolicyResult.FAILURE_EXCEPTION;
264                         }
265                         //
266                         // Sanity check the response message
267                         //
268                         if (appcResponse.Status == null) {
269                                 //
270                                 // We cannot tell what happened if this doesn't exist
271                                 //
272                                 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
273                                 return PolicyResult.FAILURE_EXCEPTION;
274                         }
275                         //
276                         // Get the Response Code
277                         //
278                         ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
279                         if (code == null) {
280                                 //
281                                 // We are unaware of this code
282                                 //
283                                 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
284                                 return PolicyResult.FAILURE_EXCEPTION;
285                         }
286                         //
287                         // Ok, let's figure out what APP-C's response is
288                         //
289                         switch (code) {
290                         case ACCEPT:
291                                 //
292                                 // This is good, they got our original message and
293                                 // acknowledged it.
294                                 //
295                                 // Is there any need to track this?
296                                 //
297                                 return null;
298                         case ERROR:
299                         case REJECT:
300                                 //
301                                 // We'll consider these two codes as exceptions
302                                 //
303                                 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
304                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
305                                         return null;
306                                 }
307                                 return PolicyResult.FAILURE_EXCEPTION;
308                         case SUCCESS:
309                                 //
310                                 //
311                                 //
312                                 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
313                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
314                                         return null;
315                                 }
316                                 return PolicyResult.SUCCESS;
317                         case FAILURE:
318                                 //
319                                 //
320                                 //
321                                 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
322                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
323                                         return null;
324                                 }
325                                 return PolicyResult.FAILURE;
326                         }
327                 }
328                 else if (response instanceof LCMResponseWrapper) {
329
330                     LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
331
332                     /*
333                      * Parse out the operation attempt using the subrequestid
334                      */
335                     Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
336                     if (operationAttempt == null) {
337                         this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
338                     }
339
340                     /*
341                      * Process the APPCLCM response to see what PolicyResult
342                      * should be returned
343                      */
344                     AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
345
346                     if (result.getKey() != null) {
347                     this.completeOperation(operationAttempt, result.getValue(), result.getKey());
348                     if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
349                     return null;
350                 }
351                     return result.getKey();
352                     }
353                     return null;
354                 } else if (response instanceof SOResponse) {
355                         SOResponse msoResponse = (SOResponse) response;
356
357                         switch (msoResponse.httpResponseCode) {
358                         case 200:
359                         case 202:
360                                 //
361                                 // Consider it as success
362                                 //
363                                 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
364                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
365                                         return null;
366                                 }
367                                 return PolicyResult.SUCCESS;
368                         default:
369                                 //
370                                 // Consider it as failure
371                                 //
372                                 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
373                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
374                                         return null;
375                                 }
376                                 return PolicyResult.FAILURE;
377                         }
378
379                 } else if (response instanceof VFCResponse) {
380                         VFCResponse vfcResponse = (VFCResponse) response;
381
382                         if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
383                                 //
384                                 // Consider it as success
385                                 //
386                                 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
387                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
388                                         return null;
389                                 }
390                                 return PolicyResult.SUCCESS;
391                         } else {
392                                 //
393                                 // Consider it as failure
394                                 //
395                                 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
396                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
397                                         return null;
398                                 }
399                                 // increment operation attempts for retries
400                                 this.attempts += 1;
401                                 return PolicyResult.FAILURE;
402                         }
403                 }
404                 return null;
405         }
406
407         public Integer  getOperationTimeout() {
408                 //
409                 // Sanity check
410                 //
411                 if (this.policy == null) {
412                         logger.debug("getOperationTimeout returning 0");
413                         return 0;
414                 }
415                 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
416                 return this.policy.getTimeout();
417         }
418
419         public String   getOperationTimeoutString(int defaultTimeout) {
420                 Integer to = this.getOperationTimeout();
421                 if (to == null || to == 0) {
422                         return Integer.toString(defaultTimeout) + "s";
423                 }
424                 return to.toString() + "s";
425         }
426
427         public PolicyResult     getOperationResult() {
428                 return this.policyResult;
429         }
430
431         public String   getOperationMessage() {
432                 if (this.currentOperation != null && this.currentOperation.operation != null) {
433                         return this.currentOperation.operation.toMessage();
434                 }
435
436                 if (!this.operationHistory.isEmpty()) {
437                         return this.operationHistory.getLast().operation.toMessage();
438                 }
439                 return null;
440         }
441
442         public String   getOperationMessage(String guardResult) {
443                 if (this.currentOperation != null && this.currentOperation.operation != null) {
444                         return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
445                 }
446           
447                 if (!this.operationHistory.isEmpty()) {
448                         return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
449                 }
450                 return null;
451         }
452
453         public String   getOperationHistory() {
454                 if (this.currentOperation != null && this.currentOperation.operation != null) {
455                         return this.currentOperation.operation.toHistory();
456                 }
457           
458                 if (!this.operationHistory.isEmpty()) {
459                         return this.operationHistory.getLast().operation.toHistory();
460                 }
461                 return null;
462         }
463
464         public LinkedList<ControlLoopOperation> getHistory() {
465                 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
466                 for (Operation op : this.operationHistory) {
467                         history.add(new ControlLoopOperation(op.operation));
468
469                 }
470                 return history;
471         }
472
473         public void             setOperationHasTimedOut() {
474                 //
475                 //
476                 //
477                 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
478         }
479
480         public void             setOperationHasGuardDeny() {
481                 //
482                 //
483                 //
484                 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
485         }
486         
487         public void setOperationHasException(String message) {
488                 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
489         }
490
491         public boolean  isOperationComplete() {
492                 //
493                 // Is there currently a result?
494                 //
495                 if (this.policyResult == null) {
496                         //
497                         // either we are in process or we
498                         // haven't started
499                         //
500                         return false;
501                 }
502                 //
503                 // We have some result, check if the operation failed
504                 //
505                 if (this.policyResult.equals(PolicyResult.FAILURE)) {
506                         //
507                         // Check if there were no retries specified
508                         //
509                         if (policy.getRetry() == null || policy.getRetry() == 0) {
510                                 //
511                                 // The result is the failure
512                                 //
513                                 return true;
514                         }
515                         //
516                         // Check retries
517                         //
518                         if (this.isRetriesMaxedOut()) {
519                                 //
520                                 // No more attempts allowed, reset
521                                 // that our actual result is failure due to retries
522                                 //
523                                 this.policyResult = PolicyResult.FAILURE_RETRIES;
524                                 return true;
525                         } else {
526                                 //
527                                 // There are more attempts available to try the
528                                 // policy recipe.
529                                 //
530                                 return false;
531                         }
532                 }
533                 //
534                 // Other results mean we are done
535                 //
536                 return true;
537         }
538
539         public boolean  isOperationRunning() {
540                 return (this.currentOperation != null);
541         }
542
543         private boolean isRetriesMaxedOut() {
544                 if (policy.getRetry() == null || policy.getRetry() == 0) {
545                         //
546                         // There were NO retries specified, so declare
547                         // this as completed.
548                         //
549                         return (this.attempts > 0);
550                 }
551                 return (this.attempts > policy.getRetry());
552         }
553
554         private void    storeOperationInDataBase(){
555                 // Only store in DB if enabled
556                 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
557                 if( !guardEnabled ){
558                         return;
559                 }
560
561
562                 // DB Properties
563                 Properties props = new Properties();
564                 if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null &&
565                                 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null &&
566                                 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){
567                         props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
568                         props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
569                         props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
570                 }
571                 
572                 
573                 String OpsHistPU = System.getProperty("OperationsHistoryPU");
574                 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
575                         OpsHistPU = "OperationsHistoryPU";
576                 }
577                 else{
578                         props.clear();
579                 }
580                 EntityManager em;
581                 try{
582                         em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
583                 }catch(Exception e){
584                         logger.error("storeOperationInDataBase threw: ", e);
585                         return;
586                 }
587
588                 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
589
590                 newEntry.closedLoopName = this.onset.closedLoopControlName;
591                 newEntry.requestId = this.onset.requestID.toString();
592                 newEntry.actor = this.currentOperation.operation.actor;
593                 newEntry.operation = this.currentOperation.operation.operation;
594                 newEntry.target = this.eventManager.getTargetInstance(this.policy);
595                 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
596                 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
597                 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
598                 newEntry.message = this.currentOperation.operation.message;
599                 newEntry.outcome = this.currentOperation.operation.outcome;
600
601                 em.getTransaction().begin();
602                 em.persist(newEntry);
603                 em.getTransaction().commit();
604
605                 em.close();
606
607         }
608
609
610
611         private void    completeOperation(Integer attempt, String message, PolicyResult result) {
612                 if (attempt == null) {
613                         logger.debug("attempt cannot be null (i.e. subRequestID)");
614                         return;
615                 }
616                 if (this.currentOperation != null) {
617                         if (this.currentOperation.attempt == attempt.intValue()) {
618                                 this.currentOperation.operation.end = Instant.now();
619                                 this.currentOperation.operation.message = message;
620                                 this.currentOperation.operation.outcome = result.toString();
621                                 this.currentOperation.policyResult = result;
622                                 //
623                                 // Save it in history
624                                 //
625                                 this.operationHistory.add(this.currentOperation);
626                                 this.storeOperationInDataBase();
627                                 //
628                                 // Set our last result
629                                 //
630                                 this.policyResult = result;
631                                 //
632                                 // Clear the current operation field
633                                 //
634                                 this.currentOperation = null;
635                                 return;
636                         }
637                         logger.debug("not current");
638                 }
639                 for (Operation op : this.operationHistory) {
640                         if (op.attempt == attempt.intValue()) {
641                                 op.operation.end = Instant.now();
642                                 op.operation.message = message;
643                                 op.operation.outcome = result.toString();
644                                 op.policyResult = result;
645                                 return;
646                         }
647                 }
648                 logger.debug("Could not find associated operation");
649
650         }
651
652 }