Change json representation in op policy
[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.Serializable;
31 import java.util.HashMap;
32 import java.util.HashSet;
33 import java.util.Map;
34 import java.util.Set;
35 import java.util.SortedSet;
36 import java.util.TreeSet;
37 import javax.persistence.CascadeType;
38 import javax.persistence.Column;
39 import javax.persistence.Entity;
40 import javax.persistence.EnumType;
41 import javax.persistence.Enumerated;
42 import javax.persistence.FetchType;
43 import javax.persistence.Id;
44 import javax.persistence.JoinColumn;
45 import javax.persistence.JoinTable;
46 import javax.persistence.ManyToMany;
47 import javax.persistence.ManyToOne;
48 import javax.persistence.OneToMany;
49 import javax.persistence.Table;
50 import javax.persistence.Transient;
51 import org.apache.commons.lang3.RandomStringUtils;
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.util.drawing.SvgLoopGenerator;
57 import org.onap.clamp.dao.model.jsontype.StringJsonUserType;
58 import org.onap.clamp.loop.common.AuditEntity;
59 import org.onap.clamp.loop.components.external.DcaeComponent;
60 import org.onap.clamp.loop.components.external.ExternalComponent;
61 import org.onap.clamp.loop.components.external.PolicyComponent;
62 import org.onap.clamp.loop.log.LoopLog;
63 import org.onap.clamp.loop.service.Service;
64 import org.onap.clamp.loop.template.LoopElementModel;
65 import org.onap.clamp.loop.template.LoopTemplate;
66 import org.onap.clamp.policy.Policy;
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) {
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                 this.addMicroServicePolicy(new MicroServicePolicy(Policy.generatePolicyName("MICROSERVICE_",
174                         loopTemplate.getModelService().getName(),loopTemplate.getModelService().getVersion(),
175                         RandomStringUtils.randomAlphanumeric(3),RandomStringUtils.randomAlphanumeric(3)),
176                         element.getLoopElementModel().getPolicyModels().first(), false, element.getLoopElementModel()));
177             } else if (LoopElementModel.OPERATIONAL_POLICY_TYPE
178                     .equals(element.getLoopElementModel().getLoopElementType())) {
179                 this.addOperationalPolicy(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL_",
180                         loopTemplate.getModelService().getName(),loopTemplate.getModelService().getVersion(),
181                         RandomStringUtils.randomAlphanumeric(3),RandomStringUtils.randomAlphanumeric(3)), null,
182                         new JsonObject(),
183                         element.getLoopElementModel().getPolicyModels().first(), element.getLoopElementModel(),
184                         null,null));
185             }
186         });
187     }
188
189     public String getName() {
190         return name;
191     }
192
193     void setName(String name) {
194         this.name = name;
195     }
196
197     public String getDcaeDeploymentId() {
198         return dcaeDeploymentId;
199     }
200
201     void setDcaeDeploymentId(String dcaeDeploymentId) {
202         this.dcaeDeploymentId = dcaeDeploymentId;
203     }
204
205     public String getDcaeDeploymentStatusUrl() {
206         return dcaeDeploymentStatusUrl;
207     }
208
209     void setDcaeDeploymentStatusUrl(String dcaeDeploymentStatusUrl) {
210         this.dcaeDeploymentStatusUrl = dcaeDeploymentStatusUrl;
211     }
212
213     public String getSvgRepresentation() {
214         return svgRepresentation;
215     }
216
217     void setSvgRepresentation(String svgRepresentation) {
218         this.svgRepresentation = svgRepresentation;
219     }
220
221     public LoopState getLastComputedState() {
222         return lastComputedState;
223     }
224
225     void setLastComputedState(LoopState lastComputedState) {
226         this.lastComputedState = lastComputedState;
227     }
228
229     public Set<OperationalPolicy> getOperationalPolicies() {
230         return operationalPolicies;
231     }
232
233     void setOperationalPolicies(Set<OperationalPolicy> operationalPolicies) {
234         this.operationalPolicies = operationalPolicies;
235     }
236
237     public Set<MicroServicePolicy> getMicroServicePolicies() {
238         return microServicePolicies;
239     }
240
241     void setMicroServicePolicies(Set<MicroServicePolicy> microServicePolicies) {
242         this.microServicePolicies = microServicePolicies;
243     }
244
245     public JsonObject getGlobalPropertiesJson() {
246         return globalPropertiesJson;
247     }
248
249     void setGlobalPropertiesJson(JsonObject globalPropertiesJson) {
250         this.globalPropertiesJson = globalPropertiesJson;
251     }
252
253     public Set<LoopLog> getLoopLogs() {
254         return loopLogs;
255     }
256
257     void setLoopLogs(SortedSet<LoopLog> loopLogs) {
258         this.loopLogs = loopLogs;
259     }
260
261     /**
262      * This method adds an operational policy to the loop.
263      * It re-computes the Svg as well.
264      *
265      * @param opPolicy the operationalPolicy to add
266      */
267     public void addOperationalPolicy(OperationalPolicy opPolicy) {
268         operationalPolicies.add(opPolicy);
269         opPolicy.setLoop(this);
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         } else if (!name.equals(other.name)) {
372             return false;
373         }
374         return true;
375     }
376
377 }