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