Search in sources :

Example 16 with Artifacts

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();
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) RemoteException(java.rmi.RemoteException) File(java.io.File) ConfigurationManager(org.wso2.carbon.mediation.initializer.configurations.ConfigurationManager)

Example 17 with Artifacts

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);
    }
}
Also used : APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIProductDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductDTO) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) IOException(java.io.IOException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) JsonArray(com.google.gson.JsonArray) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) List(java.util.List) NodeList(org.w3c.dom.NodeList)

Example 18 with Artifacts

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();
}
Also used : SequencesDTO(org.wso2.carbon.apimgt.rest.api.gateway.dto.SequencesDTO)

Example 19 with Artifacts

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;
}
Also used : ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) InMemoryAPIDeployer(org.wso2.carbon.apimgt.gateway.InMemoryAPIDeployer) DeployResponseDTO(org.wso2.carbon.apimgt.rest.api.gateway.dto.DeployResponseDTO)

Example 20 with Artifacts

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;
}
Also used : ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) InMemoryAPIDeployer(org.wso2.carbon.apimgt.gateway.InMemoryAPIDeployer) DeployResponseDTO(org.wso2.carbon.apimgt.rest.api.gateway.dto.DeployResponseDTO)

Aggregations

File (java.io.File)23 IOException (java.io.IOException)18 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 ArrayList (java.util.ArrayList)17 CAppArtifacts (org.wso2.ei.dashboard.core.rest.model.CAppArtifacts)16 Operation (io.swagger.v3.oas.annotations.Operation)15 ApiResponse (io.swagger.v3.oas.annotations.responses.ApiResponse)15 ApiResponses (io.swagger.v3.oas.annotations.responses.ApiResponses)15 Response (javax.ws.rs.core.Response)15 Artifact (org.wso2.carbon.application.deployer.config.Artifact)15 Artifacts (org.wso2.ei.dashboard.core.rest.model.Artifacts)15 DeploymentException (org.apache.axis2.deployment.DeploymentException)11 CappFile (org.wso2.carbon.application.deployer.config.CappFile)11 Deployer (org.apache.axis2.deployment.Deployer)10 ArtifactSynchronizerException (org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException)10 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)10 InputStream (java.io.InputStream)9 FileInputStream (java.io.FileInputStream)7 APIRuntimeArtifactDto (org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto)7 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)7