2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.nio.charset.StandardCharsets;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.Optional;
34 import java.util.concurrent.Callable;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.Future;
38 import java.util.concurrent.TimeUnit;
39 import java.util.function.Function;
40 import java.util.stream.Collectors;
42 import javax.servlet.ServletContext;
43 import javax.servlet.http.HttpServletRequest;
45 import org.apache.commons.collections.CollectionUtils;
46 import org.apache.commons.collections.MapUtils;
47 import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
48 import org.openecomp.sdc.be.components.distribution.engine.INotificationData;
49 import org.openecomp.sdc.be.components.distribution.engine.VfModuleArtifactPayload;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
51 import org.openecomp.sdc.be.config.BeEcompErrorManager;
52 import org.openecomp.sdc.be.config.ConfigurationManager;
53 import org.openecomp.sdc.be.dao.api.ActionStatus;
54 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.GroupTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
59 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
60 import org.openecomp.sdc.be.model.ArtifactDefinition;
61 import org.openecomp.sdc.be.model.Component;
62 import org.openecomp.sdc.be.model.ComponentInstance;
63 import org.openecomp.sdc.be.model.DistributionStatusEnum;
64 import org.openecomp.sdc.be.model.DistributionTransitionEnum;
65 import org.openecomp.sdc.be.model.GroupDefinition;
66 import org.openecomp.sdc.be.model.LifecycleStateEnum;
67 import org.openecomp.sdc.be.model.Resource;
68 import org.openecomp.sdc.be.model.Service;
69 import org.openecomp.sdc.be.model.User;
70 import org.openecomp.sdc.be.model.category.CategoryDefinition;
71 import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
72 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
73 import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
74 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
75 import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
76 import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
77 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
78 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
79 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
80 import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent;
81 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
82 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
83 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
84 import org.openecomp.sdc.be.user.Role;
85 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
86 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
87 import org.openecomp.sdc.common.api.Constants;
88 import org.openecomp.sdc.common.config.EcompErrorName;
89 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
90 import org.openecomp.sdc.common.datastructure.Wrapper;
91 import org.openecomp.sdc.common.kpi.api.ASDCKpiApi;
92 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
93 import org.openecomp.sdc.common.util.ValidationUtils;
94 import org.openecomp.sdc.exception.ResponseFormat;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
97 import org.springframework.beans.factory.annotation.Autowired;
98 import org.springframework.web.context.WebApplicationContext;
100 import com.google.gson.Gson;
101 import com.google.gson.GsonBuilder;
103 import fj.data.Either;
105 @org.springframework.stereotype.Component("serviceBusinessLogic")
106 public class ServiceBusinessLogic extends ComponentBusinessLogic {
108 private static final String STATUS_SUCCESS_200 = "200";
110 private static final String STATUS_DEPLOYED = "DEPLOYED";
113 private IElementOperation elementDao;
116 private IDistributionEngine distributionEngine;
119 // private AuditingDao auditingDao;
122 private AuditCassandraDao auditCassandraDao;
125 private ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic;
128 private ICacheMangerOperation cacheManagerOperation;
130 private static Logger log = LoggerFactory.getLogger(ServiceBusinessLogic.class.getName());
131 private static final String INITIAL_VERSION = "0.1";
133 public ServiceBusinessLogic() {
134 log.debug("ServiceBusinessLogic started");
137 public Either<Service, ResponseFormat> changeServiceDistributionState(String serviceId, String state, LifecycleChangeInfoWithAction commentObj, User user) {
139 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "change Service Distribution State", false);
140 if (resp.isRight()) {
141 return Either.right(resp.right().value());
144 log.debug("check request state");
145 Either<DistributionTransitionEnum, ResponseFormat> validateEnum = validateTransitionEnum(state, user);
146 if (validateEnum.isRight()) {
147 return Either.right(validateEnum.right().value());
149 DistributionTransitionEnum distributionTransition = validateEnum.left().value();
150 AuditingActionEnum auditAction = (distributionTransition == DistributionTransitionEnum.APPROVE ? AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_APPROV : AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REJECT);
151 Either<String, ResponseFormat> commentResponse = validateComment(commentObj, user, auditAction);
152 if (commentResponse.isRight()) {
153 return Either.right(commentResponse.right().value());
155 String comment = commentResponse.left().value();
157 Either<Service, ResponseFormat> validateService = validateServiceDistributionChange(user, serviceId, auditAction, comment);
158 if (validateService.isRight()) {
159 return Either.right(validateService.right().value());
161 Service service = validateService.left().value();
162 DistributionStatusEnum initState = service.getDistributionStatus();
164 Either<User, ResponseFormat> validateUser = validateUserDistributionChange(user, service, auditAction, comment);
165 if (validateUser.isRight()) {
166 return Either.right(validateUser.right().value());
168 user = validateUser.left().value();
172 * StorageOperationStatus lockResult = graphLockOperation.lockComponent(serviceId, NodeTypeEnum.Service); if (!lockResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.
173 * BeFailedLockObjectError, "ChangeServiceDistributionState"); log.debug("Failed to lock service {} error - {}", serviceId, lockResult); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR,
174 * service.getVersion(), service.getServiceName());
176 * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(componentsUtils.getResponseFormat(ActionStatus. GENERAL_ERROR)); }
178 Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "ChangeServiceDistributionState");
179 if (lockResult.isRight()) {
180 ResponseFormat responseFormat = lockResult.right().value();
181 createAudit(user, auditAction, comment, service, responseFormat);
182 return Either.right(responseFormat);
187 DistributionStatusEnum newState;
188 if (distributionTransition == DistributionTransitionEnum.APPROVE) {
189 newState = DistributionStatusEnum.DISTRIBUTION_APPROVED;
191 newState = DistributionStatusEnum.DISTRIBUTION_REJECTED;
193 Either<Service, StorageOperationStatus> result = serviceOperation.updateDestributionStatus(service, user, newState);
194 if (result.isRight()) {
195 titanGenericDao.rollback();
196 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "ChangeServiceDistributionState");
197 BeEcompErrorManager.getInstance().logBeSystemError("ChangeServiceDistributionState");
198 log.debug("service {} is change destribuation status failed", service.getUniqueId());
199 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, service.getVersion(), service.getName());
200 createAudit(user, auditAction, comment, service, responseFormat);
201 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
203 titanGenericDao.commit();
204 Service updatedService = result.left().value();
205 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
206 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
207 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, updatedService.getDistributionStatus().name());
208 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, initState.name());
209 createAudit(user, auditAction, comment, updatedService, responseFormat, auditingFields);
210 return Either.left(result.left().value());
213 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
218 public Either<List<Map<String, Object>>, ResponseFormat> getComponentAuditRecords(String componentVersion, String componentUUID, String userId) {
219 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Component Audit Records", false);
220 if (resp.isRight()) {
221 return Either.right(resp.right().value());
223 Either<List<Map<String, Object>>, ActionStatus> result;
227 if (componentVersion.endsWith(".0")) {
228 Either<List<ResourceAdminEvent>, ActionStatus> eitherAuditingForCertified = auditCassandraDao.getByServiceInstanceId(componentUUID);
229 if (eitherAuditingForCertified.isLeft()) {
230 result = Either.left(getAuditingFieldsList(eitherAuditingForCertified.left().value()));
232 result = Either.right(eitherAuditingForCertified.right().value());
235 // Uncertified Version
237 result = getAuditRecordsForUncertifiedComponent(componentUUID, componentVersion);
239 } catch (Exception e) {
240 log.debug("get Audit Records failed with exception {}", e);
241 result = Either.right(ActionStatus.GENERAL_ERROR);
244 if (result.isRight()) {
245 return Either.right(componentsUtils.getResponseFormat(result.right().value()));
247 return Either.left(result.left().value());
252 private Either<List<Map<String, Object>>, ActionStatus> getAuditRecordsForUncertifiedComponent(String componentUUID, String componentVersion) {
254 Either<List<ResourceAdminEvent>, ActionStatus> eitherprevVerAudit = auditCassandraDao.getAuditByServiceIdAndPrevVersion(componentUUID, componentVersion);
256 if (eitherprevVerAudit.isRight()) {
257 return Either.right(eitherprevVerAudit.right().value());
261 Either<List<ResourceAdminEvent>, ActionStatus> eitherCurrVerAudit = auditCassandraDao.getAuditByServiceIdAndCurrVersion(componentUUID, componentVersion);
262 if (eitherCurrVerAudit.isRight()) {
263 return Either.right(eitherCurrVerAudit.right().value());
266 List<Map<String, Object>> prevVerAuditList = getAuditingFieldsList(eitherprevVerAudit.left().value());
267 List<Map<String, Object>> currVerAuditList = getAuditingFieldsList(eitherCurrVerAudit.left().value());
269 List<Map<String, Object>> duplicateElements = new ArrayList<Map<String, Object>>();
270 duplicateElements.addAll(prevVerAuditList);
271 duplicateElements.retainAll(currVerAuditList);
273 List<Map<String, Object>> joinedNonDuplicatedList = new ArrayList<Map<String, Object>>();
274 joinedNonDuplicatedList.addAll(prevVerAuditList);
275 joinedNonDuplicatedList.removeAll(duplicateElements);
276 joinedNonDuplicatedList.addAll(currVerAuditList);
278 return Either.left(joinedNonDuplicatedList);
281 private List<Map<String, Object>> getAuditingFieldsList(List<? extends AuditingGenericEvent> prevVerAuditList) {
283 List<Map<String, Object>> prevVerAudit = new ArrayList<Map<String, Object>>();
284 for (AuditingGenericEvent auditEvent : prevVerAuditList) {
285 auditEvent.fillFields();
286 prevVerAudit.add(auditEvent.getFields());
297 * - modifier data (userId)
298 * @return Either<Service, responseFormat>
300 public Either<Service, ResponseFormat> createService(Service service, User user) {
303 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Create Service", service, AuditingActionEnum.CREATE_RESOURCE, false);
304 if (eitherCreator.isRight()) {
305 return Either.right(eitherCreator.right().value());
307 user = eitherCreator.left().value();
309 // validate user role
310 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, new ArrayList<Role>(), AuditingActionEnum.CREATE_RESOURCE, null);
311 if (validateRes.isRight()) {
312 return Either.right(validateRes.right().value());
314 service.setCreatorUserId(user.getUserId());
316 // warn on overridden fields
317 checkFieldsForOverideAttampt(service);
319 log.debug("enrich service with version and state");
320 service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
321 service.setVersion(INITIAL_VERSION);
322 service.setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
324 Either<Service, ResponseFormat> createServiceResponse = validateServiceBeforeCreate(service, user, AuditingActionEnum.CREATE_RESOURCE);
325 if (createServiceResponse.isRight()) {
326 return createServiceResponse;
328 return createServiceByDao(service, AuditingActionEnum.CREATE_RESOURCE, serviceOperation, user);
331 private void checkFieldsForOverideAttampt(Service service) {
332 checkComponentFieldsForOverrideAttempt(service);
333 if ((service.getDistributionStatus() != null)) {
334 log.info("Distribution Status cannot be defined by user. This field will be overridden by the application");
338 private Either<Service, ResponseFormat> createServiceByDao(Service service, AuditingActionEnum actionEnum, IServiceOperation dataModel, User user) {
339 log.debug("send service {} to dao for create", service.getComponentMetadataDefinition().getMetadataDataDefinition().getName());
341 Either<Boolean, ResponseFormat> lockResult = lockComponentByName(service.getSystemName(), service, "Create Service");
342 if (lockResult.isRight()) {
343 ResponseFormat responseFormat = lockResult.right().value();
344 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
345 return Either.right(responseFormat);
348 log.debug("System name locked is {}, status = {}", service.getSystemName(), lockResult);
352 createMandatoryArtifactsData(service, user);
353 createServiceApiArtifactsData(service, user);
354 setToscaArtifactsPlaceHolders(service, user);
356 Either<Service, StorageOperationStatus> dataModelResponse = dataModel.createService(service);
358 // service created successfully!!!
359 if (dataModelResponse.isLeft()) {
360 log.debug("Service created successfully!!!");
361 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
362 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
363 ASDCKpiApi.countCreatedServicesKPI();
365 Service createdService = dataModelResponse.left().value();
366 // //add service to cache
367 // cacheManagerOperation.updateComponentInCache(createdService.getUniqueId(),
368 // createdService.getLastUpdateDate(), NodeTypeEnum.Service);
370 return Either.left(dataModelResponse.left().value());
373 ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()), service, ComponentTypeEnum.SERVICE);
374 log.debug("audit before sending response");
375 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
376 return Either.right(responseFormat);
379 graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), NodeTypeEnum.Service);
383 private void createServiceApiArtifactsData(Service service, User user) {
384 // create mandatory artifacts
386 // TODO it must be removed after that artifact uniqueId creation will be
387 // moved to ArtifactOperation
388 // String serviceUniqueId =
389 // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
390 // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
391 String serviceUniqueId = service.getUniqueId();
392 Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
393 if (artifactMap == null)
394 artifactMap = new HashMap<String, ArtifactDefinition>();
396 Map<String, Object> serviceApiArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceApiArtifacts();
397 List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
399 List<CategoryDefinition> categories = service.getCategories();
400 boolean isCreateArtifact = true;
401 if (categories != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
402 for (String exlude : exludeServiceCategory) {
403 if (exlude.equalsIgnoreCase(categories.get(0).getName())) {
404 isCreateArtifact = false;
411 if (serviceApiArtifacts != null && isCreateArtifact) {
412 Set<String> keys = serviceApiArtifacts.keySet();
413 for (String serviceApiArtifactName : keys) {
414 Map<String, Object> artifactInfoMap = (Map<String, Object>) serviceApiArtifacts.get(serviceApiArtifactName);
415 ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, serviceApiArtifactName, artifactInfoMap, user, true);
416 artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.SERVICE_API);
417 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
420 service.setArtifacts(artifactMap);
424 private Either<Service, ResponseFormat> validateServiceBeforeCreate(Service service, User user, AuditingActionEnum actionEnum) {
426 Either<Boolean, ResponseFormat> validationResponse = validateServiceFieldsBeforeCreate(user, service, actionEnum);
427 if (validationResponse.isRight()) {
428 return Either.right(validationResponse.right().value());
430 service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
431 service.setContactId(service.getContactId().toLowerCase());
433 // Generate invariant UUID - must be here and not in operation since it
434 // should stay constant during clone
435 String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
436 service.setInvariantUUID(invariantUUID);
438 return Either.left(service);
441 private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) {
442 Either<Boolean, ResponseFormat> componentsFieldsValidation = validateComponentFieldsBeforeCreate(user, service, actionEnum);
443 if (componentsFieldsValidation.isRight()) {
444 return componentsFieldsValidation;
447 // validate service name uniqueness
448 log.debug("validate service name uniqueness");
449 Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
450 if (serviceNameUniquenessValidation.isRight()) {
451 return serviceNameUniquenessValidation;
455 log.debug("validate category");
456 Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
457 if (categoryValidation.isRight()) {
458 return categoryValidation;
461 log.debug("validate projectName");
462 Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
463 if (projectCodeValidation.isRight()) {
464 return projectCodeValidation;
467 return Either.left(true);
471 private Either<Boolean, ResponseFormat> validateServiceCategory(User user, Service service, AuditingActionEnum actionEnum) {
472 log.debug("validate Service category");
474 if (service.getCategories() == null || service.getCategories().size() == 0) {
475 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
476 componentsUtils.auditComponentAdmin(errorResponse, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
477 return Either.right(errorResponse);
480 Either<Boolean, ResponseFormat> validatCategory = validateServiceCategory(service.getCategories());
481 if (validatCategory.isRight()) {
482 ResponseFormat responseFormat = validatCategory.right().value();
483 componentsUtils.auditComponentAdmin(responseFormat, user, service, "", "", actionEnum, ComponentTypeEnum.SERVICE);
484 return Either.right(responseFormat);
487 return Either.left(true);
490 public Either<Map<String, Boolean>, ResponseFormat> validateServiceNameExists(String serviceName, String userId) {
492 Either<User, ResponseFormat> resp = validateUserExists(userId, "validate Service Name Exists", false);
493 if (resp.isRight()) {
494 return Either.right(resp.right().value());
497 Either<Boolean, StorageOperationStatus> dataModelResponse = serviceOperation.validateServiceNameExists(serviceName);
499 if (dataModelResponse.isLeft()) {
500 Map<String, Boolean> result = new HashMap<>();
501 result.put("isValid", dataModelResponse.left().value());
502 log.debug("validation was successfully performed.");
503 return Either.left(result);
506 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(dataModelResponse.right().value()));
508 return Either.right(responseFormat);
511 public void setElementDao(IElementOperation elementDao) {
512 this.elementDao = elementDao;
515 public void setServiceOperation(ServiceOperation serviceOperation) {
516 this.serviceOperation = serviceOperation;
519 public void setCassandraAuditingDao(AuditCassandraDao auditingDao) {
520 this.auditCassandraDao = auditingDao;
524 * public void setUserAdmin(UserAdminBuisinessLogic userAdmin) { this.userAdmin = userAdmin; }
526 * public void setComponentsUtils(ComponentsUtils componentsUtils) { this.componentsUtils = componentsUtils; }
528 * public void setGraphLockOperation(IGraphLockOperation graphLockOperation) { this.graphLockOperation = graphLockOperation; }
531 public ArtifactsBusinessLogic getArtifactBl() {
532 return artifactsBusinessLogic;
535 public void setArtifactBl(ArtifactsBusinessLogic artifactBl) {
536 this.artifactsBusinessLogic = artifactBl;
539 public Either<Service, ResponseFormat> updateServiceMetadata(String serviceId, Service serviceUpdate, User user) {
540 Either<User, ResponseFormat> eitherCreator = validateUser(user, "updateServiceMetadata", serviceUpdate, null, false);
541 if (eitherCreator.isRight()) {
542 return Either.right(eitherCreator.right().value());
544 user = eitherCreator.left().value();
546 // validate user role
547 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, serviceUpdate, new ArrayList<Role>(), null, null);
548 if (validateRes.isRight()) {
549 return Either.right(validateRes.right().value());
552 Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
553 if (storageStatus.isRight()) {
554 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), ""));
557 Service currentService = storageStatus.left().value();
559 if (!ComponentValidationUtils.canWorkOnService(currentService.getUniqueId(), serviceOperation, user.getUserId())) {
560 log.info("Restricted operation for user {} on service {}", user.getUserId(), currentService.getCreatorUserId());
561 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
564 Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate);
565 if (validationRsponse.isRight()) {
566 log.info("service update metadata: validations field.");
567 return validationRsponse;
569 Service serviceToUpdate = validationRsponse.left().value();
572 Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, currentService, "Update Service Metadata");
573 if (lockResult.isRight()) {
574 return Either.right(lockResult.right().value());
577 Either<Service, StorageOperationStatus> updateResponse = serviceOperation.updateService(serviceToUpdate, true);
578 if (updateResponse.isRight()) {
579 titanGenericDao.rollback();
580 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Update Service Metadata");
581 BeEcompErrorManager.getInstance().logBeSystemError("Update Service Metadata");
582 log.debug("failed to update sevice {}", serviceToUpdate.getUniqueId());
583 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
585 titanGenericDao.commit();
586 return Either.left(updateResponse.left().value());
588 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
592 private Either<Service, ResponseFormat> validateAndUpdateServiceMetadata(User user, Service currentService, Service serviceUpdate) {
594 boolean hasBeenCertified = ValidationUtils.hasBeenCertified(currentService.getVersion());
595 Either<Boolean, ResponseFormat> response = validateAndUpdateCategory(user, currentService, serviceUpdate, hasBeenCertified, null);
596 if (response.isRight()) {
597 ResponseFormat errorResponse = response.right().value();
598 return Either.right(errorResponse);
601 String creatorUserIdUpdated = serviceUpdate.getCreatorUserId();
602 String creatorUserIdCurrent = currentService.getCreatorUserId();
603 if (creatorUserIdUpdated != null && !creatorUserIdCurrent.equals(creatorUserIdUpdated)) {
604 log.info("update srvice: recived request to update creatorUserId to {} the field is not updatable ignoring.", creatorUserIdUpdated);
607 String creatorFullNameUpdated = serviceUpdate.getCreatorFullName();
608 String creatorFullNameCurrent = currentService.getCreatorFullName();
609 if (creatorFullNameUpdated != null && !creatorFullNameCurrent.equals(creatorFullNameUpdated)) {
610 log.info("update srvice: recived request to update creatorFullName to {} the field is not updatable ignoring.", creatorFullNameUpdated);
613 String lastUpdaterUserIdUpdated = serviceUpdate.getLastUpdaterUserId();
614 String lastUpdaterUserIdCurrent = currentService.getLastUpdaterUserId();
615 if (lastUpdaterUserIdUpdated != null && !lastUpdaterUserIdCurrent.equals(lastUpdaterUserIdUpdated)) {
616 log.info("update srvice: recived request to update lastUpdaterUserId to {} the field is not updatable ignoring.", lastUpdaterUserIdUpdated);
619 String lastUpdaterFullNameUpdated = serviceUpdate.getLastUpdaterFullName();
620 String lastUpdaterFullNameCurrent = currentService.getLastUpdaterFullName();
621 if (lastUpdaterFullNameUpdated != null && !lastUpdaterFullNameCurrent.equals(lastUpdaterFullNameUpdated)) {
622 log.info("update srvice: recived request to update lastUpdaterFullName to {} the field is not updatable ignoring.", lastUpdaterFullNameUpdated );
625 response = validateAndUpdateServiceName(user, currentService, serviceUpdate, hasBeenCertified, null);
626 if (response.isRight()) {
627 ResponseFormat errorResponse = response.right().value();
628 return Either.right(errorResponse);
631 DistributionStatusEnum distributionStatusUpdated = serviceUpdate.getDistributionStatus();
632 DistributionStatusEnum distributionStatusCurrent = currentService.getDistributionStatus();
633 if (distributionStatusUpdated != null && !distributionStatusUpdated.name().equals((distributionStatusCurrent != null ? distributionStatusCurrent.name() : null))) {
634 log.info("update srvice: recived request to update distributionStatus to {} the field is not updatable ignoring.", distributionStatusUpdated);
637 if (serviceUpdate.getProjectCode() != null) {
638 response = validateAndUpdateProjectCode(user, currentService, serviceUpdate, null);
639 if (response.isRight()) {
640 ResponseFormat errorResponse = response.right().value();
641 return Either.right(errorResponse);
645 response = validateAndUpdateIcon(user, currentService, serviceUpdate, hasBeenCertified, null);
646 if (response.isRight()) {
647 ResponseFormat errorResponse = response.right().value();
648 return Either.right(errorResponse);
651 Long creationDateUpdated = serviceUpdate.getCreationDate();
652 Long creationDateCurrent = currentService.getCreationDate();
653 if (creationDateUpdated != null && !creationDateCurrent.equals(creationDateUpdated)) {
654 log.info("update srvice: recived request to update creationDate to {} the field is not updatable ignoring.", creationDateUpdated);
657 String versionUpdated = serviceUpdate.getVersion();
658 String versionCurrent = currentService.getVersion();
659 if (versionUpdated != null && !versionCurrent.equals(versionUpdated)) {
660 log.info("update srvice: recived request to update version to {} the field is not updatable ignoring.", versionUpdated);
663 response = validateAndUpdateDescription(user, currentService, serviceUpdate, hasBeenCertified, null);
664 if (response.isRight()) {
665 ResponseFormat errorResponse = response.right().value();
666 return Either.right(errorResponse);
669 response = validateAndUpdateTags(user, currentService, serviceUpdate, hasBeenCertified, null);
670 if (response.isRight()) {
671 ResponseFormat errorResponse = response.right().value();
672 return Either.right(errorResponse);
675 response = validateAndUpdateContactId(user, currentService, serviceUpdate, null);
676 if (response.isRight()) {
677 ResponseFormat errorResponse = response.right().value();
678 return Either.right(errorResponse);
681 Long lastUpdateDateUpdated = serviceUpdate.getLastUpdateDate();
682 Long lastUpdateDateCurrent = currentService.getLastUpdateDate();
683 if (lastUpdateDateUpdated != null && !lastUpdateDateCurrent.equals(lastUpdateDateUpdated)) {
684 log.info("update srvice: recived request to update lastUpdateDate to {} the field is not updatable ignoring.", lastUpdateDateUpdated);
687 LifecycleStateEnum lifecycleStateUpdated = serviceUpdate.getLifecycleState();
688 LifecycleStateEnum lifecycleStateCurrent = currentService.getLifecycleState();
689 if (lifecycleStateUpdated != null && !lifecycleStateCurrent.name().equals(lifecycleStateUpdated.name())) {
690 log.info("update srvice: recived request to update lifecycleState to {} the field is not updatable ignoring.", lifecycleStateUpdated);
693 Boolean isHighestVersionUpdated = serviceUpdate.isHighestVersion();
694 Boolean isHighestVersionCurrent = currentService.isHighestVersion();
695 if (isHighestVersionUpdated != null && !isHighestVersionCurrent.equals(isHighestVersionUpdated)) {
696 log.info("update srvice: recived request to update isHighestVersion to {} the field is not updatable ignoring.", isHighestVersionUpdated);
699 String uuidUpdated = serviceUpdate.getUUID();
700 String uuidCurrent = currentService.getUUID();
701 if (!uuidCurrent.equals(uuidUpdated)) {
702 log.info("update srvice: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated);
705 String currentInvariantUuid = currentService.getInvariantUUID();
706 String updatedInvariantUuid = serviceUpdate.getInvariantUUID();
708 if ((updatedInvariantUuid != null) && (!updatedInvariantUuid.equals(currentInvariantUuid))) {
709 log.warn("Product invariant UUID is automatically set and cannot be updated");
710 serviceUpdate.setInvariantUUID(currentInvariantUuid);
712 return Either.left(currentService);
716 private Either<Boolean, ResponseFormat> validateAndUpdateContactId(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
717 String contactIdUpdated = serviceUpdate.getContactId();
718 String contactIdCurrent = currentService.getContactId();
719 if (!contactIdCurrent.equals(contactIdUpdated)) {
720 Either<Boolean, ResponseFormat> validatContactId = validateContactId(user, serviceUpdate, audatingAction);
721 if (validatContactId.isRight()) {
722 ResponseFormat errorRespons = validatContactId.right().value();
723 return Either.right(errorRespons);
725 currentService.setContactId(contactIdUpdated.toLowerCase());
727 return Either.left(true);
730 private Either<Boolean, ResponseFormat> validateAndUpdateTags(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
731 List<String> tagsUpdated = serviceUpdate.getTags();
732 List<String> tagsCurrent = currentService.getTags();
733 if (tagsUpdated == null || tagsUpdated.isEmpty()) {
734 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_TAGS);
735 componentsUtils.auditComponentAdmin(responseFormat, user, serviceUpdate, "", "", audatingAction, ComponentTypeEnum.SERVICE);
736 return Either.right(responseFormat);
739 if (!(tagsCurrent.containsAll(tagsUpdated) && tagsUpdated.containsAll(tagsCurrent))) {
740 Either<Boolean, ResponseFormat> validatResponse = validateTagsListAndRemoveDuplicates(user, serviceUpdate, audatingAction);
741 if (validatResponse.isRight()) {
742 ResponseFormat errorRespons = validatResponse.right().value();
743 return Either.right(errorRespons);
745 currentService.setTags(tagsUpdated);
747 return Either.left(true);
750 private Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
751 String descriptionUpdated = serviceUpdate.getDescription();
752 String descriptionCurrent = currentService.getDescription();
753 if (!descriptionCurrent.equals(descriptionUpdated)) {
754 Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, serviceUpdate, audatingAction);
755 if (validateDescriptionResponse.isRight()) {
756 ResponseFormat errorRespons = validateDescriptionResponse.right().value();
757 return Either.right(errorRespons);
759 currentService.setDescription(serviceUpdate.getDescription());
761 return Either.left(true);
764 private Either<Boolean, ResponseFormat> validateAndUpdateProjectCode(User user, Service currentService, Service serviceUpdate, AuditingActionEnum audatingAction) {
765 String projectCodeUpdated = serviceUpdate.getProjectCode();
766 String projectCodeCurrent = currentService.getProjectCode();
767 if (!projectCodeCurrent.equals(projectCodeUpdated)) {
768 Either<Boolean, ResponseFormat> validatProjectCodeResponse = validateProjectCode(user, serviceUpdate, audatingAction);
769 if (validatProjectCodeResponse.isRight()) {
770 ResponseFormat errorRespons = validatProjectCodeResponse.right().value();
771 return Either.right(errorRespons);
773 currentService.setProjectCode(projectCodeUpdated);
775 return Either.left(true);
778 private Either<Boolean, ResponseFormat> validateAndUpdateIcon(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
779 String iconUpdated = serviceUpdate.getIcon();
780 String iconCurrent = currentService.getIcon();
781 if (!iconCurrent.equals(iconUpdated)) {
782 if (!hasBeenCertified) {
783 Either<Boolean, ResponseFormat> validatIconResponse = validateIcon(user, serviceUpdate, audatingAction);
784 if (validatIconResponse.isRight()) {
785 ResponseFormat errorRespons = validatIconResponse.right().value();
786 return Either.right(errorRespons);
788 currentService.setIcon(iconUpdated);
790 log.info("icon {} cannot be updated once the service has been certified once.", iconUpdated);
791 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED);
792 return Either.right(errorResponse);
795 return Either.left(true);
798 private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
799 String serviceNameUpdated = serviceUpdate.getName();
800 String serviceNameCurrent = currentService.getName();
801 if (!serviceNameCurrent.equals(serviceNameUpdated)) {
802 if (!hasBeenCertified) {
803 Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, audatingAction);
804 if (validatServiceNameResponse.isRight()) {
805 ResponseFormat errorRespons = validatServiceNameResponse.right().value();
806 return Either.right(errorRespons);
809 Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, audatingAction);
810 if (serviceNameUniquenessValidation.isRight()) {
811 return serviceNameUniquenessValidation;
813 currentService.setName(serviceNameUpdated);
814 currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(serviceNameUpdated));
815 currentService.getComponentMetadataDefinition().getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(serviceNameUpdated));
818 log.info("service name {} cannot be updated once the service has been certified once.", serviceNameUpdated);
819 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED);
820 return Either.right(errorResponse);
823 return Either.left(true);
826 private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
827 List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
828 List<CategoryDefinition> categoryCurrent = currentService.getCategories();
829 Either<Boolean, ResponseFormat> validatCategoryResponse = validateServiceCategory(user, serviceUpdate, audatingAction);
830 if (validatCategoryResponse.isRight()) {
831 ResponseFormat errorRespons = validatCategoryResponse.right().value();
832 return Either.right(errorRespons);
834 if (!categoryCurrent.get(0).getName().equals(categoryUpdated.get(0).getName())) {
835 if (!hasBeenCertified) {
836 currentService.setCategories(categoryUpdated);
838 log.info("category {} cannot be updated once the service has been certified once.", categoryUpdated);
839 ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED);
840 return Either.right(errorResponse);
843 return Either.left(true);
847 public Either<Boolean, ResponseFormat> validateServiceCategory(List<CategoryDefinition> list) {
849 if (list.size() > 1) {
850 log.debug("Must be only one category for service");
851 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_TOO_MUCH_CATEGORIES, ComponentTypeEnum.SERVICE.getValue());
852 return Either.right(responseFormat);
854 CategoryDefinition category = list.get(0);
855 if (category.getSubcategories() != null) {
856 log.debug("Subcategories cannot be defined for service");
857 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_CANNOT_CONTAIN_SUBCATEGORY);
858 return Either.right(responseFormat);
860 if (!ValidationUtils.validateStringNotEmpty(category.getName())) {
861 log.debug("Resource category is empty");
862 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
863 return Either.right(responseFormat);
866 log.debug("validating service category {} against valid categories list", list);
867 Either<List<CategoryDefinition>, ActionStatus> categorys = elementDao.getAllServiceCategories();
868 if (categorys.isRight()) {
869 log.debug("failed to retrive service categories from Titan");
870 ResponseFormat responseFormat = componentsUtils.getResponseFormat(categorys.right().value());
871 return Either.right(responseFormat);
873 List<CategoryDefinition> categoryList = categorys.left().value();
874 for (CategoryDefinition value : categoryList) {
875 if (value.getName().equals(category.getName())) {
876 return Either.left(true);
879 log.debug("Category {} is not part of service category group. Service category valid values are {}", list, categoryList);
880 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue()));
882 return Either.left(false);
885 public ResponseFormat deleteService(String serviceId, User user) {
886 ResponseFormat responseFormat;
887 String ecompErrorContext = "delete service";
889 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
890 if (eitherCreator.isRight()) {
891 return eitherCreator.right().value();
893 user = eitherCreator.left().value();
895 Either<Service, StorageOperationStatus> serviceStatus = serviceOperation.getService(serviceId);
896 if (serviceStatus.isRight()) {
897 log.debug("failed to get service {}", serviceId);
898 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceStatus.right().value()), "");
901 Service service = serviceStatus.left().value();
903 StorageOperationStatus result = StorageOperationStatus.OK;
904 Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
905 if (lockResult.isRight()) {
906 result = StorageOperationStatus.GENERAL_ERROR;
907 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
912 result = markComponentToDelete(service);
913 if (result.equals(StorageOperationStatus.OK)) {
914 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
916 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
917 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
919 return responseFormat;
922 if (result == null || !result.equals(StorageOperationStatus.OK)) {
923 log.warn("operation failed. do rollback");
924 BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
925 titanGenericDao.rollback();
927 log.debug("operation success. do commit");
928 titanGenericDao.commit();
930 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
934 public ResponseFormat deleteServiceByNameAndVersion(String serviceName, String version, User user) {
935 ResponseFormat responseFormat;
936 String ecompErrorContext = "delete service";
937 Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
938 if (validateEmptyResult.isRight()) {
939 return validateEmptyResult.right().value();
942 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
943 if (eitherCreator.isRight()) {
944 return eitherCreator.right().value();
946 user = eitherCreator.left().value();
948 Either<Service, ResponseFormat> getResult = getServiceByNameAndVersion(serviceName, version, user.getUserId());
949 if (getResult.isRight()) {
950 return getResult.right().value();
952 Service service = getResult.left().value();
954 StorageOperationStatus result = StorageOperationStatus.OK;
955 Either<Boolean, ResponseFormat> lockResult = lockComponent(service, "Mark service to delete");
956 if (lockResult.isRight()) {
957 result = StorageOperationStatus.GENERAL_ERROR;
958 return componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
962 result = markComponentToDelete(service);
963 if (result.equals(StorageOperationStatus.OK)) {
964 responseFormat = componentsUtils.getResponseFormat(ActionStatus.NO_CONTENT);
966 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(result);
967 responseFormat = componentsUtils.getResponseFormatByResource(actionStatus, service.getName());
969 return responseFormat;
972 if (result == null || !result.equals(StorageOperationStatus.OK)) {
973 log.warn("operation failed. do rollback");
974 BeEcompErrorManager.getInstance().logBeSystemError("Delete Service");
975 titanGenericDao.rollback();
977 log.debug("operation success. do commit");
978 titanGenericDao.commit();
980 graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service);
984 public Either<Service, ResponseFormat> getService(String serviceId, User user) {
985 String ecompErrorContext = "Get service";
986 Either<User, ResponseFormat> validateEmptyResult = validateUserNotEmpty(user, ecompErrorContext);
987 if (validateEmptyResult.isRight()) {
988 return Either.right(validateEmptyResult.right().value());
991 Either<User, ResponseFormat> eitherCreator = validateUserExists(user, ecompErrorContext, false);
992 if (eitherCreator.isRight()) {
993 return Either.right(eitherCreator.right().value());
995 user = eitherCreator.left().value();
997 Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
998 if (storageStatus.isRight()) {
999 log.debug("failed to get service by id {}", serviceId);
1000 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
1002 // Service service =
1003 // createServiceApiArtifactLIst(storageStatus.left().value());
1004 Service service = storageStatus.left().value();
1005 return Either.left(service);
1008 public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
1009 Either<User, ResponseFormat> resp = validateUserExists(userId, "get Service By Name And Version", false);
1010 if (resp.isRight()) {
1011 return Either.right(resp.right().value());
1013 Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getServiceByNameAndVersion(serviceName, serviceVersion, null, false);
1014 if (storageStatus.isRight()) {
1015 log.debug("failed to get service by name {} and version {}", serviceName, serviceVersion);
1016 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceName));
1018 Service service = storageStatus.left().value();
1019 return Either.left(service);
1022 private void createMandatoryArtifactsData(Service service, User user) {
1023 // create mandatory artifacts
1025 // TODO it must be removed after that artifact uniqueId creation will be
1026 // moved to ArtifactOperation
1027 // String serviceUniqueId =
1028 // UniqueIdBuilder.buildServiceUniqueId(service.getComponentMetadataDefinition().getMetadataDataDefinition().getName(),
1029 // service.getComponentMetadataDefinition().getMetadataDataDefinition().getVersion());
1030 String serviceUniqueId = service.getUniqueId();
1031 Map<String, ArtifactDefinition> artifactMap = service.getArtifacts();
1032 if (artifactMap == null)
1033 artifactMap = new HashMap<String, ArtifactDefinition>();
1035 Map<String, Object> informationalServiceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalServiceArtifacts();
1036 List<String> exludeServiceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeServiceCategory();
1038 String category = service.getCategories().get(0).getName();
1039 boolean isCreateArtifact = true;
1040 if (category != null && exludeServiceCategory != null && !exludeServiceCategory.isEmpty()) {
1041 for (String exlude : exludeServiceCategory) {
1042 if (exlude.equalsIgnoreCase(category)) {
1043 isCreateArtifact = false;
1050 if (informationalServiceArtifacts != null && isCreateArtifact) {
1051 Set<String> keys = informationalServiceArtifacts.keySet();
1052 for (String informationalServiceArtifactName : keys) {
1053 Map<String, Object> artifactInfoMap = (Map<String, Object>) informationalServiceArtifacts.get(informationalServiceArtifactName);
1054 ArtifactDefinition artifactDefinition = createArtifactDefinition(serviceUniqueId, informationalServiceArtifactName, artifactInfoMap, user, false);
1055 artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
1059 service.setArtifacts(artifactMap);
1063 private ArtifactDefinition createArtifactDefinition(String serviceId, String logicalName, Map<String, Object> artifactInfoMap, User user, Boolean isServiceApi) {
1065 ArtifactDefinition artifactInfo = artifactsBusinessLogic.createArtifactPlaceHolderInfo(serviceId, logicalName, artifactInfoMap, user, ArtifactGroupTypeEnum.INFORMATIONAL);
1068 artifactInfo.setMandatory(false);
1069 artifactInfo.setServiceApi(true);
1071 return artifactInfo;
1074 private Either<DistributionTransitionEnum, ResponseFormat> validateTransitionEnum(String distributionTransition, User user) {
1075 DistributionTransitionEnum transitionEnum = null;
1077 transitionEnum = DistributionTransitionEnum.getFromDisplayName(distributionTransition);
1078 if (transitionEnum == null) {
1079 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change Service Distribution");
1080 BeEcompErrorManager.getInstance().logBeSystemError("Change Service Distribution");
1081 log.info("state operation is not valid. operations allowed are: {}", DistributionTransitionEnum.valuesAsString());
1082 ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1083 return Either.right(error);
1086 return Either.left(transitionEnum);
1089 private Either<String, ResponseFormat> validateComment(LifecycleChangeInfoWithAction comment, User user, AuditingActionEnum auditAction) {
1090 String data = comment.getUserRemarks();
1092 if (data == null || data.trim().isEmpty()) {
1093 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution");
1094 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
1095 log.debug("user comment cannot be empty or null.");
1096 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1098 data = ValidationUtils.removeNoneUtf8Chars(data);
1099 data = ValidationUtils.removeHtmlTags(data);
1100 data = ValidationUtils.normaliseWhitespace(data);
1101 data = ValidationUtils.stripOctets(data);
1103 if (!ValidationUtils.validateLength(data, ValidationUtils.COMMENT_MAX_LENGTH)) {
1104 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidJsonInput, "Change Service Distribution");
1105 BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Change Service Distribution");
1106 log.debug("user comment exceeds limit.");
1107 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, "comment", String.valueOf(ValidationUtils.COMMENT_MAX_LENGTH)));
1109 if (!ValidationUtils.validateIsEnglish(data)) {
1110 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1112 return Either.left(data);
1115 private Either<Service, ResponseFormat> validateServiceDistributionChange(User user, String serviceId, AuditingActionEnum auditAction, String comment) {
1116 Either<Service, StorageOperationStatus> storageStatus = serviceOperation.getService(serviceId);
1117 if (storageStatus.isRight()) {
1118 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceId);
1119 createAudit(user, auditAction, comment, responseFormat);
1120 return Either.right(responseFormat);
1122 Service service = storageStatus.left().value();
1124 if (service.getLifecycleState() != LifecycleStateEnum.CERTIFIED) {
1125 log.info("service {} is not available for distribution. Should be in certified state", service.getUniqueId());
1126 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, service.getVersion(), service.getName());
1127 createAudit(user, auditAction, comment, service, responseFormat);
1128 return Either.right(responseFormat);
1130 return Either.left(service);
1133 private Either<User, ResponseFormat> validateUserDistributionChange(User user, Service service, AuditingActionEnum auditAction, String comment) {
1134 log.debug("get user from DB");
1136 * Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId());s if (eitherCreator.isRight() || eitherCreator.left().value() == null) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeUserMissingError,
1137 * "Activate Distribution", user.getUserId()); log. debug("changeServiceDistributionState method - user is not listed. userId=" + user.getUserId()); ResponseFormat responseFormat =
1138 * componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND); createAudit(user, auditAction, comment, responseFormat); return Either.right(responseFormat); } user = eitherCreator.left().value(); log.debug("validate user role"); if
1139 * (!validateUserTemp(user, Role.ADMIN, Role.GOVERNOR)) { log.info("role {} is not allowed to perform this action", user.getRole()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
1140 * createAudit(user, auditAction, comment, service, responseFormat); return Either.right(responseFormat); }
1143 Either<User, ResponseFormat> eitherCreator = validateUser(user, "Activate Distribution", service, auditAction, false);
1144 if (eitherCreator.isRight()) {
1145 return Either.right(eitherCreator.right().value());
1147 user = eitherCreator.left().value();
1149 // validate user role
1150 List<Role> roles = new ArrayList<>();
1151 roles.add(Role.ADMIN);
1152 roles.add(Role.GOVERNOR);
1153 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, comment);
1154 if (validateRes.isRight()) {
1155 return Either.right(validateRes.right().value());
1157 return Either.left(user);
1160 private void createAudit(User user, AuditingActionEnum auditAction, String comment, ResponseFormat responseFormat) {
1161 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1163 createAudit(user, auditAction, comment, null, responseFormat, auditingFields);
1166 private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat) {
1167 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1168 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, component.getDistributionStatus().name());
1169 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, component.getDistributionStatus().name());
1170 createAudit(user, auditAction, comment, component, component.getLifecycleState().name(), component.getVersion(), responseFormat, auditingFields);
1173 private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
1174 log.debug("audit before sending response");
1175 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment);
1176 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditAction, ComponentTypeEnum.SERVICE, auditingFields);
1179 private void createAudit(User user, AuditingActionEnum auditAction, String comment, Service component, String prevState, String prevVersion, ResponseFormat responseFormat, EnumMap<AuditingFieldsKeysEnum, Object> auditingFields) {
1180 log.debug("audit before sending response");
1181 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_COMMENT, comment);
1182 componentsUtils.auditComponent(responseFormat, user, component, prevState, prevVersion, auditAction, ComponentTypeEnum.SERVICE, auditingFields);
1185 public Either<Service, ResponseFormat> activateDistribution(String serviceId, String envName, User modifier, HttpServletRequest request) {
1187 Either<User, ResponseFormat> eitherCreator = validateUserExists(modifier.getUserId(), "activate Distribution", false);
1188 if (eitherCreator.isRight()) {
1189 return Either.right(eitherCreator.right().value());
1192 User user = eitherCreator.left().value();
1194 Either<Service, ResponseFormat> result = null;
1195 ResponseFormat response = null;
1196 Service updatedService = null;
1197 String did = ThreadLocalsHolder.getUuid();
1198 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1199 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID, did);
1201 String configuredEnvName = ConfigurationManager.getConfigurationManager().getDistributionEngineConfiguration().getEnvironments().get(0);
1202 if (configuredEnvName != null && false == envName.equals(configuredEnvName)) {
1203 log.trace("Update environment name to be {} instead of {}", configuredEnvName, envName);
1204 envName = configuredEnvName;
1208 ServletContext servletContext = request.getSession().getServletContext();
1209 boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(request.getSession().getServletContext()); // DE
1210 if (!isDistributionEngineUp) {
1211 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Distribution Engine is DOWN");
1212 BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN");
1213 log.debug("Distribution Engine is DOWN");
1214 response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1215 return Either.right(response);
1218 Either<Service, StorageOperationStatus> serviceRes = serviceOperation.getService(serviceId);
1219 if (serviceRes.isRight()) {
1220 log.debug("failed retrieving service");
1221 response = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceRes.right().value(), ComponentTypeEnum.SERVICE), serviceId);
1222 componentsUtils.auditComponent(response, user, null, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields);
1223 return Either.right(response);
1225 Service service = serviceRes.left().value();
1226 String dcurrStatus = service.getDistributionStatus().name();
1227 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DPREV_STATUS, dcurrStatus);
1229 Either<INotificationData, StorageOperationStatus> readyForDistribution = distributionEngine.isReadyForDistribution(service, did, envName);
1230 if (readyForDistribution.isLeft()) {
1231 INotificationData notificationData = readyForDistribution.left().value();
1232 StorageOperationStatus notifyServiceResponse = distributionEngine.notifyService(did, service, notificationData, envName, user.getUserId(), user.getFullName());
1233 if (notifyServiceResponse == StorageOperationStatus.OK) {
1234 Either<Service, ResponseFormat> updateStateRes = updateDistributionStatusForActivation(service, user, DistributionStatusEnum.DISTRIBUTED);
1235 if (updateStateRes.isLeft() && updateStateRes.left().value() != null) {
1236 updatedService = updateStateRes.left().value();
1237 dcurrStatus = updatedService.getDistributionStatus().name();
1239 // The response is not relevant
1240 updatedService = service;
1242 ASDCKpiApi.countActivatedDistribution();
1243 response = componentsUtils.getResponseFormat(ActionStatus.OK);
1244 result = Either.left(updatedService);
1246 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Activate Distribution - send notification");
1247 BeEcompErrorManager.getInstance().logBeSystemError("Activate Distribution - send notification");
1248 log.debug("distributionEngine.notifyService response is: {}", notifyServiceResponse);
1249 response = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1250 result = Either.right(response);
1253 StorageOperationStatus distEngineValidationResponse = readyForDistribution.right().value();
1254 response = componentsUtils.getResponseFormatByDE(componentsUtils.convertFromStorageResponse(distEngineValidationResponse), service.getName(), envName);
1255 result = Either.right(response);
1257 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_DCURR_STATUS, dcurrStatus);
1258 componentsUtils.auditComponent(response, user, service, null, null, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST, ComponentTypeEnum.SERVICE, auditingFields);
1262 // convert to private after deletion of temp url
1263 public Either<Service, ResponseFormat> updateDistributionStatusForActivation(Service service, User user, DistributionStatusEnum state) {
1265 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "update Distribution Status For Activation", false);
1266 if (resp.isRight()) {
1267 return Either.right(resp.right().value());
1270 String serviceId = service.getUniqueId();
1271 Either<Boolean, ResponseFormat> lockResult = lockComponent(serviceId, service, "updateDistributionStatusForActivation");
1272 if (lockResult.isRight()) {
1273 return Either.right(lockResult.right().value());
1276 Either<Service, StorageOperationStatus> result = serviceOperation.updateDestributionStatus(service, user, state);
1277 if (result.isRight()) {
1278 titanGenericDao.rollback();
1279 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "updateDistributionStatusForActivation");
1280 BeEcompErrorManager.getInstance().logBeSystemError("updateDistributionStatusForActivation");
1281 log.debug("service {} change distribution status failed", serviceId);
1282 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1284 titanGenericDao.commit();
1285 return Either.left(result.left().value());
1287 graphLockOperation.unlockComponent(serviceId, NodeTypeEnum.Service);
1291 public Either<Service, ResponseFormat> markDistributionAsDeployed(String serviceId, String did, User user) {
1293 Either<User, ResponseFormat> resp = validateUserExists(user.getUserId(), "mark Distribution As Deployed", false);
1294 if (resp.isRight()) {
1295 return Either.right(resp.right().value());
1298 log.debug("mark distribution deployed");
1300 AuditingActionEnum auditAction = AuditingActionEnum.DISTRIBUTION_DEPLOY;
1301 Either<Service, StorageOperationStatus> getServiceResponse = serviceOperation.getService(serviceId);
1302 if (getServiceResponse.isRight()) {
1303 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeServiceMissingError, "markDistributionAsDeployed", serviceId);
1304 BeEcompErrorManager.getInstance().logBeComponentMissingError("markDistributionAsDeployed", ComponentTypeEnum.SERVICE.getValue(), serviceId);
1305 log.debug("service {} not found", serviceId);
1306 ResponseFormat responseFormat = auditDeployError(did, user, auditAction, null, componentsUtils.convertFromStorageResponse(getServiceResponse.right().value(), ComponentTypeEnum.SERVICE), "");
1308 return Either.right(responseFormat);
1311 Service service = getServiceResponse.left().value();
1313 Either<User, ResponseFormat> validateRoleForDeploy = validateRoleForDeploy(did, user, auditAction, service);
1314 if (validateRoleForDeploy.isRight()) {
1315 return Either.right(validateRoleForDeploy.right().value());
1317 user = validateRoleForDeploy.left().value();
1319 return checkDistributionAndDeploy(did, user, auditAction, service);
1323 public Either<Service, ResponseFormat> generateVfModuleArtifacts(Service service, User modifier, boolean shouldLock) {
1324 Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = ri ->
1325 // Only one VF Module Artifact per instance - add it to a list of one
1326 Arrays.asList(new VfModuleArtifacGenerator(modifier, ri, service, shouldLock));
1328 return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
1332 private List<GroupDefinition> collectGroupsForCompInstance(ComponentInstance currVF, Wrapper<ResponseFormat> responseWrapper) {
1333 List<GroupDefinition> relevantGroups = new ArrayList<>();
1334 Either<List<GroupDefinition>, StorageOperationStatus> eitherGroups = groupOperation.getAllGroups(currVF.getComponentUid(), NodeTypeEnum.Resource);
1336 if (eitherGroups.isRight()) {
1337 final StorageOperationStatus storageStatus = eitherGroups.right().value();
1338 if (storageStatus != StorageOperationStatus.NOT_FOUND && storageStatus != StorageOperationStatus.OK) {
1339 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
1340 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
1344 relevantGroups = eitherGroups.left().value().stream().filter(p -> GroupTypeEnum.VF_MODULE.getGroupTypeName().equals(p.getType())).collect(Collectors.toList());
1346 return relevantGroups;
1349 private ArtifactDefinition getVfModuleArtifactForCompInstance(ComponentInstance currVF, Service service, User modifier, List<GroupDefinition> groupsForCurrVF, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
1350 ArtifactDefinition vfModuleAertifact = null;
1352 Optional<ArtifactDefinition> optionalVfModuleArtifact = currVF.getDeploymentArtifacts().values().stream().filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.VF_MODULES_METADATA.name())).findAny();
1353 if (optionalVfModuleArtifact.isPresent()) {
1354 vfModuleAertifact = optionalVfModuleArtifact.get();
1356 Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact = createVfModuleArtifact(modifier, currVF, service, payloadWrapper.getInnerElement());
1357 if (createVfModuleArtifact.isLeft()) {
1358 vfModuleAertifact = createVfModuleArtifact.left().value();
1360 responseWrapper.setInnerElement(createVfModuleArtifact.right().value());
1363 return vfModuleAertifact;
1366 private void fillVfModuleHeatEnvPayload(List<GroupDefinition> groupsForCurrVF, ComponentInstance currVFInstance, Wrapper<String> payloadWrapper) {
1367 // Converts GroupDefinition to VfModuleArtifactPayload which is the
1368 // format used in the payload
1370 List<VfModuleArtifactPayload> vfModulePayloadForCurrVF = groupsForCurrVF.stream().map(group -> new VfModuleArtifactPayload(group)).collect(Collectors.toList());
1371 Collections.sort(vfModulePayloadForCurrVF, (art1, art2) -> VfModuleArtifactPayload.compareByGroupName(art1, art2));
1372 // Update Payload With Heat Env
1373 vfModulePayloadForCurrVF.stream().forEach(e -> addHeatEnvArtifactsToVFModulePayload(e, currVFInstance));
1375 final Gson gson = new GsonBuilder().setPrettyPrinting().create();
1377 String vfModulePayloadString = gson.toJson(vfModulePayloadForCurrVF);
1378 payloadWrapper.setInnerElement(vfModulePayloadString);
1382 private void addHeatEnvArtifactsToVFModulePayload(VfModuleArtifactPayload vfModulePayload, ComponentInstance currVFInstance) {
1383 List<String> originalModuleArtifacts = vfModulePayload.getArtifacts();
1384 if (!MapUtils.isEmpty(currVFInstance.getDeploymentArtifacts()) && !CollectionUtils.isEmpty(originalModuleArtifacts)) {
1386 final Collection<ArtifactDefinition> depInsArtifacts = currVFInstance.getDeploymentArtifacts().values();
1388 List<ArtifactDefinition> heatEnvArtifacts = depInsArtifacts.stream().filter(art -> art.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())).collect(Collectors.toList());
1389 // Unique Id Of Artifacts In the vf module
1390 List<String> moduleArtUniqueId = depInsArtifacts.stream().filter(art -> originalModuleArtifacts.contains(art.getArtifactUUID())).map(art -> art.getUniqueId()).collect(Collectors.toList());
1391 // Collect Only Heat Artifatcs that are Generated from artifacts in
1393 List<String> relevantHeatEnvUUID = heatEnvArtifacts.stream().filter(heatEnv -> moduleArtUniqueId.contains(heatEnv.getGeneratedFromId())).map(heatEnv -> heatEnv.getArtifactUUID()).collect(Collectors.toList());
1395 List<String> fullArtifactList = new ArrayList<>();
1396 fullArtifactList.addAll(originalModuleArtifacts);
1397 fullArtifactList.addAll(relevantHeatEnvUUID);
1399 vfModulePayload.setArtifacts(fullArtifactList);
1403 private Either<ArtifactDefinition, ResponseFormat> generateVfModuleArtifact(User modifier, ComponentInstance currVFInstance, Service service, boolean shouldLock) {
1404 ArtifactDefinition vfModuleAertifact = null;
1405 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
1406 Wrapper<String> payloadWrapper = new Wrapper<>();
1407 List<GroupDefinition> groupsForCurrVF = collectGroupsForCompInstance(currVFInstance, responseWrapper);
1408 if (responseWrapper.isEmpty()) {
1409 fillVfModuleHeatEnvPayload(groupsForCurrVF, currVFInstance, payloadWrapper);
1411 if (responseWrapper.isEmpty()) {
1412 vfModuleAertifact = getVfModuleArtifactForCompInstance(currVFInstance, service, modifier, groupsForCurrVF, payloadWrapper, responseWrapper);
1414 if (responseWrapper.isEmpty() && vfModuleAertifact != null) {
1415 vfModuleAertifact = fillVfModulePayload(modifier, currVFInstance, vfModuleAertifact, shouldLock, payloadWrapper, responseWrapper);
1418 Either<ArtifactDefinition, ResponseFormat> result;
1419 if (responseWrapper.isEmpty()) {
1420 result = Either.left(vfModuleAertifact);
1422 result = Either.right(responseWrapper.getInnerElement());
1428 private ArtifactDefinition fillVfModulePayload(User modifier, ComponentInstance currVF, ArtifactDefinition vfModuleAertifact, boolean shouldLock, Wrapper<String> payloadWrapper, Wrapper<ResponseFormat> responseWrapper) {
1429 ArtifactDefinition result = null;
1430 final Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(currVF.getComponentUid());
1431 if (eitherResource.isRight()) {
1432 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherResource.right().value())));
1434 Resource resource = eitherResource.left().value();
1435 Either<ArtifactDefinition, ResponseFormat> eitherPayload = artifactsBusinessLogic.generateArtifactPayload(vfModuleAertifact, resource, currVF.getName(), modifier, shouldLock, () -> System.currentTimeMillis(),
1436 () -> Either.left(artifactsBusinessLogic.createEsArtifactData(vfModuleAertifact, payloadWrapper.getInnerElement().getBytes(StandardCharsets.UTF_8))));
1437 if (eitherPayload.isLeft()) {
1438 result = eitherPayload.left().value();
1440 responseWrapper.setInnerElement(eitherPayload.right().value());
1447 private Either<ArtifactDefinition, ResponseFormat> createVfModuleArtifact(User modifier, ComponentInstance currVF, Service service, String vfModulePayloadString) {
1449 ArtifactDefinition vfModuleArtifactDefinition = new ArtifactDefinition();
1451 vfModuleArtifactDefinition.setDescription("Auto-generated VF Modules information artifact");
1452 vfModuleArtifactDefinition.setArtifactDisplayName("Vf Modules Metadata");
1453 vfModuleArtifactDefinition.setArtifactType(ArtifactTypeEnum.VF_MODULES_METADATA.getType());
1454 vfModuleArtifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
1455 vfModuleArtifactDefinition.setArtifactLabel("vfModulesMetadata");
1456 vfModuleArtifactDefinition.setTimeout(0);
1457 vfModuleArtifactDefinition.setArtifactName(currVF.getNormalizedName() + "_modules.json");
1458 vfModuleArtifactDefinition.setPayloadData(vfModulePayloadString);
1460 Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent = artifactOperation.addArifactToComponent(vfModuleArtifactDefinition, currVF.getUniqueId(), NodeTypeEnum.ResourceInstance, true, true);
1462 Either<ArtifactDefinition, ResponseFormat> result;
1463 if (addArifactToComponent.isLeft()) {
1464 result = Either.left(addArifactToComponent.left().value());
1466 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArifactToComponent.right().value())));
1472 public Either<Service, ResponseFormat> generateHeatEnvArtifacts(Service service, User modifier, boolean shouldLock) {
1474 Function<ComponentInstance, List<ArtifactGenerator<ArtifactDefinition>>> artifactTaskGeneratorCreator = resourceInstance ->
1475 // Get All Deployment Artifacts
1476 service.getComponentInstances().stream().filter(ri -> ri != null && ri == resourceInstance).filter(ri -> ri.getDeploymentArtifacts() != null).flatMap(ri -> ri.getDeploymentArtifacts().values().stream()).
1477 // Filter in Only Heat Env
1478 filter(depArtifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(depArtifact.getArtifactType())).
1479 // Create ArtifactGenerator from those Artifacts
1480 map(depArtifact -> new HeatEnvArtifactGenerator(depArtifact, service, resourceInstance.getName(), modifier, shouldLock)).collect(Collectors.toList());
1482 return generateDeploymentArtifacts(service, modifier, artifactTaskGeneratorCreator);
1486 private <CallVal> Either<Service, ResponseFormat> generateDeploymentArtifacts(Service service, User modifier, Function<ComponentInstance, List<ArtifactGenerator<CallVal>>> artifactTaskGeneratorCreator) {
1488 List<Future<Either<CallVal, ResponseFormat>>> allFutures = new ArrayList<>();
1490 // Get Flat List of (Callable) ArtifactGenerator for all the RI in the
1492 if (service.getComponentInstances() != null) {
1493 List<ArtifactGenerator<CallVal>> artifactGenList = service.getComponentInstances().stream().flatMap(ri -> artifactTaskGeneratorCreator.apply(ri).stream()).collect(Collectors.toList());
1494 if (artifactGenList != null && !artifactGenList.isEmpty()) {
1495 ExecutorService executor = Executors.newFixedThreadPool(artifactGenList.size());
1497 artifactGenList.stream().forEach(e -> allFutures.add(executor.submit(e)));
1499 boolean isSuccess = true;
1500 ResponseFormat firstError = null;
1501 for (Future<Either<CallVal, ResponseFormat>> entry : allFutures) {
1503 Either<CallVal, ResponseFormat> actionStatus = entry.get(20, TimeUnit.SECONDS);
1504 if (actionStatus.isRight()) {
1506 if (firstError == null) {
1507 firstError = actionStatus.right().value();
1509 log.debug("Failed to generate artifact error : {}", actionStatus.right().value());
1511 } catch (Exception e) {
1512 log.debug("Failed to collect result from artifact generator ", e);
1514 firstError = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1517 executor.shutdown();
1519 return Either.right(firstError);
1524 return Either.left(service);
1527 abstract class ArtifactGenerator<CallVal> implements Callable<Either<CallVal, ResponseFormat>> {
1531 class HeatEnvArtifactGenerator extends ArtifactGenerator<ArtifactDefinition> {
1532 ArtifactDefinition artifactDefinition;
1534 String resourceInstanceName;
1538 HeatEnvArtifactGenerator(ArtifactDefinition artifactDefinition, Service service, String resourceInstanceName, User modifier, boolean shouldLock) {
1539 this.artifactDefinition = artifactDefinition;
1540 this.service = service;
1541 this.resourceInstanceName = resourceInstanceName;
1542 this.modifier = modifier;
1543 this.shouldLock = shouldLock;
1547 public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
1548 return artifactsBusinessLogic.generateHeatEnvArtifact(artifactDefinition, service, resourceInstanceName, modifier, shouldLock);
1551 public ArtifactDefinition getArtifactDefinition() {
1552 return artifactDefinition;
1557 class VfModuleArtifacGenerator extends ArtifactGenerator<ArtifactDefinition> {
1559 private ComponentInstance componentInstance;
1560 private Service service;
1564 public Either<ArtifactDefinition, ResponseFormat> call() throws Exception {
1565 return generateVfModuleArtifact(user, componentInstance, service, shouldLock);
1568 private VfModuleArtifacGenerator(User user, ComponentInstance componentInstance, Service service, boolean shouldLock) {
1571 this.componentInstance = componentInstance;
1572 this.service = service;
1573 this.shouldLock = shouldLock;
1578 private synchronized Either<Service, ResponseFormat> checkDistributionAndDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
1579 boolean isDeployed = isDistributionDeployed(did, service);
1581 return Either.left(service);
1583 Either<Boolean, ResponseFormat> distributionSuccess = checkDistributionSuccess(did, user, auditAction, service);
1584 if (distributionSuccess.isRight()) {
1585 return Either.right(distributionSuccess.right().value());
1588 log.debug("mark distribution {} as deployed - success", did);
1589 componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, STATUS_DEPLOYED, "OK", user);
1590 return Either.left(service);
1593 private boolean isDistributionDeployed(String did, Service service) {
1594 Either<List<DistributionDeployEvent>, ActionStatus> alreadyDeployed = auditCassandraDao.getDistributionDeployByStatus(did, AuditingActionEnum.DISTRIBUTION_DEPLOY.getName(), STATUS_DEPLOYED);
1596 boolean isDeployed = false;
1597 if (alreadyDeployed.isLeft() && !alreadyDeployed.left().value().isEmpty()) {
1599 log.debug("distribution {} is already deployed", did);
1605 protected Either<Boolean, ResponseFormat> checkDistributionSuccess(String did, User user, AuditingActionEnum auditAction, Service service) {
1607 log.trace("checkDistributionSuccess");
1608 // get all "DRequest" records for this distribution
1609 // Either<List<ESTimeBasedEvent>, ActionStatus> distRequestsResponse =
1610 // auditingDao.getListOfDistributionByAction(did,
1611 // AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName(), "",
1612 // ResourceAdminEvent.class);
1613 Either<List<ResourceAdminEvent>, ActionStatus> distRequestsResponse = auditCassandraDao.getDistributionRequest(did, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName());
1614 if (distRequestsResponse.isRight()) {
1615 ResponseFormat error = auditDeployError(did, user, auditAction, service, distRequestsResponse.right().value());
1616 return Either.right(error);
1619 List<ResourceAdminEvent> distributionRequests = distRequestsResponse.left().value();
1620 if (distributionRequests.isEmpty()) {
1621 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDistributionMissingError, "markDistributionAsDeployed", did);
1622 BeEcompErrorManager.getInstance().logBeDistributionMissingError("markDistributionAsDeployed", did);
1623 log.info("distribution {} is not found", did);
1624 ResponseFormat error = auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_NOT_FOUND);
1625 return Either.right(error);
1627 boolean isRequestSucceeded = false;
1628 for (ResourceAdminEvent event : distributionRequests) {
1629 String eventStatus = event.getStatus();
1630 if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
1631 isRequestSucceeded = true;
1636 // get all "DNotify" records for this distribution
1637 // Either<List<ESTimeBasedEvent>, ActionStatus>
1638 // distNotificationsResponse =
1639 // auditingDao.getListOfDistributionByAction(did,
1640 // AuditingActionEnum.DISTRIBUTION_NOTIFY.getName(), "",
1641 // DistributionNotificationEvent.class);
1642 Either<List<DistributionNotificationEvent>, ActionStatus> distNotificationsResponse = auditCassandraDao.getDistributionNotify(did, AuditingActionEnum.DISTRIBUTION_NOTIFY.getName());
1643 if (distNotificationsResponse.isRight()) {
1644 ResponseFormat error = auditDeployError(did, user, auditAction, service, distNotificationsResponse.right().value());
1645 return Either.right(error);
1648 List<DistributionNotificationEvent> distributionNotifications = distNotificationsResponse.left().value();
1649 boolean isNotificationsSucceeded = false;
1650 for (DistributionNotificationEvent event : distributionNotifications) {
1651 String eventStatus = event.getStatus();
1652 if (eventStatus != null && eventStatus.equals(STATUS_SUCCESS_200)) {
1653 isNotificationsSucceeded = true;
1658 // if request failed OR there are notifications that failed
1659 if (!(isRequestSucceeded && isNotificationsSucceeded)) {
1661 log.info("distribution {} has failed", did);
1662 ResponseFormat error = componentsUtils.getResponseFormat(ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
1663 auditDeployError(did, user, auditAction, service, ActionStatus.DISTRIBUTION_REQUESTED_FAILED, did);
1664 return Either.right(error);
1666 return Either.left(true);
1669 private ResponseFormat auditDeployError(String did, User user, AuditingActionEnum auditAction, Service service, ActionStatus status, String... params) {
1671 ResponseFormat error = componentsUtils.getResponseFormat(status, params);
1672 String message = "";
1673 if (error.getMessageId() != null) {
1674 message = error.getMessageId() + ": ";
1676 message += error.getFormattedMessage();
1678 if (service != null) {
1679 componentsUtils.auditServiceDistributionDeployed(auditAction, service.getName(), service.getVersion(), service.getUUID(), did, error.getStatus().toString(), message, user);
1681 componentsUtils.auditServiceDistributionDeployed(auditAction, "", "", "", did, error.getStatus().toString(), message, user);
1686 private Either<User, ResponseFormat> validateRoleForDeploy(String did, User user, AuditingActionEnum auditAction, Service service) {
1687 Either<User, ActionStatus> eitherCreator = userAdmin.getUser(user.getUserId(), false);
1688 if (eitherCreator.isRight() || eitherCreator.left().value() == null) {
1689 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeUserMissingError, "Deploy Service", user.getUserId());
1690 BeEcompErrorManager.getInstance().logBeUserMissingError("Deploy Service", user.getUserId());
1691 log.debug("validateRoleForDeploy method - user is not listed. userId={}", user.getUserId());
1692 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.USER_NOT_FOUND, user.getUserId());
1693 auditDeployError(did, user, auditAction, service, ActionStatus.USER_NOT_FOUND);
1694 return Either.right(responseFormat);
1696 user = eitherCreator.left().value();
1697 log.debug("validate user role");
1698 List<Role> roles = new ArrayList<>();
1699 roles.add(Role.ADMIN);
1700 roles.add(Role.OPS);
1701 Either<Boolean, ResponseFormat> validateRes = validateUserRole(user, service, roles, auditAction, null);
1702 if (validateRes.isRight()) {
1703 log.info("role {} is not allowed to perform this action", user.getRole());
1704 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
1705 auditDeployError(did, user, auditAction, service, ActionStatus.RESTRICTED_OPERATION);
1706 return Either.right(responseFormat);
1708 return Either.left(user);
1713 public void setDeploymentArtifactsPlaceHolder(Component component, User user) {
1714 // TODO Auto-generated method stub
1719 public Either<List<String>, ResponseFormat> deleteMarkedComponents() {
1720 return deleteMarkedComponents(ComponentTypeEnum.SERVICE);
1723 private HealthCheckBusinessLogic getHealthCheckBL(ServletContext context) {
1724 WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
1725 WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
1726 HealthCheckBusinessLogic healthCheckBl = webApplicationContext.getBean(HealthCheckBusinessLogic.class);
1727 return healthCheckBl;
1731 public ComponentInstanceBusinessLogic getComponentInstanceBL() {
1732 return serviceComponentInstanceBusinessLogic;
1736 public Either<List<ComponentInstance>, ResponseFormat> getComponentInstancesFilteredByPropertiesAndInputs(String componentId, ComponentTypeEnum componentTypeEnum, String userId, String searchText) {
1738 Either<User, ResponseFormat> resp = validateUserExists(userId, "Get Component Instances", false);
1739 if (resp.isRight()) {
1740 return Either.right(resp.right().value());
1743 ComponentOperation componentOperation = getComponentOperation(componentTypeEnum);
1745 Either<List<ComponentInstance>, StorageOperationStatus> componentInstancesResponse = componentOperation.getAllComponentInstncesMetadata(componentId, componentTypeEnum.getNodeType());
1746 if (componentInstancesResponse.isRight()) {
1748 if (componentInstancesResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1749 return Either.left(new ArrayList<ComponentInstance>());
1751 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentInstancesResponse.right().value()));
1752 return Either.right(responseFormat);
1755 List<ComponentInstance> componentInstances = componentInstancesResponse.left().value();
1756 componentInstances = componentInstances.stream().filter(instance -> instance.getOriginType().equals(OriginTypeEnum.VF)).collect(Collectors.toList());
1758 return Either.left(componentInstances);
1761 public ICacheMangerOperation getCacheManagerOperation() {
1762 return cacheManagerOperation;
1765 public void setCacheManagerOperation(ICacheMangerOperation cacheManagerOperation) {
1766 this.cacheManagerOperation = cacheManagerOperation;