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