b5ec6dd5cf48a66ca73e89c39e548591b0626d72
[ccsdk/cds.git] /
1 /*
2  * Copyright © 2018-2019 AT&T Intellectual Property.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.atomix.service
18
19 import io.atomix.cluster.ClusterMembershipEvent
20 import io.atomix.core.Atomix
21 import io.atomix.core.lock.DistributedLock
22 import kotlinx.coroutines.delay
23 import org.onap.ccsdk.cds.blueprintsprocessor.atomix.utils.AtomixLibUtils
24 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.BluePrintClusterService
25 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterInfo
26 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterLock
27 import org.onap.ccsdk.cds.blueprintsprocessor.core.service.ClusterMember
28 import org.onap.ccsdk.cds.controllerblueprints.core.logger
29 import org.springframework.stereotype.Service
30 import java.time.Duration
31 import java.util.concurrent.CompletableFuture
32
33 @Service
34 open class AtomixBluePrintClusterService : BluePrintClusterService {
35
36     private val log = logger(AtomixBluePrintClusterService::class)
37
38     lateinit var atomix: Atomix
39
40     override suspend fun startCluster(clusterInfo: ClusterInfo) {
41         log.info(
42             "Cluster(${clusterInfo.id}) node(${clusterInfo.nodeId}), node address(${clusterInfo.nodeAddress}) " +
43                 "starting with members(${clusterInfo.clusterMembers})"
44         )
45
46         /** Create Atomix cluster either from config file or default multi-cast cluster*/
47         atomix = if (!clusterInfo.configFile.isNullOrEmpty()) {
48             AtomixLibUtils.configAtomix(clusterInfo.configFile!!)
49         } else {
50             AtomixLibUtils.defaultMulticastAtomix(clusterInfo)
51         }
52
53         /** Listen for the member chaneg events */
54         atomix.membershipService.addListener { membershipEvent ->
55             when (membershipEvent.type()) {
56                 ClusterMembershipEvent.Type.MEMBER_ADDED -> log.info("Member Added : ${membershipEvent.subject()}")
57                 ClusterMembershipEvent.Type.MEMBER_REMOVED -> log.info("Member Removed: ${membershipEvent.subject()}")
58                 ClusterMembershipEvent.Type.METADATA_CHANGED -> log.info("Changed : ${membershipEvent.subject()}")
59                 else -> log.info("Member event unknown")
60             }
61         }
62         atomix.start().join()
63         log.info(
64             "Cluster(${clusterInfo.id}) node(${clusterInfo.nodeId}), node address(${clusterInfo.nodeAddress}) " +
65                 "created successfully...."
66         )
67
68         /** Receive ping from network */
69         val pingHandler = { message: String ->
70             log.info("####### ping message received : $message")
71             CompletableFuture.completedFuture(message)
72         }
73         atomix.communicationService.subscribe("ping", pingHandler)
74
75         /** Ping the network */
76         atomix.communicationService.broadcast(
77             "ping",
78             "ping from node(${clusterInfo.nodeId})"
79         )
80     }
81
82     override fun clusterJoined(): Boolean {
83         return atomix.isRunning
84     }
85
86     override suspend fun allMembers(): Set<ClusterMember> {
87         check(::atomix.isInitialized) { "failed to start and join cluster" }
88         check(atomix.isRunning) { "cluster is not running" }
89
90         return atomix.membershipService.members.map {
91             ClusterMember(
92                 id = it.id().id(),
93                 memberAddress = it.host()
94             )
95         }.toSet()
96     }
97
98     override suspend fun clusterMembersForPrefix(memberPrefix: String): Set<ClusterMember> {
99         check(::atomix.isInitialized) { "failed to start and join cluster" }
100         check(atomix.isRunning) { "cluster is not running" }
101
102         return atomix.membershipService.members.filter {
103             it.id().id().startsWith(memberPrefix, true)
104         }.map { ClusterMember(id = it.id().id(), memberAddress = it.host()) }
105             .toSet()
106     }
107
108     override suspend fun <T> clusterMapStore(name: String): MutableMap<String, T> {
109         check(::atomix.isInitialized) { "failed to start and join cluster" }
110         return AtomixLibUtils.distributedMapStore<T>(atomix, name)
111     }
112
113     /** The DistributedLock is a distributed implementation of Java’s Lock.
114      * This API provides monotonically increasing, globally unique lock instance identifiers that can be used to
115      * determine ordering of multiple concurrent lock holders.
116      * DistributedLocks are designed to account for failures within the cluster.
117      * When a lock holder crashes or becomes disconnected from the partition by which the lock’s state is controlled,
118      * the lock will be released and granted to the next waiting process.     *
119      */
120     override suspend fun clusterLock(name: String): ClusterLock {
121         check(::atomix.isInitialized) { "failed to start and join cluster" }
122         return ClusterLockImpl(atomix, name)
123     }
124
125     override suspend fun shutDown(duration: Duration) {
126         if (::atomix.isInitialized) {
127             val shutDownMilli = duration.toMillis()
128             log.info("Received cluster shutdown request, shutdown in ($shutDownMilli)ms")
129             delay(shutDownMilli)
130             atomix.stop()
131         }
132     }
133 }
134
135 open class ClusterLockImpl(private val atomix: Atomix, private val name: String) : ClusterLock {
136
137     lateinit var distributedLock: DistributedLock
138
139     override suspend fun lock() {
140         distributedLock = AtomixLibUtils.distributedLock(atomix, name)
141         distributedLock.lock()
142     }
143
144     override suspend fun tryLock(timeout: Long): Boolean {
145         distributedLock = AtomixLibUtils.distributedLock(atomix, name)
146         return distributedLock.tryLock(Duration.ofMillis(timeout))
147     }
148
149     override suspend fun unLock() {
150         distributedLock.unlock()
151     }
152
153     override fun isLocked(): Boolean {
154         return distributedLock.isLocked
155     }
156 }