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