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