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