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