Search in sources :

Example 1 with Id

use of io.cdap.cdap.common.id.Id in project cdap by caskdata.

the class DefaultArtifactRepository method addSystemArtifacts.

@Override
public void addSystemArtifacts() throws Exception {
    // scan the directory for artifact .jar files and config files for those artifacts
    Map<Id.Artifact, SystemArtifactInfo> systemArtifacts = new HashMap<>();
    for (File systemArtifactDir : systemArtifactDirs) {
        for (File jarFile : DirUtils.listFiles(systemArtifactDir, "jar")) {
            // parse id from filename
            Id.Artifact artifactId;
            try {
                artifactId = Id.Artifact.parse(Id.Namespace.SYSTEM, jarFile.getName());
            } catch (IllegalArgumentException e) {
                LOG.warn(String.format("Skipping system artifact '%s' because the name is invalid: ", e.getMessage()));
                continue;
            }
            // check for a corresponding .json config file
            String artifactFileName = jarFile.getName();
            String configFileName = artifactFileName.substring(0, artifactFileName.length() - ".jar".length()) + ".json";
            File configFile = new File(systemArtifactDir, configFileName);
            try {
                // read and parse the config file if it exists. Otherwise use an empty config with the artifact filename
                ArtifactConfig artifactConfig = configFile.isFile() ? configReader.read(artifactId.getNamespace(), configFile) : new ArtifactConfig();
                validateParentSet(artifactId, artifactConfig.getParents());
                validatePluginSet(artifactConfig.getPlugins());
                systemArtifacts.put(artifactId, new SystemArtifactInfo(artifactId, jarFile, artifactConfig));
            } catch (InvalidArtifactException e) {
                LOG.warn(String.format("Could not add system artifact '%s' because it is invalid.", artifactFileName), e);
            }
        }
    }
    // child -> parents
    Multimap<Id.Artifact, Id.Artifact> childToParents = HashMultimap.create();
    // parent -> children
    Multimap<Id.Artifact, Id.Artifact> parentToChildren = HashMultimap.create();
    Set<Id.Artifact> remainingArtifacts = new HashSet<>();
    // build mapping from child to parents and from parents to children
    for (SystemArtifactInfo child : systemArtifacts.values()) {
        Id.Artifact childId = child.getArtifactId();
        remainingArtifacts.add(childId);
        for (SystemArtifactInfo potentialParent : systemArtifacts.values()) {
            Id.Artifact potentialParentId = potentialParent.getArtifactId();
            // skip if we're looking at ourselves
            if (childId.equals(potentialParentId)) {
                continue;
            }
            if (child.getConfig().hasParent(potentialParentId)) {
                childToParents.put(childId, potentialParentId);
                parentToChildren.put(potentialParentId, childId);
            }
        }
    }
    if (!remainingArtifacts.isEmpty()) {
        ExecutorService executorService = Executors.newFixedThreadPool(Math.min(maxArtifactLoadParallelism, remainingArtifacts.size()), Threads.createDaemonThreadFactory("system-artifact-loader-%d"));
        try {
            // loop until there is no change
            boolean artifactsAdded = true;
            while (!remainingArtifacts.isEmpty() && artifactsAdded) {
                artifactsAdded = loadSystemArtifacts(executorService, systemArtifacts, remainingArtifacts, parentToChildren, childToParents);
            }
        } finally {
            executorService.shutdownNow();
        }
        if (!remainingArtifacts.isEmpty()) {
            LOG.warn("Unable to add system artifacts {} due to cyclic dependencies", Joiner.on(",").join(remainingArtifacts));
        }
    }
}
Also used : HashMap(java.util.HashMap) ArtifactConfig(io.cdap.cdap.common.conf.ArtifactConfig) ExecutorService(java.util.concurrent.ExecutorService) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) PluginId(io.cdap.cdap.proto.id.PluginId) Id(io.cdap.cdap.common.id.Id) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) File(java.io.File) InvalidArtifactException(io.cdap.cdap.common.InvalidArtifactException) HashSet(java.util.HashSet)

Example 2 with Id

use of io.cdap.cdap.common.id.Id in project cdap by caskdata.

the class AppLifecycleHttpHandler method getAllApps.

/**
 * Returns a list of applications associated with a namespace.
 */
@GET
@Path("/apps")
public void getAllApps(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @QueryParam("artifactName") String artifactName, @QueryParam("artifactVersion") String artifactVersion, @QueryParam("pageToken") String pageToken, @QueryParam("pageSize") Integer pageSize, @QueryParam("orderBy") SortOrder orderBy, @QueryParam("nameFilter") String nameFilter) throws Exception {
    NamespaceId namespace = validateNamespace(namespaceId);
    Set<String> names = new HashSet<>();
    if (!Strings.isNullOrEmpty(artifactName)) {
        for (String name : Splitter.on(',').split(artifactName)) {
            names.add(name);
        }
    }
    if (Optional.ofNullable(pageSize).orElse(0) != 0) {
        JsonPaginatedListResponder.respond(GSON, responder, APP_LIST_PAGINATED_KEY, jsonListResponder -> {
            AtomicReference<ApplicationRecord> lastRecord = new AtomicReference<>(null);
            ScanApplicationsRequest scanRequest = getScanRequest(namespaceId, artifactVersion, pageToken, pageSize, orderBy, nameFilter, names);
            boolean pageLimitReached = applicationLifecycleService.scanApplications(scanRequest, appDetail -> {
                ApplicationRecord record = new ApplicationRecord(appDetail);
                jsonListResponder.send(record);
                lastRecord.set(record);
            });
            ApplicationRecord record = lastRecord.get();
            return !pageLimitReached || record == null ? null : record.getName() + EntityId.IDSTRING_PART_SEPARATOR + record.getAppVersion();
        });
    } else {
        ScanApplicationsRequest scanRequest = getScanRequest(namespaceId, artifactVersion, pageToken, null, orderBy, nameFilter, names);
        JsonWholeListResponder.respond(GSON, responder, jsonListResponder -> applicationLifecycleService.scanApplications(scanRequest, d -> jsonListResponder.send(new ApplicationRecord(d))));
    }
}
Also used : ScanApplicationsRequest(io.cdap.cdap.app.store.ScanApplicationsRequest) AuditDetail(io.cdap.cdap.common.security.AuditDetail) ApplicationDetail(io.cdap.cdap.proto.ApplicationDetail) Arrays(java.util.Arrays) GsonBuilder(com.google.gson.GsonBuilder) ScanApplicationsRequest(io.cdap.cdap.app.store.ScanApplicationsRequest) ArtifactSummary(io.cdap.cdap.api.artifact.ArtifactSummary) Map(java.util.Map) HeaderParam(javax.ws.rs.HeaderParam) ApplicationNotFoundException(io.cdap.cdap.common.ApplicationNotFoundException) ProgramTerminator(io.cdap.cdap.internal.app.deploy.ProgramTerminator) EnumSet(java.util.EnumSet) HttpRequest(io.netty.handler.codec.http.HttpRequest) BodyConsumer(io.cdap.http.BodyConsumer) Set(java.util.Set) Reader(java.io.Reader) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) StandardCharsets(java.nio.charset.StandardCharsets) Id(io.cdap.cdap.common.id.Id) JsonArray(com.google.gson.JsonArray) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) Singleton(com.google.inject.Singleton) Iterables(com.google.common.collect.Iterables) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Location(org.apache.twill.filesystem.Location) GET(javax.ws.rs.GET) AccessEnforcer(io.cdap.cdap.security.spi.authorization.AccessEnforcer) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) WriteConflictException(io.cdap.cdap.internal.app.runtime.artifact.WriteConflictException) JsonWriter(com.google.gson.stream.JsonWriter) Nullable(javax.annotation.Nullable) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) AbstractBodyConsumer(io.cdap.cdap.common.http.AbstractBodyConsumer) Throwables(com.google.common.base.Throwables) DatasetManagementException(io.cdap.cdap.api.dataset.DatasetManagementException) IOException(java.io.IOException) ConflictException(io.cdap.cdap.common.ConflictException) NotImplementedException(io.cdap.cdap.common.NotImplementedException) InputStreamReader(java.io.InputStreamReader) ProgramRuntimeService(io.cdap.cdap.app.runtime.ProgramRuntimeService) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) JsonObject(com.google.gson.JsonObject) NamespaceQueryAdmin(io.cdap.cdap.common.namespace.NamespaceQueryAdmin) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) AccessException(io.cdap.cdap.api.security.AccessException) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) Unpooled(io.netty.buffer.Unpooled) QueryParam(javax.ws.rs.QueryParam) Gson(com.google.gson.Gson) AuthenticationContext(io.cdap.cdap.security.spi.authentication.AuthenticationContext) DefaultValue(javax.ws.rs.DefaultValue) Splitter(com.google.common.base.Splitter) DELETE(javax.ws.rs.DELETE) SortOrder(io.cdap.cdap.spi.data.SortOrder) ApplicationUpdateDetail(io.cdap.cdap.proto.ApplicationUpdateDetail) BatchApplicationDetail(io.cdap.cdap.proto.BatchApplicationDetail) Collection(java.util.Collection) ApplicationLifecycleService(io.cdap.cdap.internal.app.services.ApplicationLifecycleService) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) List(java.util.List) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) CaseInsensitiveEnumTypeAdapterFactory(io.cdap.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory) Optional(java.util.Optional) Constants(io.cdap.cdap.common.conf.Constants) InvalidArtifactException(io.cdap.cdap.common.InvalidArtifactException) DirUtils(io.cdap.cdap.common.utils.DirUtils) ArtifactScope(io.cdap.cdap.api.artifact.ArtifactScope) ArtifactAlreadyExistsException(io.cdap.cdap.common.ArtifactAlreadyExistsException) NotFoundException(io.cdap.cdap.common.NotFoundException) StandardPermission(io.cdap.cdap.proto.security.StandardPermission) PathParam(javax.ws.rs.PathParam) TypeToken(com.google.common.reflect.TypeToken) ApplicationWithPrograms(io.cdap.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms) EntityId(io.cdap.cdap.proto.id.EntityId) ServiceException(io.cdap.cdap.common.ServiceException) AtomicReference(java.util.concurrent.atomic.AtomicReference) JsonElement(com.google.gson.JsonElement) HashSet(java.util.HashSet) OutputStreamWriter(java.io.OutputStreamWriter) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) AbstractAppFabricHttpHandler(io.cdap.cdap.gateway.handlers.util.AbstractAppFabricHttpHandler) ProgramController(io.cdap.cdap.app.runtime.ProgramController) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) HttpResponder(io.cdap.http.HttpResponder) HttpHeaderValues(io.netty.handler.codec.http.HttpHeaderValues) JsonSyntaxException(com.google.gson.JsonSyntaxException) ChunkResponder(io.cdap.http.ChunkResponder) ApplicationFilter(io.cdap.cdap.app.store.ApplicationFilter) ProgramId(io.cdap.cdap.proto.id.ProgramId) BadRequestException(io.cdap.cdap.common.BadRequestException) KerberosPrincipalId(io.cdap.cdap.proto.id.KerberosPrincipalId) ArtifactNotFoundException(io.cdap.cdap.common.ArtifactNotFoundException) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) NamespacePathLocator(io.cdap.cdap.common.namespace.NamespacePathLocator) PUT(javax.ws.rs.PUT) FileReader(java.io.FileReader) AppRequest(io.cdap.cdap.proto.artifact.AppRequest) ApplicationRecord(io.cdap.cdap.proto.ApplicationRecord) Collections(java.util.Collections) AtomicReference(java.util.concurrent.atomic.AtomicReference) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) HashSet(java.util.HashSet) ApplicationRecord(io.cdap.cdap.proto.ApplicationRecord) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 3 with Id

use of io.cdap.cdap.common.id.Id in project cdap by caskdata.

the class AbstractProgramRuntimeService method list.

@Override
public Map<RunId, RuntimeInfo> list(ProgramType type) {
    Map<RunId, RuntimeInfo> result = new HashMap<>();
    Lock lock = runtimeInfosLock.readLock();
    lock.lock();
    try {
        result.putAll(runtimeInfos.row(type));
    } finally {
        lock.unlock();
    }
    // Add any missing RuntimeInfo from the remote twill runner
    if (remoteTwillRunnerService == null) {
        return Collections.unmodifiableMap(result);
    }
    for (TwillRunner.LiveInfo liveInfo : remoteTwillRunnerService.lookupLive()) {
        ProgramId programId = TwillAppNames.fromTwillAppName(liveInfo.getApplicationName(), false);
        if (programId == null || !programId.getType().equals(type)) {
            continue;
        }
        for (TwillController controller : liveInfo.getControllers()) {
            // For remote twill runner, the twill run id and cdap run id are the same
            RunId runId = controller.getRunId();
            if (result.computeIfAbsent(runId, rid -> createRuntimeInfo(programId, runId, controller)) == null) {
                LOG.warn("Unable to create runtime info for program {} with run id {}", programId, runId);
            }
        }
    }
    return Collections.unmodifiableMap(result);
}
Also used : TwillController(org.apache.twill.api.TwillController) ConfigResponse(io.cdap.cdap.app.deploy.ConfigResponse) Arrays(java.util.Arrays) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) ClusterMode(io.cdap.cdap.app.guice.ClusterMode) TimeoutException(java.util.concurrent.TimeoutException) HashBasedTable(com.google.common.collect.HashBasedTable) TwillAppNames(io.cdap.cdap.common.twill.TwillAppNames) AppDeploymentRuntimeInfo(io.cdap.cdap.internal.app.deploy.pipeline.AppDeploymentRuntimeInfo) ResourceReport(org.apache.twill.api.ResourceReport) SimpleProgramOptions(io.cdap.cdap.internal.app.runtime.SimpleProgramOptions) Map(java.util.Map) Closeables(com.google.common.io.Closeables) RunId(org.apache.twill.api.RunId) EnumSet(java.util.EnumSet) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) TwillController(org.apache.twill.api.TwillController) Threads(org.apache.twill.common.Threads) Artifacts(io.cdap.cdap.internal.app.runtime.artifact.Artifacts) ImmutableMap(com.google.common.collect.ImmutableMap) ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) Set(java.util.Set) InMemoryProgramLiveInfo(io.cdap.cdap.proto.InMemoryProgramLiveInfo) ApplicationClass(io.cdap.cdap.api.artifact.ApplicationClass) AppDeploymentInfo(io.cdap.cdap.internal.app.deploy.pipeline.AppDeploymentInfo) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Sets(com.google.common.collect.Sets) Id(io.cdap.cdap.common.id.Id) List(java.util.List) Optional(java.util.Optional) Constants(io.cdap.cdap.common.conf.Constants) ClassLoaderFolder(io.cdap.cdap.common.lang.jar.ClassLoaderFolder) ProgramOptionConstants(io.cdap.cdap.internal.app.runtime.ProgramOptionConstants) Configurator(io.cdap.cdap.app.deploy.Configurator) DirUtils(io.cdap.cdap.common.utils.DirUtils) AppSpecInfo(io.cdap.cdap.internal.app.deploy.pipeline.AppSpecInfo) Joiner(com.google.common.base.Joiner) ProgramRunners(io.cdap.cdap.internal.app.runtime.ProgramRunners) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Iterables(com.google.common.collect.Iterables) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Location(org.apache.twill.filesystem.Location) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) SimpleRuntimeInfo(io.cdap.cdap.internal.app.runtime.service.SimpleRuntimeInfo) Program(io.cdap.cdap.app.program.Program) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Programs(io.cdap.cdap.app.program.Programs) ProgramType(io.cdap.cdap.proto.ProgramType) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) NotRunningProgramLiveInfo(io.cdap.cdap.proto.NotRunningProgramLiveInfo) Strings(com.google.common.base.Strings) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ImmutableList(com.google.common.collect.ImmutableList) TwillRunner(org.apache.twill.api.TwillRunner) AbstractIdleService(com.google.common.util.concurrent.AbstractIdleService) Locations(io.cdap.cdap.common.io.Locations) TwillRunnerService(org.apache.twill.api.TwillRunnerService) ArtifactId(io.cdap.cdap.proto.id.ArtifactId) ArtifactDetail(io.cdap.cdap.internal.app.runtime.artifact.ArtifactDetail) ExecutorService(java.util.concurrent.ExecutorService) Nullable(javax.annotation.Nullable) ProgramLiveInfo(io.cdap.cdap.proto.ProgramLiveInfo) Logger(org.slf4j.Logger) ConfiguratorFactory(io.cdap.cdap.internal.app.deploy.ConfiguratorFactory) Files(java.nio.file.Files) RunIds(io.cdap.cdap.common.app.RunIds) RuntimeArguments(io.cdap.cdap.api.common.RuntimeArguments) ProgramId(io.cdap.cdap.proto.id.ProgramId) Throwables(com.google.common.base.Throwables) ProgramDescriptor(io.cdap.cdap.app.program.ProgramDescriptor) IOException(java.io.IOException) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) Maps(com.google.common.collect.Maps) File(java.io.File) AbstractListener(io.cdap.cdap.internal.app.runtime.AbstractListener) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Lock(java.util.concurrent.locks.Lock) ArtifactNotFoundException(io.cdap.cdap.common.ArtifactNotFoundException) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) Closeable(java.io.Closeable) ArtifactRepository(io.cdap.cdap.internal.app.runtime.artifact.ArtifactRepository) BundleJarUtil(io.cdap.cdap.common.lang.jar.BundleJarUtil) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Table(com.google.common.collect.Table) Plugin(io.cdap.cdap.api.plugin.Plugin) Collections(java.util.Collections) BasicArguments(io.cdap.cdap.internal.app.runtime.BasicArguments) AppDeploymentRuntimeInfo(io.cdap.cdap.internal.app.deploy.pipeline.AppDeploymentRuntimeInfo) SimpleRuntimeInfo(io.cdap.cdap.internal.app.runtime.service.SimpleRuntimeInfo) HashMap(java.util.HashMap) TwillRunner(org.apache.twill.api.TwillRunner) RunId(org.apache.twill.api.RunId) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ProgramId(io.cdap.cdap.proto.id.ProgramId) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Lock(java.util.concurrent.locks.Lock)

Example 4 with Id

use of io.cdap.cdap.common.id.Id in project cdap by caskdata.

the class SystemAppManagementServiceTest method testSystemAppManagementServiceE2E.

/**
 * Tests SystemAppManagementService's upgrade method end to end by running this scenario:
 * 1. Creates a system app config for an application into corresponding directory with artifact version VERSION1.
 * 2. Successfully read and load the config.
 * 3. Runs all steps to enable a system app , tests SystemAppEnableExecutor.
 * 4. Deploys the VERSION1 app and runs all programs corresponding to the app.
 * 5. Checks status of a continuously running program, i.e a service program.
 * 6. Updates system app config with app version upgraded to VERSION2.
 * 7. On restart of SystemAppManagementService, app should kill old running programs and start program again.
 */
@Test
public void testSystemAppManagementServiceE2E() throws Exception {
    systemConfigDir = TEMPORARY_FOLDER.newFolder("demo-sys-app-config-dir");
    cConf.set(Constants.SYSTEM_APP_CONFIG_DIR, systemConfigDir.getAbsolutePath());
    systemAppManagementService = new SystemAppManagementService(cConf, applicationLifecycleService, programLifecycleService);
    Id.Artifact artifactId1 = Id.Artifact.from(Id.Namespace.DEFAULT, "App", VERSION1);
    addAppArtifact(artifactId1, AllProgramsApp.class);
    createEnableSysAppConfigFile(artifactId1, "demo.json");
    systemAppManagementService.startUp();
    ApplicationId appId1 = NamespaceId.DEFAULT.app(AllProgramsApp.NAME);
    ProgramId serviceId1 = appId1.program(ProgramType.SERVICE, AllProgramsApp.NoOpService.NAME);
    waitState(serviceId1, RUNNING);
    Assert.assertEquals(RUNNING, getProgramStatus(serviceId1));
    // Program shouldn't be killed first time it is started.
    assertProgramRuns(serviceId1, ProgramRunStatus.KILLED, 0);
    systemAppManagementService.shutDown();
    // New system app config with newer artifact version.
    Id.Artifact artifactId2 = Id.Artifact.from(Id.Namespace.DEFAULT, "App", VERSION2);
    addAppArtifact(artifactId2, AllProgramsApp.class);
    createEnableSysAppConfigFile(artifactId2, "demo.json");
    // SystemAppManagement restarts again.
    systemAppManagementService.startUp();
    // Program ID still stays the same.
    waitState(serviceId1, RUNNING);
    Assert.assertEquals(RUNNING, getProgramStatus(serviceId1));
    assertProgramRuns(serviceId1, ProgramRunStatus.KILLED, 1);
}
Also used : NamespaceId(io.cdap.cdap.proto.id.NamespaceId) ProgramId(io.cdap.cdap.proto.id.ProgramId) Id(io.cdap.cdap.common.id.Id) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) ProgramId(io.cdap.cdap.proto.id.ProgramId) Test(org.junit.Test)

Example 5 with Id

use of io.cdap.cdap.common.id.Id in project cdap by caskdata.

the class ApplicationLifecycleService method upgradeApplication.

/**
 * Upgrades an existing application by upgrading application artifact versions and plugin artifact versions.
 *
 * @param appId the id of the application to upgrade.
 * @param allowedArtifactScopes artifact scopes allowed while looking for latest artifacts for upgrade.
 * @param allowSnapshot whether to consider snapshot version of artifacts or not for upgrade.
 * @throws IllegalStateException if something unexpected happened during upgrade.
 * @throws IOException if there was an IO error during initializing application class from artifact.
 * @throws JsonIOException if there was an error in serializing or deserializing app config.
 * @throws UnsupportedOperationException if application does not support upgrade operation.
 * @throws InvalidArtifactException if candidate application artifact is invalid for upgrade purpose.
 * @throws NotFoundException if any object related to upgrade is not found like application/artifact.
 * @throws Exception if there was an exception during the upgrade of application. This exception will often wrap
 *                   the actual exception
 */
public void upgradeApplication(ApplicationId appId, Set<ArtifactScope> allowedArtifactScopes, boolean allowSnapshot) throws Exception {
    // Check if the current user has admin privileges on it before updating.
    accessEnforcer.enforce(appId, authenticationContext.getPrincipal(), StandardPermission.UPDATE);
    // check that app exists
    ApplicationSpecification currentSpec = store.getApplication(appId);
    if (currentSpec == null) {
        LOG.info("Application {} not found for upgrade.", appId);
        throw new NotFoundException(appId);
    }
    ArtifactId currentArtifact = currentSpec.getArtifactId();
    ArtifactSummary candidateArtifact = getLatestAppArtifactForUpgrade(appId, currentArtifact, allowedArtifactScopes, allowSnapshot);
    ArtifactVersion candidateArtifactVersion = new ArtifactVersion(candidateArtifact.getVersion());
    // Current artifact should not have higher version than candidate artifact.
    if (currentArtifact.getVersion().compareTo(candidateArtifactVersion) > 0) {
        String error = String.format("The current artifact has a version higher %s than any existing artifact.", currentArtifact.getVersion());
        throw new InvalidArtifactException(error);
    }
    ArtifactId newArtifactId = new ArtifactId(candidateArtifact.getName(), candidateArtifactVersion, candidateArtifact.getScope());
    Id.Artifact newArtifact = Id.Artifact.fromEntityId(Artifacts.toProtoArtifactId(appId.getParent(), newArtifactId));
    ArtifactDetail newArtifactDetail = artifactRepository.getArtifact(newArtifact);
    updateApplicationInternal(appId, currentSpec.getConfiguration(), programId -> {
    }, newArtifactDetail, Collections.singletonList(ApplicationConfigUpdateAction.UPGRADE_ARTIFACT), allowedArtifactScopes, allowSnapshot, ownerAdmin.getOwner(appId), false);
}
Also used : ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) ArtifactSummary(io.cdap.cdap.api.artifact.ArtifactSummary) ArtifactVersion(io.cdap.cdap.api.artifact.ArtifactVersion) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) ApplicationNotFoundException(io.cdap.cdap.common.ApplicationNotFoundException) NotFoundException(io.cdap.cdap.common.NotFoundException) ArtifactNotFoundException(io.cdap.cdap.common.ArtifactNotFoundException) Id(io.cdap.cdap.common.id.Id) InstanceId(io.cdap.cdap.proto.id.InstanceId) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) EntityId(io.cdap.cdap.proto.id.EntityId) ProgramId(io.cdap.cdap.proto.id.ProgramId) KerberosPrincipalId(io.cdap.cdap.proto.id.KerberosPrincipalId) InvalidArtifactException(io.cdap.cdap.common.InvalidArtifactException) ArtifactDetail(io.cdap.cdap.internal.app.runtime.artifact.ArtifactDetail)

Aggregations

Id (io.cdap.cdap.common.id.Id)18 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)16 ProgramId (io.cdap.cdap.proto.id.ProgramId)16 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)15 Set (java.util.Set)12 ApplicationSpecification (io.cdap.cdap.api.app.ApplicationSpecification)11 NotFoundException (io.cdap.cdap.common.NotFoundException)11 Constants (io.cdap.cdap.common.conf.Constants)11 ProgramRunId (io.cdap.cdap.proto.id.ProgramRunId)11 Collections (java.util.Collections)11 HashMap (java.util.HashMap)11 List (java.util.List)11 Map (java.util.Map)11 Nullable (javax.annotation.Nullable)11 Gson (com.google.gson.Gson)10 IOException (java.io.IOException)10 Collection (java.util.Collection)10 HashSet (java.util.HashSet)10 ImmutableMap (com.google.common.collect.ImmutableMap)9 GsonBuilder (com.google.gson.GsonBuilder)9