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