2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.policy.guard;
22 import java.util.HashMap;
24 import java.util.UUID;
26 import org.onap.policy.controlloop.policy.TargetType;
27 import org.onap.policy.guard.impl.PNFTargetLock;
28 import org.onap.policy.guard.impl.VMTargetLock;
30 public class PolicyGuard {
32 private static Map<String, TargetLock> activeLocks = new HashMap<String, TargetLock>();
34 public static class LockResult<A, B> {
38 public static <A, B> LockResult<A, B> createLockResult(A a, B b) {
39 return new LockResult<A, B>(a, b);
42 public LockResult(A a, B b) {
56 public static LockResult<GuardResult, TargetLock> lockTarget(TargetType targetType, String targetInstance, UUID requestID, LockCallback callback) {
58 synchronized(activeLocks) {
60 // Is there a lock on this instance already?
62 if (activeLocks.containsKey(targetInstance)) {
63 return LockResult.createLockResult(GuardResult.LOCK_DENIED, null);
65 TargetLock lock = null;
69 // Create the Lock object
71 lock = new PNFTargetLock(targetType, targetInstance, requestID, callback);
75 // Create the Lock object
77 lock = new VMTargetLock(targetType, targetInstance, requestID, callback);
80 return LockResult.createLockResult(GuardResult.LOCK_EXCEPTION, null);
85 activeLocks.put(targetInstance, lock);
89 System.out.println("Locking " + lock);
90 return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock);
94 public static boolean unlockTarget(TargetLock lock) {
95 synchronized(activeLocks) {
96 if (activeLocks.containsKey(lock.getTargetInstance())) {
97 System.out.println("Unlocking " + lock);
98 return (activeLocks.remove(lock.getTargetInstance()) != null);
104 public static boolean isLocked(TargetType targetType, String targetInstance, UUID requestID) {
105 synchronized(activeLocks) {
106 if (activeLocks.containsKey(targetInstance)) {
107 TargetLock lock = activeLocks.get(targetInstance);
108 return (lock.getTargetType().equals(targetType) && lock.getRequestID().equals(requestID));