re base code
[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 com.datastax.driver.core.Session;
24 import com.datastax.driver.mapping.MappingManager;
25 import com.datastax.driver.mapping.Result;
26 import fj.data.Either;
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.openecomp.sdc.be.config.BeEcompErrorManager;
29 import org.openecomp.sdc.be.dao.api.ActionStatus;
30 import org.openecomp.sdc.be.dao.cassandra.schema.Table;
31 import org.openecomp.sdc.be.resources.data.auditing.*;
32 import org.openecomp.sdc.common.log.wrappers.Logger;
33 import org.springframework.stereotype.Component;
34
35 import javax.annotation.PostConstruct;
36 import java.util.ArrayList;
37 import java.util.List;
38
39 @Component("audit-cassandra-dao")
40 public class AuditCassandraDao extends CassandraDao {
41
42         private AuditAccessor auditAccessor;
43
44         private static Logger logger = Logger.getLogger(AuditCassandraDao.class.getName());
45
46         public AuditCassandraDao() {
47                 super();
48         }
49
50         @PostConstruct
51         public void init() {
52                 String keyspace = AuditingTypesConstants.AUDIT_KEYSPACE;
53                 if (client.isConnected()) {
54                         Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
55                         if (result.isLeft()) {
56                                 session = result.left().value().left;
57                                 manager = result.left().value().right;
58                                 auditAccessor = manager.createAccessor(AuditAccessor.class);
59                                 logger.info("** AuditCassandraDao created");
60                         } else {
61                                 logger.info("** AuditCassandraDao failed");
62                                 throw new RuntimeException(
63                                                 "Audit keyspace [" + keyspace + "] failed to connect with error : " + result.right().value());
64                         }
65                 } else {
66                         logger.info("** Cassandra client isn't connected");
67                         logger.info("** AuditCassandraDao created, but not connected");
68                 }
69
70         }
71
72         @SuppressWarnings("unchecked")
73         public <T extends AuditingGenericEvent> CassandraOperationStatus saveRecord(T entity) {
74                 return client.save(entity, (Class<T>) entity.getClass(), manager);
75         }
76
77         /**
78          * 
79          * @param did
80          * @return
81          */
82         public Either<List<DistributionStatusEvent>, ActionStatus> getListOfDistributionStatuses(String did) {
83                 List<DistributionStatusEvent> remainingElements = new ArrayList<>();
84
85                 try {
86                         Result<DistributionStatusEvent> events = auditAccessor.getListOfDistributionStatuses(did);
87                         if (events == null) {
88                                 logger.debug("not found distribution statuses for did {}", did);
89                                 return Either.left(remainingElements);
90                         }
91                         events.all().forEach(event -> {
92                                 event.fillFields();
93                                 remainingElements.add(event);
94                                 logger.debug(event.toString());
95                         });
96                         return Either.left(remainingElements);
97                 } catch (Exception e) {
98                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get DistributionStatuses List");
99                         logger.debug("failed to get distribution statuses for ", e);
100                         return Either.right(ActionStatus.GENERAL_ERROR);
101                 }
102         }
103
104         public Either<List<DistributionDeployEvent>, ActionStatus> getDistributionDeployByStatus(String did, String action,
105                         String status) {
106                 List<DistributionDeployEvent> remainingElements = new ArrayList<>();
107
108                 try {
109                         Result<DistributionDeployEvent> events = auditAccessor.getDistributionDeployByStatus(did, action, status);
110                         if (events == null) {
111                                 logger.debug("not found distribution statuses for did {}", did);
112                                 return Either.left(remainingElements);
113                         }
114                         events.all().forEach(event -> {
115                                 event.fillFields();
116                                 remainingElements.add(event);
117                                 logger.debug(event.toString());
118                         });
119
120                         return Either.left(remainingElements);
121                 } catch (Exception e) {
122                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution Deploy By Status");
123                         logger.debug("failed to get distribution deploy by status for ", e);
124                         return Either.right(ActionStatus.GENERAL_ERROR);
125                 }
126         }
127
128         public Either<List<ResourceAdminEvent>, ActionStatus> getDistributionRequest(String did, String action) {
129                 List<ResourceAdminEvent> remainingElements = new ArrayList<>();
130
131                 try {
132                         Result<ResourceAdminEvent> events = auditAccessor.getDistributionRequest(did, action);
133                         if (events == null) {
134                                 logger.debug("not found distribution requests for did {}", did);
135                                 return Either.left(remainingElements);
136                         }
137                         events.all().forEach(event -> {
138                                 event.fillFields();
139                                 remainingElements.add(event);
140                                 logger.debug(event.toString());
141                         });
142                         return Either.left(remainingElements);
143                 } catch (Exception e) {
144                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution request");
145                         logger.debug("failed to get distribution request for ", e);
146                         return Either.right(ActionStatus.GENERAL_ERROR);
147                 }
148         }
149
150         public Either<List<DistributionNotificationEvent>, ActionStatus> getDistributionNotify(String did, String action) {
151                 List<DistributionNotificationEvent> remainingElements = new ArrayList<>();
152
153                 try {
154                         Result<DistributionNotificationEvent> events = auditAccessor.getDistributionNotify(did, action);
155                         if (events == null) {
156                                 logger.debug("not found distribution notify for did {}", did);
157                                 return Either.left(remainingElements);
158                         }
159                         events.all().forEach(event -> {
160                                 event.fillFields();
161                                 remainingElements.add(event);
162                                 logger.debug(event.toString());
163                         });
164
165                         return Either.left(remainingElements);
166                 } catch (Exception e) {
167                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
168                         logger.debug("failed to get distribution notify for ", e);
169                         return Either.right(ActionStatus.GENERAL_ERROR);
170                 }
171         }
172
173         public Either<List<ResourceAdminEvent>, ActionStatus> getByServiceInstanceId(String serviceInstanceId) {
174                 List<ResourceAdminEvent> remainingElements = new ArrayList<>();
175
176                 try {
177                         Result<ResourceAdminEvent> events = auditAccessor.getByServiceInstanceId(serviceInstanceId);
178                         if (events == null) {
179                                 logger.debug("not found audit records for serviceInstanceId {}", serviceInstanceId);
180                                 return Either.left(remainingElements);
181                         }
182                         events.all().forEach(event -> {
183                                 event.fillFields();
184                                 remainingElements.add(event);
185                                 logger.debug(event.toString());
186                         });
187                         return Either.left(remainingElements);
188                 } catch (Exception e) {
189                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Distribution notify");
190                         logger.debug("failed to get distribution notify for ", e);
191                         return Either.right(ActionStatus.GENERAL_ERROR);
192                 }
193         }
194
195         /**
196          * 
197          * @param serviceInstanceId
198          * @return
199          */
200         public Either<List<? extends AuditingGenericEvent>, ActionStatus> getServiceDistributionStatusesList(
201                         String serviceInstanceId) {
202
203                 List<AuditingGenericEvent> resList = new ArrayList<>();
204
205                 try {
206                         Result<ResourceAdminEvent> resourceAdminEvents = auditAccessor
207                                         .getServiceDistributionStatus(serviceInstanceId);
208
209                         if (resourceAdminEvents != null) {
210                                 resourceAdminEvents.all().forEach(event -> {
211                                         event.fillFields();
212                                         resList.add(event);
213                                         logger.debug(event.toString());
214                                 });
215                         }
216
217                 } catch (Exception e) {
218                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
219                         logger.debug("failed to get  distribution statuses for action {}",
220                                         AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), e);
221                         return Either.right(ActionStatus.GENERAL_ERROR);
222                 }
223                 try {
224                         Result<DistributionDeployEvent> distDeployEvents = auditAccessor
225                                         .getServiceDistributionDeploy(serviceInstanceId);
226                         if (distDeployEvents != null) {
227                                 distDeployEvents.all().forEach(event -> {
228                                         event.fillFields();
229                                         resList.add(event);
230                                         logger.debug(event.toString());
231                                 });
232                         }
233                 } catch (Exception e) {
234                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
235                         logger.debug("failed to get distribution statuses for action {}",
236                                         AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), e);
237                         return Either.right(ActionStatus.GENERAL_ERROR);
238                 }
239                 try {
240                         Result<DistributionNotificationEvent> distNotifEvent = auditAccessor
241                                         .getServiceDistributionNotify(serviceInstanceId);
242                         if (distNotifEvent != null) {
243                                 distNotifEvent.all().forEach(event -> {
244                                         event.fillFields();
245                                         resList.add(event);
246                                         logger.debug(event.toString());
247                                 });
248                         }
249                 } catch (Exception e) {
250                         BeEcompErrorManager.getInstance().logBeDaoSystemError("Get Service DistributionStatuses List");
251                         logger.debug("failed to get distribution statuses for action {}",
252                                         AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), e);
253                         return Either.right(ActionStatus.GENERAL_ERROR);
254                 }
255
256                 return Either.left(resList);
257         }
258
259         public Either<List<ResourceAdminEvent>, ActionStatus> getAuditByServiceIdAndPrevVersion(String serviceInstanceId,
260                         String prevVersion) {
261                 List<ResourceAdminEvent> remainingElements = new ArrayList<>();
262
263                 try {
264                         Result<ResourceAdminEvent> events = auditAccessor.getAuditByServiceIdAndPrevVersion(serviceInstanceId,
265                                         prevVersion);
266                         if (events == null) {
267                                 logger.debug("not found audit records for serviceInstanceId {} andprevVersion {}", serviceInstanceId,
268                                                 prevVersion);
269                                 return Either.left(remainingElements);
270                         }
271                         events.all().forEach(event -> {
272                                 event.fillFields();
273                                 remainingElements.add(event);
274                                 logger.debug(event.toString());
275                         });
276                         return Either.left(remainingElements);
277                 } catch (Exception e) {
278                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And PrevVersion");
279                         logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
280                         return Either.right(ActionStatus.GENERAL_ERROR);
281                 }
282         }
283
284         public Either<List<ResourceAdminEvent>, ActionStatus> getAuditByServiceIdAndCurrVersion(String serviceInstanceId,
285                         String currVersion) {
286                 List<ResourceAdminEvent> remainingElements = new ArrayList<>();
287
288                 try {
289                         Result<ResourceAdminEvent> events = auditAccessor.getAuditByServiceIdAndCurrVersion(serviceInstanceId,
290                                         currVersion);
291                         if (events == null) {
292                                 logger.debug("not found audit records for serviceInstanceId {} andprevVersion {}", serviceInstanceId,
293                                                 currVersion);
294                                 return Either.left(remainingElements);
295                         }
296                         events.all().forEach(event -> {
297                                 event.fillFields();
298                                 remainingElements.add(event);
299                                 logger.debug(event.toString());
300                         });
301                         return Either.left(remainingElements);
302                 } catch (Exception e) {
303                         BeEcompErrorManager.getInstance().logBeDaoSystemError("get Audit By ServiceId And CurrVersion");
304
305                         logger.debug("failed to getAuditByServiceIdAndPrevVersion ", e);
306                         return Either.right(ActionStatus.GENERAL_ERROR);
307                 }
308         }
309
310         public Either<List<ResourceAdminEvent>, ActionStatus> getArchiveAuditByServiceInstanceId(String serviceInstanceId) {
311                 List<ResourceAdminEvent> remainingElements = new ArrayList<>();
312
313                 try {
314                         Result<ResourceAdminEvent> events = auditAccessor.getArchiveAuditByServiceInstanceId(serviceInstanceId);
315                         if (events == null) {
316                                 logger.debug("not found audit records for serviceInstanceId {}", serviceInstanceId);
317                                 return Either.left(remainingElements);
318                         }
319                         events.all().forEach(event -> {
320                                 event.fillFields();
321                                 remainingElements.add(event);
322                                 logger.debug(event.toString());
323                         });
324                         return Either.left(remainingElements);
325                 } catch (Exception e) {
326                         BeEcompErrorManager.getInstance().logBeDaoSystemError("getArchiveAuditByServiceInstanceId");
327
328                         logger.debug("failed getArchiveAuditByServiceInstanceId ", e);
329                         return Either.right(ActionStatus.GENERAL_ERROR);
330                 }
331         }
332
333         public Either<List<ResourceAdminEvent>, ActionStatus> getRestoreAuditByServiceInstanceId(String serviceInstanceId) {
334                 List<ResourceAdminEvent> remainingElements = new ArrayList<>();
335
336                 try {
337                         Result<ResourceAdminEvent> events = auditAccessor.getRestoreAuditByServiceInstanceId(serviceInstanceId);
338                         if (events == null) {
339                                 logger.debug("not found audit records for serviceInstanceId {}", serviceInstanceId);
340                                 return Either.left(remainingElements);
341                         }
342                         events.all().forEach(event -> {
343                                 event.fillFields();
344                                 remainingElements.add(event);
345                                 logger.debug(event.toString());
346                         });
347                         return Either.left(remainingElements);
348                 } catch (Exception e) {
349                         BeEcompErrorManager.getInstance().logBeDaoSystemError("getRestoreAuditByServiceInstanceId");
350
351                         logger.debug("failed getRestoreAuditByServiceInstanceId ", e);
352                         return Either.right(ActionStatus.GENERAL_ERROR);
353                 }
354         }
355
356
357         /**
358          * the method checks if the given table is empty in the audit keyspace
359          * 
360          * @param tableName
361          *            the name of the table we want to check
362          * @return true if the table is empty
363          */
364         public Either<Boolean, CassandraOperationStatus> isTableEmpty(String tableName) {
365                 return super.isTableEmpty(tableName);
366         }
367
368         /**
369          * ---------for use in JUnit only--------------- the method deletes all the
370          * tables in the audit keyspace
371          * 
372          * @return the status of the last failed operation or ok if all the deletes
373          *         were successful
374          */
375         public CassandraOperationStatus deleteAllAudit() {
376                 logger.info("cleaning all audit tables.");
377                 String query = "truncate " + AuditingTypesConstants.AUDIT_KEYSPACE + ".";
378                 try {
379                         for (Table table : Table.values()) {
380                                 if (table.getTableDescription().getKeyspace().equals(AuditingTypesConstants.AUDIT_KEYSPACE)) {
381                                         logger.debug("clean Audit table:{}", table.getTableDescription().getTableName());
382                                         session.execute(query + table.getTableDescription().getTableName() + ";");
383                                         logger.debug("clean Audit table:{} was succsesfull", table.getTableDescription().getTableName());
384                                 }
385                         }
386                 } catch (Exception e) {
387                         logger.error("Failed to clean Audit", e);
388                         return CassandraOperationStatus.GENERAL_ERROR;
389                 }
390                 logger.info("clean all audit finished succsesfully.");
391                 return CassandraOperationStatus.OK;
392         }
393 }