Sync Integ to Master
[sdc.git] / catalog-dao / src / main / java / org / openecomp / sdc / be / dao / cassandra / AuditCassandraDao.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.be.dao.cassandra;
22
23 import java.util.ArrayList;
24 import java.util.List;
25
26 import javax.annotation.PostConstruct;
27
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.config.BeEcompErrorManager;
30 import org.openecomp.sdc.be.dao.api.ActionStatus;
31 import org.openecomp.sdc.be.dao.cassandra.schema.Table;
32 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
33 import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
34 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
35 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
36 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
37 import org.openecomp.sdc.be.resources.data.auditing.DistributionStatusEvent;
38 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
39 import org.openecomp.sdc.common.config.EcompErrorName;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.stereotype.Component;
43
44 import com.datastax.driver.core.Session;
45 import com.datastax.driver.mapping.MappingManager;
46 import com.datastax.driver.mapping.Result;
47
48 import fj.data.Either;
49
50 @Component("audit-cassandra-dao")
51 public class AuditCassandraDao extends CassandraDao {
52
53         private AuditAccessor auditAccessor;
54
55         private static Logger logger = LoggerFactory.getLogger(AuditCassandraDao.class.getName());
56
57         public AuditCassandraDao() {
58                 super();
59         }
60
61         @PostConstruct
62         public void init() {
63                 String keyspace = AuditingTypesConstants.AUDIT_KEYSPACE;
64                 if (client.isConnected()) {
65                         Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
66                         if (result.isLeft()) {
67                                 session = result.left().value().left;
68                                 manager = result.left().value().right;
69                                 auditAccessor = manager.createAccessor(AuditAccessor.class);
70                                 logger.info("** AuditCassandraDao created");
71                         } else {
72                                 logger.info("** AuditCassandraDao failed");
73                                 throw new RuntimeException(
74                                                 "Audit keyspace [" + keyspace + "] failed to connect with error : " + result.right().value());
75                         }
76                 } else {
77                         logger.info("** Cassandra client isn't connected");
78                         logger.info("** AuditCassandraDao created, but not connected");
79                 }
80
81         }
82
83         @SuppressWarnings("unchecked")
84         public <T extends AuditingGenericEvent> CassandraOperationStatus saveRecord(T entity) {
85                 return client.save(entity, (Class<T>) entity.getClass(), manager);
86         }
87
88         /**
89          * 
90          * @param did
91          * @return
92          */
93         public Either<List<DistributionStatusEvent>, ActionStatus> getListOfDistributionStatuses(String did) {
94                 List<DistributionStatusEvent> remainingElements = new ArrayList<DistributionStatusEvent>();
95
96                 try {
97                         Result<DistributionStatusEvent> events = auditAccessor.getListOfDistributionStatuses(did);
98                         if (events == null) {
99                                 logger.debug("not found distribution statuses for did {}", did);
100                                 return Either.left(remainingElements);
101                         }
102                         events.all().forEach(event -> {
103                                 event.fillFields();
104                                 remainingElements.add(event);
105                                 logger.debug(event.toString());
106                         });
107                         return Either.left(remainingElements);
108                 } catch (Exception e) {
109                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
110                         logger.debug("failed to get distribution statuses for ", e);
111                         return Either.right(ActionStatus.GENERAL_ERROR);
112                 }
113         }
114
115         public Either<List<DistributionDeployEvent>, ActionStatus> getDistributionDeployByStatus(String did, String action,
116                         String status) {
117                 List<DistributionDeployEvent> remainingElements = new ArrayList<DistributionDeployEvent>();
118
119                 try {
120                         Result<DistributionDeployEvent> events = auditAccessor.getDistributionDeployByStatus(did, action, status);
121                         if (events == null) {
122                                 logger.debug("not found distribution statuses for did {}", did);
123                                 return Either.left(remainingElements);
124                         }
125                         events.all().forEach(event -> {
126                                 event.fillFields();
127                                 remainingElements.add(event);
128                                 logger.debug(event.toString());
129                         });
130
131                         return Either.left(remainingElements);
132                 } catch (Exception e) {
133                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution Deploy By Status");
134                         logger.debug("failed to get distribution deploy by status for ", e);
135                         return Either.right(ActionStatus.GENERAL_ERROR);
136                 }
137         }
138
139         public Either<List<ResourceAdminEvent>, ActionStatus> getDistributionRequest(String did, String action) {
140                 List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
141
142                 try {
143                         Result<ResourceAdminEvent> events = auditAccessor.getDistributionRequest(did, action);
144                         if (events == null) {
145                                 logger.debug("not found distribution requests for did {}", did);
146                                 return Either.left(remainingElements);
147                         }
148                         events.all().forEach(event -> {
149                                 event.fillFields();
150                                 remainingElements.add(event);
151                                 logger.debug(event.toString());
152                         });
153                         return Either.left(remainingElements);
154                 } catch (Exception e) {
155                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution request");
156                         logger.debug("failed to get distribution request for ", e);
157                         return Either.right(ActionStatus.GENERAL_ERROR);
158                 }
159         }
160
161         public Either<List<DistributionNotificationEvent>, ActionStatus> getDistributionNotify(String did, String action) {
162                 List<DistributionNotificationEvent> remainingElements = new ArrayList<DistributionNotificationEvent>();
163
164                 try {
165                         Result<DistributionNotificationEvent> events = auditAccessor.getDistributionNotify(did, action);
166                         if (events == null) {
167                                 logger.debug("not found distribution notify for did {}", did);
168                                 return Either.left(remainingElements);
169                         }
170                         events.all().forEach(event -> {
171                                 event.fillFields();
172                                 remainingElements.add(event);
173                                 logger.debug(event.toString());
174                         });
175
176                         return Either.left(remainingElements);
177                 } catch (Exception e) {
178                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
179                         logger.debug("failed to get distribution notify for ", e);
180                         return Either.right(ActionStatus.GENERAL_ERROR);
181                 }
182         }
183
184         public Either<List<ResourceAdminEvent>, ActionStatus> getByServiceInstanceId(String serviceInstanceId) {
185                 List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
186
187                 try {
188                         Result<ResourceAdminEvent> events = auditAccessor.getByServiceInstanceId(serviceInstanceId);
189                         if (events == null) {
190                                 logger.debug("not found audit records for serviceInstanceId {}", serviceInstanceId);
191                                 return Either.left(remainingElements);
192                         }
193                         events.all().forEach(event -> {
194                                 event.fillFields();
195                                 remainingElements.add(event);
196                                 logger.debug(event.toString());
197                         });
198                         return Either.left(remainingElements);
199                 } catch (Exception e) {
200                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
201                         logger.debug("failed to get distribution notify for ", e);
202                         return Either.right(ActionStatus.GENERAL_ERROR);
203                 }
204         }
205
206         /**
207          * 
208          * @param serviceInstanceId
209          * @return
210          */
211         public Either<List<? extends AuditingGenericEvent>, ActionStatus> getServiceDistributionStatusesList(
212                         String serviceInstanceId) {
213
214                 List<AuditingGenericEvent> resList = new ArrayList<>();
215
216                 try {
217                         Result<ResourceAdminEvent> resourceAdminEvents = auditAccessor
218                                         .getServiceDistributionStatus(serviceInstanceId);
219
220                         if (resourceAdminEvents != null) {
221                                 resourceAdminEvents.all().forEach(event -> {
222                                         event.fillFields();
223                                         resList.add(event);
224                                         logger.debug(event.toString());
225                                 });
226                         }
227
228                 } catch (Exception e) {
229                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
230                         logger.debug("failed to get  distribution statuses for action {}",
231                                         AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), e);
232                         return Either.right(ActionStatus.GENERAL_ERROR);
233                 }
234                 try {
235                         Result<DistributionDeployEvent> distDeployEvents = auditAccessor
236                                         .getServiceDistributionDeploy(serviceInstanceId);
237                         if (distDeployEvents != null) {
238                                 distDeployEvents.all().forEach(event -> {
239                                         event.fillFields();
240                                         resList.add(event);
241                                         logger.debug(event.toString());
242                                 });
243                         }
244                 } catch (Exception e) {
245                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
246                         logger.debug("failed to get distribution statuses for action {}",
247                                         AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), e);
248                         return Either.right(ActionStatus.GENERAL_ERROR);
249                 }
250                 try {
251                         Result<DistributionNotificationEvent> distNotifEvent = auditAccessor
252                                         .getServiceDistributionNotify(serviceInstanceId);
253                         if (distNotifEvent != null) {
254                                 distNotifEvent.all().forEach(event -> {
255                                         event.fillFields();
256                                         resList.add(event);
257                                         logger.debug(event.toString());
258                                 });
259                         }
260                 } catch (Exception e) {
261                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
262                         logger.debug("failed to get distribution statuses for action {}",
263                                         AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), e);
264                         return Either.right(ActionStatus.GENERAL_ERROR);
265                 }
266
267                 return Either.left(resList);
268         }
269
270         public Either<List<ResourceAdminEvent>, ActionStatus> getAuditByServiceIdAndPrevVersion(String serviceInstanceId,
271                         String prevVersion) {
272                 List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
273
274                 try {
275                         Result<ResourceAdminEvent> events = auditAccessor.getAuditByServiceIdAndPrevVersion(serviceInstanceId,
276                                         prevVersion);
277                         if (events == null) {
278                                 logger.debug("not found audit records for serviceInstanceId {} andprevVersion {}", serviceInstanceId,
279                                                 prevVersion);
280                                 return Either.left(remainingElements);
281                         }
282                         events.all().forEach(event -> {
283                                 event.fillFields();
284                                 remainingElements.add(event);
285                                 logger.debug(event.toString());
286                         });
287                         return Either.left(remainingElements);
288                 } catch (Exception e) {
289                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And PrevVersion");
290                         logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
291                         return Either.right(ActionStatus.GENERAL_ERROR);
292                 }
293         }
294
295         public Either<List<ResourceAdminEvent>, ActionStatus> getAuditByServiceIdAndCurrVersion(String serviceInstanceId,
296                         String currVersion) {
297                 List<ResourceAdminEvent> remainingElements = new ArrayList<ResourceAdminEvent>();
298
299                 try {
300                         Result<ResourceAdminEvent> events = auditAccessor.getAuditByServiceIdAndCurrVersion(serviceInstanceId,
301                                         currVersion);
302                         if (events == null) {
303                                 logger.debug("not found audit records for serviceInstanceId {} andprevVersion {}", serviceInstanceId,
304                                                 currVersion);
305                                 return Either.left(remainingElements);
306                         }
307                         events.all().forEach(event -> {
308                                 event.fillFields();
309                                 remainingElements.add(event);
310                                 logger.debug(event.toString());
311                         });
312                         return Either.left(remainingElements);
313                 } catch (Exception e) {
314                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And CurrVersion");
315
316                         logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
317                         return Either.right(ActionStatus.GENERAL_ERROR);
318                 }
319         }
320
321         /**
322          * the method checks if the given table is empty in the audit keyspace
323          * 
324          * @param tableName
325          *            the name of the table we want to check
326          * @return true if the table is empty
327          */
328         public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
329                 return super.isTableEmpty(tableName);
330         }
331
332         /**
333          * ---------for use in JUnit only--------------- the method deletes all the
334          * tables in the audit keyspace
335          * 
336          * @return the status of the last failed operation or ok if all the deletes
337          *         were successful
338          */
339         public CassandraOperationStatus deleteAllAudit() {
340                 logger.info("cleaning all audit tables.");
341                 String query = "truncate " + AuditingTypesConstants.AUDIT_KEYSPACE + ".";
342                 try {
343                         for (Table table : Table.values()) {
344                                 if (table.getTableDescription().getKeyspace().equals(AuditingTypesConstants.AUDIT_KEYSPACE)) {
345                                         logger.debug("clean Audit table:{}", table.getTableDescription().getTableName());
346                                         session.execute(query + table.getTableDescription().getTableName() + ";");
347                                         logger.debug("clean Audit table:{} was succsesfull", table.getTableDescription().getTableName());
348                                 }
349                         }
350                 } catch (Exception e) {
351                         logger.error("Failed to clean Audit", e);
352                         return CassandraOperationStatus.GENERAL_ERROR;
353                 }
354                 logger.info("clean all audit finished succsesfully.");
355                 return CassandraOperationStatus.OK;
356         }
357 }