Adapt A1 controller to latest A1 spec
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / tasks / RicRecoveryTask.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.oransc.policyagent.tasks;
22
23 import java.util.Vector;
24
25 import org.oransc.policyagent.clients.A1Client;
26 import org.oransc.policyagent.clients.A1ClientFactory;
27 import org.oransc.policyagent.clients.AsyncRestClient;
28 import org.oransc.policyagent.exceptions.ServiceException;
29 import org.oransc.policyagent.repository.ImmutablePolicyType;
30 import org.oransc.policyagent.repository.Policies;
31 import org.oransc.policyagent.repository.Policy;
32 import org.oransc.policyagent.repository.PolicyType;
33 import org.oransc.policyagent.repository.PolicyTypes;
34 import org.oransc.policyagent.repository.Ric;
35 import org.oransc.policyagent.repository.Service;
36 import org.oransc.policyagent.repository.Services;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import reactor.core.publisher.Flux;
41 import reactor.core.publisher.Mono;
42
43 /**
44  * Recovery handling of RIC, which means:
45  * - load all policy types
46  * - send all policy instances to the RIC
47  * --- if that fails remove all policy instances
48  * - Notify subscribing services
49  */
50 public class RicRecoveryTask {
51
52     private static final Logger logger = LoggerFactory.getLogger(RicRecoveryTask.class);
53
54     private final A1ClientFactory a1ClientFactory;
55     private final PolicyTypes policyTypes;
56     private final Policies policies;
57     private final Services services;
58
59     public RicRecoveryTask(A1ClientFactory a1ClientFactory, PolicyTypes policyTypes, Policies policies,
60         Services services) {
61         this.a1ClientFactory = a1ClientFactory;
62         this.policyTypes = policyTypes;
63         this.policies = policies;
64         this.services = services;
65     }
66
67     public void run(Ric ric) {
68         logger.debug("Handling ric: {}", ric.getConfig().name());
69
70         synchronized (ric) {
71             if (ric.state().equals(Ric.RicState.RECOVERING)) {
72                 return; // Already running
73             }
74             ric.setState(Ric.RicState.RECOVERING);
75         }
76         this.a1ClientFactory.createA1Client(ric)//
77             .flatMapMany(client -> startRecover(ric, client)) //
78             .subscribe(x -> logger.debug("Recover: " + x), //
79                 throwable -> onRecoveryError(ric, throwable), //
80                 () -> onRecoveryComplete(ric));
81     }
82
83     private Flux<Object> startRecover(Ric ric, A1Client a1Client) {
84         Flux<PolicyType> recoverTypes = recoverPolicyTypes(ric, a1Client);
85         Flux<?> deletePoliciesInRic = a1Client.deleteAllPolicies();
86         Flux<?> recreatePoliciesInRic = recreateAllPoliciesInRic(ric, a1Client);
87
88         return Flux.concat(recoverTypes, deletePoliciesInRic, recreatePoliciesInRic);
89     }
90
91     private void onRecoveryComplete(Ric ric) {
92         logger.debug("Recovery completed for:" + ric.name());
93         ric.setState(Ric.RicState.IDLE);
94         notifyAllServices("Recovery completed for:" + ric.name());
95     }
96
97     private void notifyAllServices(String body) {
98         synchronized (services) {
99             for (Service service : services.getAll()) {
100                 String url = service.getCallbackUrl();
101                 if (service.getCallbackUrl().length() > 0) {
102                     createClient(url) //
103                         .put("", body) //
104                         .subscribe(rsp -> logger.debug("Service called"),
105                             throwable -> logger.warn("Service called failed", throwable),
106                             () -> logger.debug("Service called complete"));
107                 }
108             }
109         }
110     }
111
112     private void onRecoveryError(Ric ric, Throwable t) {
113         logger.warn("Recovery failed for: {}, reason: {}", ric.name(), t.getMessage());
114         // If recovery fails, try to remove all instances
115         deleteAllPolicies(ric);
116         Flux<PolicyType> recoverTypes = this.a1ClientFactory.createA1Client(ric) //
117             .flatMapMany(a1Client -> recoverPolicyTypes(ric, a1Client));
118         Flux<?> deletePoliciesInRic = this.a1ClientFactory.createA1Client(ric) //
119             .flatMapMany(a1Client -> a1Client.deleteAllPolicies());
120
121         Flux.merge(recoverTypes, deletePoliciesInRic) //
122             .subscribe(x -> logger.debug("Brute recover: " + x), //
123                 throwable -> onRemoveAllError(ric, throwable), //
124                 () -> onRecoveryComplete(ric));
125     }
126
127     private void onRemoveAllError(Ric ric, Throwable t) {
128         logger.warn("Remove all failed for: {}, reason: {}", ric.name(), t.getMessage());
129         ric.setState(Ric.RicState.UNDEFINED);
130     }
131
132     private AsyncRestClient createClient(final String url) {
133         return new AsyncRestClient(url);
134     }
135
136     private Flux<PolicyType> recoverPolicyTypes(Ric ric, A1Client a1Client) {
137         ric.clearSupportedPolicyTypes();
138         return a1Client.getPolicyTypeIdentities() //
139             .flatMapMany(types -> Flux.fromIterable(types)) //
140             .doOnNext(typeId -> logger.debug("For ric: {}, handling type: {}", ric.getConfig().name(), typeId)) //
141             .flatMap((policyTypeId) -> getPolicyType(ric, policyTypeId, a1Client)) //
142             .doOnNext(policyType -> ric.addSupportedPolicyType(policyType)); //
143     }
144
145     private Mono<PolicyType> getPolicyType(Ric ric, String policyTypeId, A1Client a1Client) {
146         if (policyTypes.contains(policyTypeId)) {
147             try {
148                 return Mono.just(policyTypes.getType(policyTypeId));
149             } catch (ServiceException e) {
150                 return Mono.error(e);
151             }
152         }
153         return a1Client.getPolicyTypeSchema(policyTypeId) //
154             .flatMap(schema -> createPolicyType(policyTypeId, schema));
155     }
156
157     private Mono<PolicyType> createPolicyType(String policyTypeId, String schema) {
158         PolicyType pt = ImmutablePolicyType.builder().name(policyTypeId).schema(schema).build();
159         policyTypes.put(pt);
160         return Mono.just(pt);
161     }
162
163     private void deleteAllPolicies(Ric ric) {
164         synchronized (policies) {
165             for (Policy policy : policies.getForRic(ric.name())) {
166                 this.policies.remove(policy);
167             }
168         }
169     }
170
171     private Flux<String> recreateAllPoliciesInRic(Ric ric, A1Client a1Client) {
172         synchronized (policies) {
173             return Flux.fromIterable(new Vector<>(policies.getForRic(ric.name()))) //
174                 .doOnNext(
175                     policy -> logger.debug("Recreating policy: {}, for ric: {}", policy.id(), ric.getConfig().name()))
176                 .flatMap(policy -> a1Client.putPolicy(policy));
177         }
178     }
179
180 }