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