Rework the policy refresh
[clamp.git] / src / main / java / org / onap / clamp / loop / Loop.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  *
22  */
23
24 package org.onap.clamp.loop;
25
26 import com.google.gson.JsonObject;
27 import com.google.gson.annotations.Expose;
28 import java.io.Serializable;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.SortedSet;
34 import java.util.TreeSet;
35 import javax.persistence.CascadeType;
36 import javax.persistence.Column;
37 import javax.persistence.Entity;
38 import javax.persistence.EnumType;
39 import javax.persistence.Enumerated;
40 import javax.persistence.FetchType;
41 import javax.persistence.Id;
42 import javax.persistence.JoinColumn;
43 import javax.persistence.JoinTable;
44 import javax.persistence.ManyToMany;
45 import javax.persistence.ManyToOne;
46 import javax.persistence.OneToMany;
47 import javax.persistence.Table;
48 import javax.persistence.Transient;
49 import org.hibernate.annotations.SortNatural;
50 import org.hibernate.annotations.Type;
51 import org.hibernate.annotations.TypeDef;
52 import org.hibernate.annotations.TypeDefs;
53 import org.onap.clamp.clds.tosca.update.ToscaConverterWithDictionarySupport;
54 import org.onap.clamp.clds.util.drawing.SvgLoopGenerator;
55 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
56 import org.onap.clamp.loop.common.AuditEntity;
57 import org.onap.clamp.loop.components.external.DcaeComponent;
58 import org.onap.clamp.loop.components.external.ExternalComponent;
59 import org.onap.clamp.loop.components.external.PolicyComponent;
60 import org.onap.clamp.loop.log.LoopLog;
61 import org.onap.clamp.loop.service.Service;
62 import org.onap.clamp.loop.template.LoopElementModel;
63 import org.onap.clamp.loop.template.LoopTemplate;
64 import org.onap.clamp.policy.microservice.MicroServicePolicy;
65 import org.onap.clamp.policy.operational.OperationalPolicy;
66
67 @Entity
68 @Table(name = "loops")
69 @TypeDefs({@TypeDef(name = "json", typeClass = StringJsonUserType.class)})
70 public class Loop extends AuditEntity implements Serializable {
71
72     /**
73      * The serial version id.
74      */
75     private static final long serialVersionUID = -286522707701388642L;
76
77     @Id
78     @Expose
79     @Column(nullable = false, name = "name", unique = true)
80     private String name;
81
82     @Expose
83     @Column(name = "dcae_deployment_id")
84     private String dcaeDeploymentId;
85
86     @Expose
87     @Column(name = "dcae_deployment_status_url")
88     private String dcaeDeploymentStatusUrl;
89
90     @Column(columnDefinition = "MEDIUMTEXT", name = "svg_representation")
91     private String svgRepresentation;
92
93     @Expose
94     @Type(type = "json")
95     @Column(columnDefinition = "json", name = "global_properties_json")
96     private JsonObject globalPropertiesJson;
97
98     @Expose
99     @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
100     @JoinColumn(name = "service_uuid")
101     private Service modelService;
102
103     @Expose
104     @Column(nullable = false, name = "last_computed_state")
105     @Enumerated(EnumType.STRING)
106     private LoopState lastComputedState;
107
108     @Expose
109     @Transient
110     private final Map<String, ExternalComponent> components = new HashMap<>();
111
112     @Expose
113     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loop", orphanRemoval = true)
114     private Set<OperationalPolicy> operationalPolicies = new HashSet<>();
115
116     @Expose
117     @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.EAGER)
118     @JoinTable(name = "loops_to_microservicepolicies", joinColumns = @JoinColumn(name = "loop_name"),
119             inverseJoinColumns = @JoinColumn(name = "microservicepolicy_name"))
120     private Set<MicroServicePolicy> microServicePolicies = new HashSet<>();
121
122     @Expose
123     @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loop", orphanRemoval = true)
124     @SortNatural
125     private SortedSet<LoopLog> loopLogs = new TreeSet<>();
126
127     @Expose
128     @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.EAGER)
129     @JoinColumn(name = "loop_template_name", nullable = false)
130     private LoopTemplate loopTemplate;
131
132     private void initializeExternalComponents() {
133         this.addComponent(new PolicyComponent());
134         this.addComponent(new DcaeComponent());
135     }
136
137     /**
138      * Public constructor.
139      */
140     public Loop() {
141         initializeExternalComponents();
142     }
143
144     /**
145      * Constructor.
146      */
147     public Loop(String name, String svgRepresentation) {
148         this.name = name;
149         this.svgRepresentation = svgRepresentation;
150         this.lastComputedState = LoopState.DESIGN;
151         this.globalPropertiesJson = new JsonObject();
152         initializeExternalComponents();
153     }
154
155     /**
156      * This constructor creates a loop from a loop template.
157      *
158      * @param name         The loop name
159      * @param loopTemplate The loop template from which a new loop instance must be created
160      */
161     public Loop(String name, LoopTemplate loopTemplate, ToscaConverterWithDictionarySupport toscaConverter) {
162         this(name, "");
163         this.setLoopTemplate(loopTemplate);
164         this.setModelService(loopTemplate.getModelService());
165         loopTemplate.getLoopElementModelsUsed().forEach(element -> {
166             if (LoopElementModel.MICRO_SERVICE_TYPE.equals(element.getLoopElementModel().getLoopElementType())) {
167                 this.addMicroServicePolicy((MicroServicePolicy) element.getLoopElementModel()
168                         .createPolicyInstance(this, toscaConverter));
169             }
170             else if (LoopElementModel.OPERATIONAL_POLICY_TYPE
171                     .equals(element.getLoopElementModel().getLoopElementType())) {
172                 this.addOperationalPolicy((OperationalPolicy) element.getLoopElementModel()
173                         .createPolicyInstance(this, toscaConverter));
174             }
175         });
176     }
177
178     public String getName() {
179         return name;
180     }
181
182     void setName(String name) {
183         this.name = name;
184     }
185
186     public String getDcaeDeploymentId() {
187         return dcaeDeploymentId;
188     }
189
190     void setDcaeDeploymentId(String dcaeDeploymentId) {
191         this.dcaeDeploymentId = dcaeDeploymentId;
192     }
193
194     public String getDcaeDeploymentStatusUrl() {
195         return dcaeDeploymentStatusUrl;
196     }
197
198     void setDcaeDeploymentStatusUrl(String dcaeDeploymentStatusUrl) {
199         this.dcaeDeploymentStatusUrl = dcaeDeploymentStatusUrl;
200     }
201
202     public String getSvgRepresentation() {
203         return svgRepresentation;
204     }
205
206     void setSvgRepresentation(String svgRepresentation) {
207         this.svgRepresentation = svgRepresentation;
208     }
209
210     public LoopState getLastComputedState() {
211         return lastComputedState;
212     }
213
214     void setLastComputedState(LoopState lastComputedState) {
215         this.lastComputedState = lastComputedState;
216     }
217
218     public Set<OperationalPolicy> getOperationalPolicies() {
219         return operationalPolicies;
220     }
221
222     void setOperationalPolicies(Set<OperationalPolicy> operationalPolicies) {
223         this.operationalPolicies = operationalPolicies;
224     }
225
226     public Set<MicroServicePolicy> getMicroServicePolicies() {
227         return microServicePolicies;
228     }
229
230     void setMicroServicePolicies(Set<MicroServicePolicy> microServicePolicies) {
231         this.microServicePolicies = microServicePolicies;
232     }
233
234     public JsonObject getGlobalPropertiesJson() {
235         return globalPropertiesJson;
236     }
237
238     void setGlobalPropertiesJson(JsonObject globalPropertiesJson) {
239         this.globalPropertiesJson = globalPropertiesJson;
240     }
241
242     public Set<LoopLog> getLoopLogs() {
243         return loopLogs;
244     }
245
246     void setLoopLogs(SortedSet<LoopLog> loopLogs) {
247         this.loopLogs = loopLogs;
248     }
249
250     /**
251      * This method adds an operational policy to the loop.
252      * It re-computes the Svg as well.
253      *
254      * @param opPolicy the operationalPolicy to add
255      */
256     public void addOperationalPolicy(OperationalPolicy opPolicy) {
257         operationalPolicies.add(opPolicy);
258         opPolicy.setLoop(this);
259         this.setSvgRepresentation(SvgLoopGenerator.getSvgImage(this));
260     }
261
262     /**
263      * This method removes an operational policy to the loop.
264      * It re-computes the Svg as well.
265      *
266      * @param opPolicy the operationalPolicy to add
267      */
268     public void removeOperationalPolicy(OperationalPolicy opPolicy) {
269         operationalPolicies.remove(opPolicy);
270         this.setSvgRepresentation(SvgLoopGenerator.getSvgImage(this));
271     }
272
273     /**
274      * This method adds an micro service policy to the loop.
275      * It re-computes the Svg as well.
276      *
277      * @param microServicePolicy the micro service to add
278      */
279     public void addMicroServicePolicy(MicroServicePolicy microServicePolicy) {
280         microServicePolicies.add(microServicePolicy);
281         microServicePolicy.getUsedByLoops().add(this);
282         this.setSvgRepresentation(SvgLoopGenerator.getSvgImage(this));
283     }
284
285     public void addLog(LoopLog log) {
286         log.setLoop(this);
287         this.loopLogs.add(log);
288     }
289
290     public Service getModelService() {
291         return modelService;
292     }
293
294     void setModelService(Service modelService) {
295         this.modelService = modelService;
296     }
297
298     public Map<String, ExternalComponent> getComponents() {
299         refreshDcaeComponents();
300         return components;
301     }
302
303     public ExternalComponent getComponent(String componentName) {
304         refreshDcaeComponents();
305         return this.components.get(componentName);
306     }
307
308     public void addComponent(ExternalComponent component) {
309         this.components.put(component.getComponentName(), component);
310     }
311
312     public LoopTemplate getLoopTemplate() {
313         return loopTemplate;
314     }
315
316     public void setLoopTemplate(LoopTemplate loopTemplate) {
317         this.loopTemplate = loopTemplate;
318     }
319
320     private void refreshDcaeComponents() {
321         if (!this.loopTemplate.getUniqueBlueprint()) {
322             this.components.remove("DCAE");
323             for (MicroServicePolicy policy : this.microServicePolicies) {
324                 if (!this.components.containsKey("DCAE_" + policy.getName())) {
325                     this.addComponent(new DcaeComponent(policy.getName()));
326                 }
327             }
328         }
329     }
330
331     /**
332      * Generate the loop name.
333      *
334      * @param serviceName       The service name
335      * @param serviceVersion    The service version
336      * @param resourceName      The resource name
337      * @param blueprintFileName The blueprint file name
338      * @return The generated loop name
339      */
340     public static String generateLoopName(String serviceName, String serviceVersion, String resourceName,
341                                           String blueprintFileName) {
342         StringBuilder buffer = new StringBuilder("LOOP_").append(serviceName).append("_v").append(serviceVersion)
343                 .append("_").append(resourceName).append("_").append(blueprintFileName.replaceAll(".yaml", ""));
344         return buffer.toString().replace('.', '_').replaceAll(" ", "");
345     }
346
347     @Override
348     public int hashCode() {
349         final int prime = 31;
350         int result = 1;
351         result = prime * result + ((name == null) ? 0 : name.hashCode());
352         return result;
353     }
354
355     @Override
356     public boolean equals(Object obj) {
357         if (this == obj) {
358             return true;
359         }
360         if (obj == null) {
361             return false;
362         }
363         if (getClass() != obj.getClass()) {
364             return false;
365         }
366         Loop other = (Loop) obj;
367         if (name == null) {
368             if (other.name != null) {
369                 return false;
370             }
371         }
372         else if (!name.equals(other.name)) {
373             return false;
374         }
375         return true;
376     }
377
378 }