eeb724ad20dedab18c1db57a54f99c9965b9671d
[policy/drools-applications.git] /
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, 
213                                             operation.operation, this.policy, eventManager.getVnfResponse());
214                     }
215                     else {
216                         this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, 
217                                                 operation.operation, this.policy, eventManager.getVnfResponse());
218                     }
219                         //
220                         // Save the operation
221                         //
222                         
223                         return operationRequest;
224                 case "SO":
225                         SOActorServiceProvider SOAsp = new SOActorServiceProvider();
226                         this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
227
228                         // Save the operation
229                         this.currentOperation = operation;
230
231                         if (this.operationRequest == null) {
232                                 this.policyResult = PolicyResult.FAILURE;
233                         }
234
235                         return operationRequest;
236                 case "VFC":
237                         this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse());
238                         this.currentOperation = operation;
239                         return operationRequest;
240
241                 }
242                 return null;
243         }
244
245         public PolicyResult     onResponse(Object response) {
246                 //
247                 // Which response is it?
248                 //
249                 if (response instanceof Response) {
250                         //
251                         // Cast it
252                         //
253                         Response appcResponse = (Response) response;
254                         //
255                         // Determine which subrequestID (ie. attempt)
256                         //
257                         Integer operationAttempt = null;
258                         try {
259                                 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
260                         } catch (NumberFormatException e) {
261                                 //
262                                 // We cannot tell what happened if this doesn't exist
263                                 //
264                                 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
265                                 return PolicyResult.FAILURE_EXCEPTION;
266                         }
267                         //
268                         // Sanity check the response message
269                         //
270                         if (appcResponse.Status == null) {
271                                 //
272                                 // We cannot tell what happened if this doesn't exist
273                                 //
274                                 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
275                                 return PolicyResult.FAILURE_EXCEPTION;
276                         }
277                         //
278                         // Get the Response Code
279                         //
280                         ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
281                         if (code == null) {
282                                 //
283                                 // We are unaware of this code
284                                 //
285                                 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
286                                 return PolicyResult.FAILURE_EXCEPTION;
287                         }
288                         //
289                         // Ok, let's figure out what APP-C's response is
290                         //
291                         switch (code) {
292                         case ACCEPT:
293                                 //
294                                 // This is good, they got our original message and
295                                 // acknowledged it.
296                                 //
297                                 // Is there any need to track this?
298                                 //
299                                 return null;
300                         case ERROR:
301                         case REJECT:
302                                 //
303                                 // We'll consider these two codes as exceptions
304                                 //
305                                 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
306                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
307                                         return null;
308                                 }
309                                 return PolicyResult.FAILURE_EXCEPTION;
310                         case SUCCESS:
311                                 //
312                                 //
313                                 //
314                                 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
315                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
316                                         return null;
317                                 }
318                                 return PolicyResult.SUCCESS;
319                         case FAILURE:
320                                 //
321                                 //
322                                 //
323                                 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
324                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
325                                         return null;
326                                 }
327                                 return PolicyResult.FAILURE;
328                         }
329                 }
330                 else if (response instanceof LCMResponseWrapper) {
331
332                     LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
333
334                     /*
335                      * Parse out the operation attempt using the subrequestid
336                      */
337                     Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
338                     if (operationAttempt == null) {
339                         this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
340                     }
341
342                     /*
343                      * Process the APPCLCM response to see what PolicyResult
344                      * should be returned
345                      */
346                     AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
347
348                     if (result.getKey() != null) {
349                     this.completeOperation(operationAttempt, result.getValue(), result.getKey());
350                     if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
351                     return null;
352                 }
353                     return result.getKey();
354                     }
355                     return null;
356                 } else if (response instanceof SOResponse) {
357                         SOResponse msoResponse = (SOResponse) response;
358
359                         switch (msoResponse.httpResponseCode) {
360                         case 200:
361                         case 202:
362                                 //
363                                 // Consider it as success
364                                 //
365                                 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
366                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
367                                         return null;
368                                 }
369                                 return PolicyResult.SUCCESS;
370                         default:
371                                 //
372                                 // Consider it as failure
373                                 //
374                                 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
375                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
376                                         return null;
377                                 }
378                                 return PolicyResult.FAILURE;
379                         }
380
381                 } else if (response instanceof VFCResponse) {
382                         VFCResponse vfcResponse = (VFCResponse) response;
383
384                         if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
385                                 //
386                                 // Consider it as success
387                                 //
388                                 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
389                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
390                                         return null;
391                                 }
392                                 return PolicyResult.SUCCESS;
393                         } else {
394                                 //
395                                 // Consider it as failure
396                                 //
397                                 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
398                                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
399                                         return null;
400                                 }
401                                 // increment operation attempts for retries
402                                 this.attempts += 1;
403                                 return PolicyResult.FAILURE;
404                         }
405                 }
406                 return null;
407         }
408
409         public Integer  getOperationTimeout() {
410                 //
411                 // Sanity check
412                 //
413                 if (this.policy == null) {
414                         logger.debug("getOperationTimeout returning 0");
415                         return 0;
416                 }
417                 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
418                 return this.policy.getTimeout();
419         }
420
421         public String   getOperationTimeoutString(int defaultTimeout) {
422                 Integer to = this.getOperationTimeout();
423                 if (to == null || to == 0) {
424                         return Integer.toString(defaultTimeout) + "s";
425                 }
426                 return to.toString() + "s";
427         }
428
429         public PolicyResult     getOperationResult() {
430                 return this.policyResult;
431         }
432
433         public String   getOperationMessage() {
434                 if (this.currentOperation != null && this.currentOperation.operation != null) {
435                         return this.currentOperation.operation.toMessage();
436                 }
437
438                 if (!this.operationHistory.isEmpty()) {
439                         return this.operationHistory.getLast().operation.toMessage();
440                 }
441                 return null;
442         }
443
444         public String   getOperationMessage(String guardResult) {
445                 if (this.currentOperation != null && this.currentOperation.operation != null) {
446                         return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
447                 }
448           
449                 if (!this.operationHistory.isEmpty()) {
450                         return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
451                 }
452                 return null;
453         }
454
455         public String   getOperationHistory() {
456                 if (this.currentOperation != null && this.currentOperation.operation != null) {
457                         return this.currentOperation.operation.toHistory();
458                 }
459           
460                 if (!this.operationHistory.isEmpty()) {
461                         return this.operationHistory.getLast().operation.toHistory();
462                 }
463                 return null;
464         }
465
466         public LinkedList<ControlLoopOperation> getHistory() {
467                 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
468                 for (Operation op : this.operationHistory) {
469                         history.add(new ControlLoopOperation(op.operation));
470
471                 }
472                 return history;
473         }
474
475         public void             setOperationHasTimedOut() {
476                 //
477                 //
478                 //
479                 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
480         }
481
482         public void             setOperationHasGuardDeny() {
483                 //
484                 //
485                 //
486                 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
487         }
488         
489         public void setOperationHasException(String message) {
490                 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
491         }
492
493         public boolean  isOperationComplete() {
494                 //
495                 // Is there currently a result?
496                 //
497                 if (this.policyResult == null) {
498                         //
499                         // either we are in process or we
500                         // haven't started
501                         //
502                         return false;
503                 }
504                 //
505                 // We have some result, check if the operation failed
506                 //
507                 if (this.policyResult.equals(PolicyResult.FAILURE)) {
508                         //
509                         // Check if there were no retries specified
510                         //
511                         if (policy.getRetry() == null || policy.getRetry() == 0) {
512                                 //
513                                 // The result is the failure
514                                 //
515                                 return true;
516                         }
517                         //
518                         // Check retries
519                         //
520                         if (this.isRetriesMaxedOut()) {
521                                 //
522                                 // No more attempts allowed, reset
523                                 // that our actual result is failure due to retries
524                                 //
525                                 this.policyResult = PolicyResult.FAILURE_RETRIES;
526                                 return true;
527                         } else {
528                                 //
529                                 // There are more attempts available to try the
530                                 // policy recipe.
531                                 //
532                                 return false;
533                         }
534                 }
535                 //
536                 // Other results mean we are done
537                 //
538                 return true;
539         }
540
541         public boolean  isOperationRunning() {
542                 return (this.currentOperation != null);
543         }
544
545         private boolean isRetriesMaxedOut() {
546                 if (policy.getRetry() == null || policy.getRetry() == 0) {
547                         //
548                         // There were NO retries specified, so declare
549                         // this as completed.
550                         //
551                         return (this.attempts > 0);
552                 }
553                 return (this.attempts > policy.getRetry());
554         }
555
556         private void    storeOperationInDataBase(){
557                 // Only store in DB if enabled
558                 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
559                 if( !guardEnabled ){
560                         return;
561                 }
562
563
564                 // DB Properties
565                 Properties props = new Properties();
566                 if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null &&
567                                 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null &&
568                                 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){
569                         props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
570                         props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
571                         props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
572                 }
573                 
574                 
575                 String OpsHistPU = System.getProperty("OperationsHistoryPU");
576                 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
577                         OpsHistPU = "OperationsHistoryPU";
578                 }
579                 else{
580                         props.clear();
581                 }
582                 EntityManager em;
583                 try{
584                         em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
585                 }catch(Exception e){
586                         logger.error("storeOperationInDataBase threw: ", e);
587                         return;
588                 }
589
590                 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
591
592                 newEntry.closedLoopName = this.onset.closedLoopControlName;
593                 newEntry.requestId = this.onset.requestID.toString();
594                 newEntry.actor = this.currentOperation.operation.actor;
595                 newEntry.operation = this.currentOperation.operation.operation;
596                 newEntry.target = this.eventManager.getTargetInstance(this.policy);
597                 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
598                 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
599                 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
600                 newEntry.message = this.currentOperation.operation.message;
601                 newEntry.outcome = this.currentOperation.operation.outcome;
602
603                 em.getTransaction().begin();
604                 em.persist(newEntry);
605                 em.getTransaction().commit();
606
607                 em.close();
608
609         }
610
611
612
613         private void    completeOperation(Integer attempt, String message, PolicyResult result) {
614                 if (attempt == null) {
615                         logger.debug("attempt cannot be null (i.e. subRequestID)");
616                         return;
617                 }
618                 if (this.currentOperation != null) {
619                         if (this.currentOperation.attempt == attempt.intValue()) {
620                                 this.currentOperation.operation.end = Instant.now();
621                                 this.currentOperation.operation.message = message;
622                                 this.currentOperation.operation.outcome = result.toString();
623                                 this.currentOperation.policyResult = result;
624                                 //
625                                 // Save it in history
626                                 //
627                                 this.operationHistory.add(this.currentOperation);
628                                 this.storeOperationInDataBase();
629                                 //
630                                 // Set our last result
631                                 //
632                                 this.policyResult = result;
633                                 //
634                                 // Clear the current operation field
635                                 //
636                                 this.currentOperation = null;
637                                 return;
638                         }
639                         logger.debug("not current");
640                 }
641                 for (Operation op : this.operationHistory) {
642                         if (op.attempt == attempt.intValue()) {
643                                 op.operation.end = Instant.now();
644                                 op.operation.message = message;
645                                 op.operation.outcome = result.toString();
646                                 op.policyResult = result;
647                                 return;
648                         }
649                 }
650                 logger.debug("Could not find associated operation");
651
652         }
653
654 }