use of org.wso2.ei.dashboard.core.rest.model.Artifacts in project carbon-apimgt by wso2.
the class TenantServiceCreator method createdConfigurationContext.
public void createdConfigurationContext(ConfigurationContext configurationContext) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
log.info("Initializing APIM TenantServiceCreator for the tenant domain : " + tenantDomain);
try {
// first check which configuration should be active
org.wso2.carbon.registry.core.Registry registry = (org.wso2.carbon.registry.core.Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
AxisConfiguration axisConfig = configurationContext.getAxisConfiguration();
// initialize the lock
Lock lock = new ReentrantLock();
axisConfig.addParameter("synapse.config.lock", lock);
// creates the synapse configuration directory hierarchy if not exists
// useful at the initial tenant creation
File tenantAxis2Repo = new File(configurationContext.getAxisConfiguration().getRepository().getFile());
File synapseConfigsDir = new File(tenantAxis2Repo, "synapse-configs");
if (!synapseConfigsDir.exists()) {
if (!synapseConfigsDir.mkdir()) {
log.fatal("Couldn't create the synapse-config root on the file system " + "for the tenant domain : " + tenantDomain);
return;
}
}
String synapseConfigsDirLocation = synapseConfigsDir.getAbsolutePath();
// set the required configuration parameters to initialize the ESB
axisConfig.addParameter(SynapseConstants.Axis2Param.SYNAPSE_CONFIG_LOCATION, synapseConfigsDirLocation);
// init the multiple configuration tracker
ConfigurationManager manger = new ConfigurationManager((UserRegistry) registry, configurationContext);
manger.init();
File synapseConfigDir = new File(synapseConfigsDir, manger.getTracker().getCurrentConfigurationName());
StringBuilder filepath = new StringBuilder();
filepath.append(synapseConfigsDir).append('/').append(manger.getTracker().getCurrentConfigurationName()).append('/').append(MultiXMLConfigurationBuilder.SEQUENCES_DIR).append('/').append(authFailureHandlerSequenceName).append(".xml");
File authFailureHandlerSequenceNameFile = new File(filepath.toString());
// sequence synapse configurations by using resource artifacts
if (!authFailureHandlerSequenceNameFile.exists()) {
createTenantSynapseConfigHierarchy(synapseConfigDir, tenantDomain);
}
String graphqlFilepath = String.valueOf(synapseConfigsDir) + '/' + manger.getTracker().getCurrentConfigurationName() + '/' + MultiXMLConfigurationBuilder.SEQUENCES_DIR + '/' + graphqlAuthFailureHandlerSequenceName + ".xml";
File graphqlFailureHandlerSequenceNameFile = new File(graphqlFilepath);
if (!graphqlFailureHandlerSequenceNameFile.exists()) {
createTenantSynapseConfigHierarchy(synapseConfigDir, tenantDomain);
}
String threatFaultConfigLocation = synapseConfigsDir.getAbsolutePath() + File.separator + manger.getTracker().getCurrentConfigurationName() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + threatFaultSequenceName + ".xml";
File threatFaultXml = new File(threatFaultConfigLocation);
if (!threatFaultXml.exists()) {
FileUtils.copyFile(new File(synapseConfigRootPath + threatFaultSequenceName + ".xml"), new File(synapseConfigDir.getAbsolutePath() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + threatFaultSequenceName + ".xml"));
}
String blockingSequenceLocation = synapseConfigsDir.getAbsolutePath() + File.separator + manger.getTracker().getCurrentConfigurationName() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + blockingSequence + ".xml";
File blockingSequenceXml = new File(blockingSequenceLocation);
if (!blockingSequenceXml.exists()) {
FileUtils.copyFile(new File(synapseConfigRootPath + blockingSequence + ".xml"), new File(synapseConfigDir.getAbsolutePath() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + blockingSequence + ".xml"));
}
String backEndFailureSequence = synapseConfigsDir.getAbsolutePath() + File.separator + manger.getTracker().getCurrentConfigurationName() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + backendFailureSequenceName + ".xml";
File backendSequenceXml = new File(backEndFailureSequence);
if (!backendSequenceXml.exists()) {
FileUtils.copyFile(new File(synapseConfigRootPath + backendFailureSequenceName + ".xml"), new File(synapseConfigDir.getAbsolutePath() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + backendFailureSequenceName + ".xml"));
}
String opaPolicyFailureSequence = synapseConfigsDir.getAbsolutePath() + File.separator + manger.getTracker().getCurrentConfigurationName() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + opaPolicyFailureHandlerSequenceName + ".xml";
File opaPolicyFailureSequenceXml = new File(opaPolicyFailureSequence);
if (!opaPolicyFailureSequenceXml.exists()) {
FileUtils.copyFile(new File(synapseConfigRootPath + opaPolicyFailureHandlerSequenceName + ".xml"), new File(synapseConfigDir.getAbsolutePath() + File.separator + MultiXMLConfigurationBuilder.SEQUENCES_DIR + File.separator + opaPolicyFailureHandlerSequenceName + ".xml"));
}
} catch (RemoteException e) {
log.error("Failed to create Tenant's synapse sequences.", e);
} catch (Exception e) {
log.error("Failed to create Tenant's synapse sequences.", e);
}
// Create caches for tenants
CacheProvider.removeAllCaches();
CacheProvider.createGatewayKeyCache();
CacheProvider.createResourceCache();
CacheProvider.createGatewayTokenCache();
CacheProvider.createInvalidTokenCache();
CacheProvider.createGatewayBasicAuthResourceCache();
CacheProvider.createGatewayUsernameCache();
CacheProvider.createInvalidUsernameCache();
// Initialize product REST API token caches
CacheProvider.createRESTAPITokenCache();
CacheProvider.createRESTAPIInvalidTokenCache();
CacheProvider.createGatewayJWTTokenCache();
CacheProvider.createTenantConfigCache();
CacheProvider.createRecommendationsCache();
CacheProvider.createParsedSignJWTCache();
CacheProvider.createInvalidGatewayApiKeyCache();
CacheProvider.createGatewayInternalKeyCache();
CacheProvider.createGatewayInternalKeyDataCache();
CacheProvider.createInvalidInternalKeyCache();
}
use of org.wso2.ei.dashboard.core.rest.model.Artifacts in project carbon-apimgt by wso2.
the class ImportUtils method importApiProduct.
/**
* This method imports an API Product.
*
* @param extractedFolderPath Location of the extracted folder of the API Product
* @param preserveProvider Decision to keep or replace the provider
* @param overwriteAPIProduct Whether to update the API Product or not
* @param overwriteAPIs Whether to update the dependent APIs or not
* @param organization Organization Identifier
* @param importAPIs Whether to import the dependent APIs or not
* @throws APIImportExportException If there is an error in importing an API
*/
public static APIProduct importApiProduct(String extractedFolderPath, Boolean preserveProvider, Boolean rotateRevision, Boolean overwriteAPIProduct, Boolean overwriteAPIs, Boolean importAPIs, String[] tokenScopes, String organization) throws APIManagementException {
String userName = RestApiCommonUtil.getLoggedInUsername();
String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName));
APIProduct importedApiProduct = null;
JsonArray deploymentInfoArray = null;
String currentStatus;
String targetStatus;
String lifecycleAction;
try {
JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName, ImportExportConstants.TYPE_API_PRODUCT);
APIProductDTO importedApiProductDTO = new Gson().fromJson(jsonObject, APIProductDTO.class);
// If the provided dependent APIs params config is null, it means this happening when importing an API (not
// because when importing a dependent API of an API Product). Hence, try to retrieve the definition from
// the API folder path
JsonObject paramsConfigObject = APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath);
// If above the params configurations are not null, then resolve those
if (paramsConfigObject != null) {
importedApiProductDTO = APIControllerUtil.injectEnvParamsToAPIProduct(importedApiProductDTO, paramsConfigObject, extractedFolderPath);
JsonElement deploymentsParam = paramsConfigObject.get(ImportExportConstants.DEPLOYMENT_ENVIRONMENTS);
if (deploymentsParam != null && !deploymentsParam.isJsonNull()) {
deploymentInfoArray = deploymentsParam.getAsJsonArray();
}
}
APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiProductDTO.getProvider());
// Check whether the API resources are valid
checkAPIProductResourcesValid(extractedFolderPath, userName, apiProvider, importedApiProductDTO, preserveProvider, organization);
targetStatus = importedApiProductDTO.getState().toString();
if (importAPIs) {
// Import dependent APIs only if it is asked (the UUIDs of the dependent APIs will be updated here if a
// fresh import happens)
importedApiProductDTO = importDependentAPIs(extractedFolderPath, userName, preserveProvider, apiProvider, overwriteAPIs, rotateRevision, importedApiProductDTO, tokenScopes, organization);
} else {
// Even we do not import APIs, the UUIDs of the dependent APIs should be updated if the APIs are
// already in the APIM
importedApiProductDTO = updateDependentApiUuids(importedApiProductDTO, apiProvider, currentTenantDomain, organization);
}
APIProduct targetApiProduct = retrieveApiProductToOverwrite(importedApiProductDTO.getName(), currentTenantDomain, apiProvider, Boolean.TRUE, organization);
// If the overwrite is set to true (which means an update), retrieve the existing API
if (Boolean.TRUE.equals(overwriteAPIProduct) && targetApiProduct != null) {
log.info("Existing API Product found, attempting to update it...");
currentStatus = targetApiProduct.getState();
importedApiProduct = PublisherCommonUtils.updateApiProduct(targetApiProduct, importedApiProductDTO, RestApiCommonUtil.getLoggedInUserProvider(), userName, currentTenantDomain);
} else {
if (targetApiProduct == null && Boolean.TRUE.equals(overwriteAPIProduct)) {
log.info("Cannot find : " + importedApiProductDTO.getName() + ". Creating it.");
}
currentStatus = APIStatus.CREATED.toString();
importedApiProduct = PublisherCommonUtils.addAPIProductWithGeneratedSwaggerDefinition(importedApiProductDTO, importedApiProductDTO.getProvider(), organization);
}
// Retrieving the life cycle action to do the lifecycle state change explicitly later
lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider);
// Add/update swagger of API Product
importedApiProduct = updateApiProductSwagger(extractedFolderPath, importedApiProduct.getUuid(), importedApiProduct, apiProvider, currentTenantDomain);
// Since Image, documents and client certificates are optional, exceptions are logged and ignored in
// implementation
ApiTypeWrapper apiTypeWrapperWithUpdatedApiProduct = new ApiTypeWrapper(importedApiProduct);
addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider);
addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider, organization);
if (log.isDebugEnabled()) {
log.debug("Mutual SSL enabled. Importing client certificates.");
}
addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApiProduct.getId().getProviderName(), organization);
// Change API Product lifecycle if state transition is required
if (StringUtils.isNotEmpty(lifecycleAction)) {
apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus);
apiProvider.changeLifeCycleStatus(currentTenantDomain, new ApiTypeWrapper(importedApiProduct), lifecycleAction, new HashMap<>());
}
importedApiProduct.setState(targetStatus);
if (deploymentInfoArray == null) {
// If the params have not overwritten the deployment environments, yaml file will be read
deploymentInfoArray = retrieveDeploymentLabelsFromArchive(extractedFolderPath, false);
}
List<APIRevisionDeployment> apiProductRevisionDeployments = getValidatedDeploymentsList(deploymentInfoArray, currentTenantDomain, apiProvider, organization);
if (apiProductRevisionDeployments.size() > 0) {
String importedAPIUuid = importedApiProduct.getUuid();
String revisionId;
APIRevision apiProductRevision = new APIRevision();
apiProductRevision.setApiUUID(importedAPIUuid);
apiProductRevision.setDescription("Revision created after importing the API Product");
try {
revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
if (log.isDebugEnabled()) {
log.debug("A new revision has been created for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion() + " with ID: " + revisionId);
}
} catch (APIManagementException e) {
// rotateRevision enabled, earliest revision will be deleted before creating a revision again
if (e.getErrorHandler().getErrorCode() == ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED).getErrorCode() && rotateRevision) {
String earliestRevisionUuid = apiProvider.getEarliestRevisionUUID(importedAPIUuid);
List<APIRevisionDeployment> deploymentsList = apiProvider.getAPIRevisionDeploymentList(earliestRevisionUuid);
// if the earliest revision is already deployed in gateway environments, it will be undeployed
// before deleting
apiProvider.undeployAPIProductRevisionDeployment(importedAPIUuid, earliestRevisionUuid, deploymentsList);
apiProvider.deleteAPIProductRevision(importedAPIUuid, earliestRevisionUuid, organization);
revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
if (log.isDebugEnabled()) {
log.debug("Revision ID: " + earliestRevisionUuid + " has been undeployed from " + deploymentsList.size() + " gateway environments and created a new revision ID: " + revisionId + " for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion());
}
} else {
throw new APIManagementException(e);
}
}
// Once the new revision successfully created, artifacts will be deployed in mentioned gateway
// environments
apiProvider.deployAPIProductRevision(importedAPIUuid, revisionId, apiProductRevisionDeployments);
} else {
log.info("Valid deployment environments were not found for the imported artifact. Hence not deployed" + " in any of the gateway environments.");
}
return importedApiProduct;
} catch (IOException e) {
// mandatory steps
throw new APIManagementException("Error while reading API Product meta information from path: " + extractedFolderPath, e);
} catch (FaultGatewaysException e) {
throw new APIManagementException("Error while updating API Product: " + importedApiProduct.getId().getName(), e);
} catch (APIManagementException e) {
String errorMessage = "Error while importing API Product: ";
if (importedApiProduct != null) {
errorMessage += importedApiProduct.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApiProduct.getId().getVersion();
}
throw new APIManagementException(errorMessage + " " + e.getMessage(), e);
}
}
use of org.wso2.ei.dashboard.core.rest.model.Artifacts in project carbon-apimgt by wso2.
the class SequenceApiServiceImpl method getSequences.
public Response getSequences(String apiName, String version, String tenantDomain, MessageContext messageContext) throws APIManagementException {
tenantDomain = RestApiCommonUtil.getValidateTenantDomain(tenantDomain);
List<String> deployedSequences = GatewayUtils.retrieveDeployedSequences(apiName, version, tenantDomain);
if (debugEnabled) {
log.debug("Retrieved Artifacts for " + apiName + " from eventhub");
}
SequencesDTO sequencesDTO = new SequencesDTO();
sequencesDTO.sequences(deployedSequences);
return Response.ok().entity(sequencesDTO).build();
}
use of org.wso2.ei.dashboard.core.rest.model.Artifacts in project carbon-apimgt by wso2.
the class RedeployApiApiServiceImpl method redployAPI.
public Response redployAPI(String apiName, String version, String tenantDomain, MessageContext messageContext) {
tenantDomain = RestApiCommonUtil.getValidateTenantDomain(tenantDomain);
InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer();
try {
inMemoryApiDeployer.reDeployAPI(apiName, version, tenantDomain);
if (debugEnabled) {
log.debug("Successfully deployed " + apiName + " in gateway");
}
DeployResponseDTO responseDTO = new DeployResponseDTO();
responseDTO.setDeployStatus(DeployResponseDTO.DeployStatusEnum.DEPLOYED);
responseDTO.setJsonPayload(apiName + " redeployed from the gateway");
return Response.ok().entity(responseDTO).build();
} catch (ArtifactSynchronizerException e) {
String errorMessage = "Error in fetching artifacts from storage";
log.error(errorMessage, e);
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.ei.dashboard.core.rest.model.Artifacts in project carbon-apimgt by wso2.
the class UndeployApiApiServiceImpl method undeployAPI.
public Response undeployAPI(String apiName, String version, String tenantDomain, MessageContext messageContext) {
InMemoryAPIDeployer inMemoryApiDeployer = new InMemoryAPIDeployer();
tenantDomain = RestApiCommonUtil.getValidateTenantDomain(tenantDomain);
try {
inMemoryApiDeployer.unDeployAPI(apiName, version, tenantDomain);
if (debugEnabled) {
log.debug("Successfully undeployed " + apiName + " in gateway");
}
DeployResponseDTO deployResponseDTO = new DeployResponseDTO();
deployResponseDTO.setDeployStatus(DeployResponseDTO.DeployStatusEnum.UNDEPLOYED);
deployResponseDTO.setJsonPayload(apiName + " Undeployed from the gateway");
return Response.ok().entity(deployResponseDTO).build();
} catch (ArtifactSynchronizerException e) {
String errorMessage = "Error in fetching artifacts from storage";
log.error(errorMessage, e);
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
Aggregations