2 * ============LICENSE_START=======================================================
3 * controlloop operation manager
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.controlloop.eventmanager;
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.List;
30 import java.util.NoSuchElementException;
31 import java.util.Properties;
33 import javax.persistence.EntityManager;
34 import javax.persistence.Persistence;
36 import org.eclipse.persistence.config.PersistenceUnitProperties;
37 import org.onap.policy.aai.util.AaiException;
38 import org.onap.policy.appc.Response;
39 import org.onap.policy.appc.ResponseCode;
40 import org.onap.policy.appclcm.LcmResponseWrapper;
41 import org.onap.policy.controlloop.ControlLoopEvent;
42 import org.onap.policy.controlloop.ControlLoopException;
43 import org.onap.policy.controlloop.ControlLoopOperation;
44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
45 import org.onap.policy.controlloop.actor.appc.AppcActorServiceProvider;
46 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
47 import org.onap.policy.controlloop.actor.sdnc.SdncActorServiceProvider;
48 import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
49 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
50 import org.onap.policy.controlloop.actor.vfc.VfcActorServiceProvider;
51 import org.onap.policy.controlloop.policy.Policy;
52 import org.onap.policy.controlloop.policy.PolicyResult;
53 import org.onap.policy.drools.system.PolicyEngine;
54 import org.onap.policy.guard.Util;
55 import org.onap.policy.sdnc.SdncResponse;
56 import org.onap.policy.sdnr.PciResponseWrapper;
57 import org.onap.policy.so.SoResponseWrapper;
58 import org.onap.policy.vfc.VfcResponse;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 public class ControlLoopOperationManager implements Serializable {
63 private static final long serialVersionUID = -3773199283624595410L;
64 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
66 private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
67 private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
68 private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
71 // These properties are not changeable, but accessible
72 // for Drools Rule statements.
74 public final ControlLoopEvent onset;
75 public final Policy policy;
78 // Properties used to track the Operation
80 private int attempts = 0;
81 private Operation currentOperation = null;
82 private LinkedList<Operation> operationHistory = new LinkedList<>();
83 private PolicyResult policyResult = null;
84 private ControlLoopEventManager eventManager = null;
85 private String targetEntity;
86 private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY"
87 private transient Object operationRequest;
90 * Construct an instance.
92 * @param onset the onset event
93 * @param policy the policy
94 * @param em the event manager
95 * @throws ControlLoopException if an error occurs
96 * @throws AaiException if an error occurs retrieving information from A&AI
98 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em)
99 throws ControlLoopException, AaiException {
101 this.policy = policy;
102 this.guardApprovalStatus = "NONE";
103 this.eventManager = em;
104 this.targetEntity = getTarget(policy);
107 // Let's make a sanity check
109 switch (policy.getActor()) {
111 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
113 * The target vnf-id may not be the same as the source vnf-id specified in the
114 * yaml, the target vnf-id is retrieved by a named query to A&AI.
116 String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(),
118 this.targetEntity = targetVnf;
130 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
134 public ControlLoopEventManager getEventManager() {
138 public void setEventManager(ControlLoopEventManager eventManager) {
139 this.eventManager = eventManager;
142 public String getTargetEntity() {
143 return this.targetEntity;
147 public String toString() {
148 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestId() : "null") + ", policy="
149 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult="
150 + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
155 // Internal class used for tracking
157 private class Operation implements Serializable {
158 private static final long serialVersionUID = 1L;
160 private ControlLoopOperation clOperation = new ControlLoopOperation();
161 private PolicyResult policyResult = null;
162 private int attempt = 0;
165 public String toString() {
166 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation
171 public Object getOperationRequest() {
172 return operationRequest;
175 public String getGuardApprovalStatus() {
176 return guardApprovalStatus;
179 public void setGuardApprovalStatus(String guardApprovalStatus) {
180 this.guardApprovalStatus = guardApprovalStatus;
184 * Get the target for a policy.
186 * @param policy the policy
188 * @throws ControlLoopException if an error occurs
189 * @throws AaiException if an error occurs retrieving information from A&AI
191 public String getTarget(Policy policy) throws ControlLoopException, AaiException {
192 if (policy.getTarget() == null) {
193 throw new ControlLoopException("The target is null");
196 if (policy.getTarget().getType() == null) {
197 throw new ControlLoopException("The target type is null");
200 switch (policy.getTarget().getType()) {
202 throw new ControlLoopException("PNF target is not supported");
205 VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
206 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
207 return virtualOnset.getAai().get(VSERVER_VSERVER_NAME);
208 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
209 return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
210 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
212 * If the onset is enriched with the vnf-id, we don't need an A&AI response
214 if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
215 return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
219 * If the vnf-name was retrieved from the onset then the vnf-id must be obtained
220 * from the event manager's A&AI GET query
222 String vnfId = this.eventManager.getVnfResponse().getVnfId();
224 throw new AaiException("No vnf-id found");
228 throw new ControlLoopException("Target does not match target type");
230 throw new ControlLoopException("The target type is not supported");
235 * Start an operation.
237 * @param onset the onset event
238 * @return the operation request
239 * @throws ControlLoopException if an error occurs
241 public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset) throws ControlLoopException {
242 verifyOperatonCanRun();
247 this.policyResult = null;
248 Operation operation = new Operation();
249 operation.attempt = ++this.attempts;
250 operation.clOperation.setActor(this.policy.getActor());
251 operation.clOperation.setOperation(this.policy.getRecipe());
252 operation.clOperation.setTarget(this.policy.getTarget().toString());
253 operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
255 // Now determine which actor we need to construct a request for
257 switch (policy.getActor()) {
260 * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an
261 * LCMRequest is constructed.
263 this.currentOperation = operation;
264 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
265 this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
266 operation.clOperation, this.policy, this.targetEntity);
268 this.operationRequest = AppcLcmActorServiceProvider.constructRequest(
269 (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity);
272 // Save the operation
275 return operationRequest;
277 SoActorServiceProvider soActorSp = new SoActorServiceProvider();
278 this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset,
279 operation.clOperation, this.policy, eventManager.getNqVserverFromAai());
281 // Save the operation
282 this.currentOperation = operation;
284 if (this.operationRequest == null) {
285 this.policyResult = PolicyResult.FAILURE;
288 return operationRequest;
290 this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
291 operation.clOperation, this.policy, this.eventManager.getVnfResponse());
292 this.currentOperation = operation;
293 if (this.operationRequest == null) {
294 this.policyResult = PolicyResult.FAILURE;
296 return operationRequest;
299 * If the recipe is ModifyConfig, a SDNR request is constructed.
301 this.currentOperation = operation;
302 this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
303 operation.clOperation, this.policy);
305 // Save the operation
307 if (this.operationRequest == null) {
308 this.policyResult = PolicyResult.FAILURE;
311 return operationRequest;
313 SdncActorServiceProvider provider = new SdncActorServiceProvider();
314 this.operationRequest = provider.constructRequest((VirtualControlLoopEvent) onset,
315 operation.clOperation, this.policy);
316 this.currentOperation = operation;
317 if (this.operationRequest == null) {
318 this.policyResult = PolicyResult.FAILURE;
320 return operationRequest;
322 throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy");
329 * @param response the response
330 * @return a PolicyResult
332 public PolicyResult onResponse(Object response) {
334 // Which response is it?
336 if (response instanceof Response) {
338 // Cast APPC response and handle it
340 return onResponse((Response) response);
341 } else if (response instanceof LcmResponseWrapper) {
343 // Cast LCM response and handle it
345 return onResponse((LcmResponseWrapper) response);
346 } else if (response instanceof PciResponseWrapper) {
348 // Cast SDNR response and handle it
350 return onResponse((PciResponseWrapper) response);
351 } else if (response instanceof SoResponseWrapper) {
353 // Cast SO response and handle it
355 return onResponse((SoResponseWrapper) response);
356 } else if (response instanceof VfcResponse) {
358 // Cast VFC response and handle it
360 return onResponse((VfcResponse) response);
361 } else if (response instanceof SdncResponse) {
363 // Cast SDNC response and handle it
365 return onResponse((SdncResponse) response);
372 * This method handles operation responses from APPC.
374 * @param appcResponse the APPC response
375 * @return The result of the response handling
377 private PolicyResult onResponse(Response appcResponse) {
379 // Determine which subrequestID (ie. attempt)
381 Integer operationAttempt = null;
383 operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId());
384 } catch (NumberFormatException e) {
386 // We cannot tell what happened if this doesn't exist
388 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
389 PolicyResult.FAILURE_EXCEPTION);
390 return PolicyResult.FAILURE_EXCEPTION;
393 // Sanity check the response message
395 if (appcResponse.getStatus() == null) {
397 // We cannot tell what happened if this doesn't exist
399 this.completeOperation(operationAttempt,
400 "Policy was unable to parse APP-C response status field (it was null).",
401 PolicyResult.FAILURE_EXCEPTION);
402 return PolicyResult.FAILURE_EXCEPTION;
405 // Get the Response Code
407 ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
410 // We are unaware of this code
412 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.",
413 PolicyResult.FAILURE_EXCEPTION);
414 return PolicyResult.FAILURE_EXCEPTION;
417 // Ok, let's figure out what APP-C's response is
422 // This is good, they got our original message and
425 // Is there any need to track this?
431 // We'll consider these two codes as exceptions
433 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
434 PolicyResult.FAILURE_EXCEPTION);
435 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
438 return PolicyResult.FAILURE_EXCEPTION;
443 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
444 PolicyResult.SUCCESS);
445 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
448 return PolicyResult.SUCCESS;
453 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
454 PolicyResult.FAILURE);
455 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
458 return PolicyResult.FAILURE;
465 * This method handles operation responses from LCM.
467 * @param dmaapResponse the LCM response
468 * @return The result of the response handling
470 private PolicyResult onResponse(LcmResponseWrapper dmaapResponse) {
472 * Parse out the operation attempt using the subrequestid
474 Integer operationAttempt = AppcLcmActorServiceProvider
475 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
476 if (operationAttempt == null) {
477 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
478 PolicyResult.FAILURE_EXCEPTION);
482 * Process the APPCLCM response to see what PolicyResult should be returned
484 AbstractMap.SimpleEntry<PolicyResult, String> result =
485 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
487 if (result.getKey() != null) {
488 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
489 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
492 return result.getKey();
498 * This method handles operation responses from SDNR.
500 * @param dmaapResponse the SDNR response
501 * @return the result of the response handling
503 private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
505 * Parse out the operation attempt using the subrequestid
507 Integer operationAttempt = SdnrActorServiceProvider
508 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
509 if (operationAttempt == null) {
510 this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.",
511 PolicyResult.FAILURE_EXCEPTION);
515 * Process the SDNR response to see what PolicyResult should be returned
517 SdnrActorServiceProvider.Pair<PolicyResult, String> result =
518 SdnrActorServiceProvider.processResponse(dmaapResponse);
520 if (result.getResult() != null) {
521 this.completeOperation(operationAttempt, result.getMessage(), result.getResult());
522 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
525 return result.getResult();
531 * This method handles operation responses from SO.
533 * @param msoResponse the SO response
534 * @return The result of the response handling
536 private PolicyResult onResponse(SoResponseWrapper msoResponse) {
537 switch (msoResponse.getSoResponse().getHttpResponseCode()) {
541 // Consider it as success
543 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success",
544 PolicyResult.SUCCESS);
545 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
548 return PolicyResult.SUCCESS;
551 // Consider it as failure
553 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed",
554 PolicyResult.FAILURE);
555 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
558 return PolicyResult.FAILURE;
563 * This method handles operation responses from VFC.
565 * @param vfcResponse the VFC response
566 * @return The result of the response handling
568 private PolicyResult onResponse(VfcResponse vfcResponse) {
569 if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) {
571 // Consider it as success
573 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
574 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
577 return PolicyResult.SUCCESS;
580 // Consider it as failure
582 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
583 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
586 // increment operation attempts for retries
588 return PolicyResult.FAILURE;
593 * This method handles operation responses from SDNC.
595 * @param sdncResponse the VFC response
596 * @return The result of the response handling
598 private PolicyResult onResponse(SdncResponse sdncResponse) {
599 if ("200".equals(sdncResponse.getResponseOutput().getResponseCode())) {
601 // Consider it as success
603 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
604 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
607 return PolicyResult.SUCCESS;
610 // Consider it as failure
612 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
613 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
616 // increment operation attempts for retries
618 return PolicyResult.FAILURE;
623 * Get the operation timeout.
625 * @return the timeout
627 public Integer getOperationTimeout() {
631 if (this.policy == null) {
632 logger.debug("getOperationTimeout returning 0");
635 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
636 return this.policy.getTimeout();
640 * Get the operation timeout as a String.
642 * @param defaultTimeout the default timeout
643 * @return the timeout as a String
645 public String getOperationTimeoutString(int defaultTimeout) {
646 Integer to = this.getOperationTimeout();
647 if (to == null || to == 0) {
648 return Integer.toString(defaultTimeout) + "s";
650 return to.toString() + "s";
653 public PolicyResult getOperationResult() {
654 return this.policyResult;
658 * Get the operation as a message.
660 * @return the operation as a message
662 public String getOperationMessage() {
663 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
664 return this.currentOperation.clOperation.toMessage();
667 if (!this.operationHistory.isEmpty()) {
668 return this.operationHistory.getLast().clOperation.toMessage();
674 * Get the operation as a message including the guard result.
676 * @param guardResult the guard result
677 * @return the operation as a message including the guard result
679 public String getOperationMessage(String guardResult) {
680 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
681 return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
684 if (!this.operationHistory.isEmpty()) {
685 return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult;
691 * Get the operation history.
693 * @return the operation history
695 public String getOperationHistory() {
696 if (this.currentOperation != null && this.currentOperation.clOperation != null) {
697 return this.currentOperation.clOperation.toHistory();
700 if (!this.operationHistory.isEmpty()) {
701 return this.operationHistory.getLast().clOperation.toHistory();
709 * @return the list of control loop operations
711 public List<ControlLoopOperation> getHistory() {
712 LinkedList<ControlLoopOperation> history = new LinkedList<>();
713 for (Operation op : this.operationHistory) {
714 history.add(new ControlLoopOperation(op.clOperation));
721 * Set the operation has timed out.
723 public void setOperationHasTimedOut() {
727 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
731 * Set the operation has been denied by guard.
733 public void setOperationHasGuardDeny() {
737 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
740 public void setOperationHasException(String message) {
741 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
745 * Is the operation complete.
747 * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
749 public boolean isOperationComplete() {
751 // Is there currently a result?
753 if (this.policyResult == null) {
755 // either we are in process or we
761 // We have some result, check if the operation failed
763 if (this.policyResult.equals(PolicyResult.FAILURE)) {
765 // Check if there were no retries specified
767 if (policy.getRetry() == null || policy.getRetry() == 0) {
769 // The result is the failure
776 if (this.isRetriesMaxedOut()) {
778 // No more attempts allowed, reset
779 // that our actual result is failure due to retries
781 this.policyResult = PolicyResult.FAILURE_RETRIES;
785 // There are more attempts available to try the
792 // Other results mean we are done
797 public boolean isOperationRunning() {
798 return (this.currentOperation != null);
802 * This method verifies that the operation manager may run an operation.
804 * @return True if the operation can run, false otherwise
805 * @throws ControlLoopException if the operation cannot run
807 private void verifyOperatonCanRun() throws ControlLoopException {
809 // They shouldn't call us if we currently running something
811 if (this.currentOperation != null) {
813 // what do we do if we are already running an operation?
815 throw new ControlLoopException("current operation is not null (an operation is already running)");
818 // Check if we have maxed out on retries
820 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
822 // No retries are allowed, so check have we even made
823 // one attempt to execute the operation?
825 if (this.attempts >= 1) {
827 // We have, let's ensure our PolicyResult is set
829 if (this.policyResult == null) {
830 this.policyResult = PolicyResult.FAILURE_RETRIES;
835 throw new ControlLoopException("current operation failed and retries are not allowed");
839 // Have we maxed out on retries?
841 if (this.attempts > this.policy.getRetry()) {
842 if (this.policyResult == null) {
843 this.policyResult = PolicyResult.FAILURE_RETRIES;
845 throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries");
850 private boolean isRetriesMaxedOut() {
851 if (policy.getRetry() == null || policy.getRetry() == 0) {
853 // There were NO retries specified, so declare
854 // this as completed.
856 return (this.attempts > 0);
858 return (this.attempts > policy.getRetry());
861 private void storeOperationInDataBase() {
862 // Only store in DB if enabled
863 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
870 Properties props = new Properties();
871 if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null
872 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null
873 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
874 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
875 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
876 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
877 props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader());
881 String opsHistPu = System.getProperty("OperationsHistoryPU");
882 if (!"TestOperationsHistoryPU".equals(opsHistPu)) {
883 opsHistPu = "OperationsHistoryPU";
889 em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
890 } catch (Exception e) {
891 logger.error("storeOperationInDataBase threw: ", e);
895 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
897 newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
898 newEntry.setRequestId(this.onset.getRequestId().toString());
899 newEntry.setActor(this.currentOperation.clOperation.getActor());
900 newEntry.setOperation(this.currentOperation.clOperation.getOperation());
901 newEntry.setTarget(this.targetEntity);
902 newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
903 newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
904 newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
905 newEntry.setMessage(this.currentOperation.clOperation.getMessage());
906 newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());
908 em.getTransaction().begin();
909 em.persist(newEntry);
910 em.getTransaction().commit();
915 private void completeOperation(Integer attempt, String message, PolicyResult result) {
916 if (attempt == null) {
917 logger.debug("attempt cannot be null (i.e. subRequestID)");
920 if (this.currentOperation != null) {
921 if (this.currentOperation.attempt == attempt.intValue()) {
922 this.currentOperation.clOperation.setEnd(Instant.now());
923 this.currentOperation.clOperation.setMessage(message);
924 this.currentOperation.clOperation.setOutcome(result.toString());
925 this.currentOperation.policyResult = result;
927 // Save it in history
929 this.operationHistory.add(this.currentOperation);
930 this.storeOperationInDataBase();
932 // Set our last result
934 this.policyResult = result;
936 // Clear the current operation field
938 this.currentOperation = null;
941 logger.debug("not current");
943 for (Operation op : this.operationHistory) {
944 if (op.attempt == attempt.intValue()) {
945 op.clOperation.setEnd(Instant.now());
946 op.clOperation.setMessage(message);
947 op.clOperation.setOutcome(result.toString());
948 op.policyResult = result;
952 logger.debug("Could not find associated operation");
957 * Commit the abatement to the history database.
959 * @param message the abatement message
960 * @param outcome the abatement outcome
962 public void commitAbatement(String message, String outcome) {
963 logger.info("commitAbatement: {}. {}", message, outcome);
965 if (this.currentOperation == null) {
967 this.currentOperation = this.operationHistory.getLast();
968 } catch (NoSuchElementException e) {
969 logger.error("{}: commitAbatement threw an exception ", this, e);
973 this.currentOperation.clOperation.setEnd(Instant.now());
974 this.currentOperation.clOperation.setMessage(message);
975 this.currentOperation.clOperation.setOutcome(outcome);
977 // Store commit in DB
979 this.storeOperationInDataBase();
981 // Clear the current operation field
983 this.currentOperation = null;