2 * ============LICENSE_START======================================================================
3 * Copyright (C) 2023 Nordix Foundation. All rights reserved.
4 * ===============================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 * ============LICENSE_END========================================================================
19 package com.oransc.rappmanager.models.statemachine;
21 import com.oransc.rappmanager.models.rapp.RappEvent;
22 import com.oransc.rappmanager.models.rappinstance.RappInstance;
23 import com.oransc.rappmanager.models.rappinstance.RappInstanceState;
24 import java.util.HashMap;
26 import java.util.UUID;
27 import lombok.RequiredArgsConstructor;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.springframework.messaging.support.MessageBuilder;
31 import org.springframework.statemachine.StateMachine;
32 import org.springframework.statemachine.config.StateMachineFactory;
33 import org.springframework.stereotype.Service;
34 import reactor.core.publisher.Mono;
37 @RequiredArgsConstructor
38 public class RappInstanceStateMachine {
40 Logger logger = LoggerFactory.getLogger(RappInstanceStateMachine.class);
42 private final StateMachineFactory<RappInstanceState, RappEvent> stateMachineFactory;
43 Map<UUID, StateMachine<RappInstanceState, RappEvent>> stateMachineMap = new HashMap<>();
45 public void onboardRappInstance(UUID rappInstanceId) {
46 StateMachine<RappInstanceState, RappEvent> stateMachine = stateMachineFactory.getStateMachine(rappInstanceId);
47 stateMachineMap.put(rappInstanceId, stateMachine);
48 stateMachine.startReactively().subscribe();
51 public void sendRappInstanceEvent(RappInstance rappInstance, RappEvent rappEvent) {
52 logger.info("Sending rapp instance event {} for {}", rappEvent.name(), rappInstance.getRappInstanceId());
53 logger.debug("State machine map is {}", stateMachineMap);
54 stateMachineMap.get(rappInstance.getRappInstanceId())
55 .sendEvent(Mono.just(MessageBuilder.withPayload(rappEvent).build())).subscribe();
58 public RappInstanceState getRappInstanceState(UUID rappInstanceId) {
59 return stateMachineMap.get(rappInstanceId).getState().getId();
62 public void deleteRappInstance(RappInstance rappInstance) {
63 stateMachineMap.get(rappInstance.getRappInstanceId()).stopReactively().subscribe();
64 stateMachineMap.remove(rappInstance.getRappInstanceId());