2 * Copyright © 2018-2019 AT&T Intellectual Property.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.onap.ccsdk.cds.blueprintsprocessor.core.cluster
19 import com.hazelcast.cluster.Member
20 import kotlinx.coroutines.GlobalScope
21 import kotlinx.coroutines.newSingleThreadContext
22 import kotlinx.coroutines.withContext
23 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterMember
26 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants
27 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
28 import org.onap.ccsdk.cds.controllerblueprints.core.MDCContext
29 import org.onap.ccsdk.cds.controllerblueprints.core.service.BluePrintDependencyService
32 * Exposed Dependency Service by this Hazelcast Lib Module
34 fun BluePrintDependencyService.clusterService(): BluePrintClusterService =
35 instance(HazelcastClusterService::class)
37 /** Optional Cluster Service, returns only if Cluster is enabled */
38 fun BluePrintDependencyService.optionalClusterService(): BluePrintClusterService? {
39 return if (BluePrintConstants.CLUSTER_ENABLED) {
40 BluePrintDependencyService.clusterService()
44 /** Extension to convert Hazelcast Member to Blueprints Cluster Member */
45 fun Member.toClusterMember(): ClusterMember {
46 val memberName: String = this.getAttribute(BluePrintConstants.PROPERTY_CLUSTER_NODE_ID) ?: this.uuid.toString()
48 id = this.uuid.toString(),
50 memberAddress = this.address.toString()
55 * This function will try to acquire the lock and then execute the provided block.
56 * If the lock cannot be acquired within timeout, a BluePrintException will be thrown.
58 * Since a lock can only be unlocked by the the thread which acquired the lock,
59 * this function will confine coroutines within the block to a dedicated thread.
61 suspend fun <R> ClusterLock.executeWithLock(acquireLockTimeout: Long, block: suspend () -> R): R {
63 return newSingleThreadContext(lock.name()).use {
64 withContext(GlobalScope.coroutineContext[MDCContext]?.plus(it) ?: it) {
65 if (lock.tryLock(acquireLockTimeout)) {
72 throw BluePrintException("Failed to acquire lock within timeout")