Search in sources :

Example 11 with Id

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

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 12 with Id

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

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 13 with Id

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

the class ProgramLifecycleHttpHandler method stopPrograms.

/**
 * Stops all programs that are passed into the data. The data is an array of JSON objects
 * where each object must contain the following three elements: appId, programType, and programId
 * (flow name, service name, etc.).
 * <p>
 * Example input:
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1"},
 * {"appId": "App1", "programType": "Mapreduce", "programId": "MapReduce2"}]
 * </code></pre>
 * </p><p>
 * The response will be an array of JsonObjects each of which will contain the three input parameters
 * as well as a "statusCode" field which maps to the status code for the data in that JsonObjects.
 * </p><p>
 * If an error occurs in the input (for the example above, App2 does not exist), then all JsonObjects for which the
 * parameters have a valid status will have the status field but all JsonObjects for which the parameters do not have
 * a valid status will have an error message and statusCode.
 * </p><p>
 * For example, if there is no App2 in the data above, then the response would be 200 OK with following possible data:
 * </p>
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1", "statusCode": 200},
 * {"appId": "App1", "programType": "Mapreduce", "programId": "Mapreduce2", "statusCode": 200}]
 * </code></pre>
 */
@POST
@Path("/stop")
@AuditPolicy({ AuditDetail.REQUEST_BODY, AuditDetail.RESPONSE_BODY })
public void stopPrograms(FullHttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId) throws Exception {
    List<BatchProgram> programs = validateAndGetBatchInput(request, BATCH_PROGRAMS_TYPE);
    List<ListenableFuture<BatchProgramResult>> issuedStops = new ArrayList<>(programs.size());
    for (final BatchProgram program : programs) {
        ProgramId programId = new ProgramId(namespaceId, program.getAppId(), program.getProgramType(), program.getProgramId());
        try {
            List<ListenableFuture<ProgramRunId>> stops = lifecycleService.issueStop(programId, null);
            for (ListenableFuture<ProgramRunId> stop : stops) {
                ListenableFuture<BatchProgramResult> issuedStop = Futures.transform(stop, (Function<ProgramRunId, BatchProgramResult>) input -> new BatchProgramResult(program, HttpResponseStatus.OK.code(), null, input.getRun()));
                issuedStops.add(issuedStop);
            }
        } catch (NotFoundException e) {
            issuedStops.add(Futures.immediateFuture(new BatchProgramResult(program, HttpResponseStatus.NOT_FOUND.code(), e.getMessage())));
        } catch (BadRequestException e) {
            issuedStops.add(Futures.immediateFuture(new BatchProgramResult(program, HttpResponseStatus.BAD_REQUEST.code(), e.getMessage())));
        }
    }
    List<BatchProgramResult> output = new ArrayList<>(programs.size());
    // need to keep this index in case there is an exception getting the future, since we won't have the program
    // information in that scenario
    int i = 0;
    for (ListenableFuture<BatchProgramResult> issuedStop : issuedStops) {
        try {
            output.add(issuedStop.get());
        } catch (Throwable t) {
            LOG.warn(t.getMessage(), t);
            output.add(new BatchProgramResult(programs.get(i), HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), t.getMessage()));
        }
        i++;
    }
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(output));
}
Also used : BatchProgramSchedule(io.cdap.cdap.proto.BatchProgramSchedule) AuditDetail(io.cdap.cdap.common.security.AuditDetail) RunRecordDetail(io.cdap.cdap.internal.app.store.RunRecordDetail) BatchProgramResult(io.cdap.cdap.proto.BatchProgramResult) TypeToken(com.google.gson.reflect.TypeToken) MRJobInfoFetcher(io.cdap.cdap.app.mapreduce.MRJobInfoFetcher) MRJobInfo(io.cdap.cdap.proto.MRJobInfo) GsonBuilder(com.google.gson.GsonBuilder) ScheduledRuntime(io.cdap.cdap.proto.ScheduledRuntime) ProgramScheduleStatus(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleStatus) ScheduleId(io.cdap.cdap.proto.id.ScheduleId) Map(java.util.Map) ProgramStatus(io.cdap.cdap.proto.ProgramStatus) ScheduleDetail(io.cdap.cdap.proto.ScheduleDetail) EnumSet(java.util.EnumSet) HttpRequest(io.netty.handler.codec.http.HttpRequest) Set(java.util.Set) Reader(java.io.Reader) Constraint(io.cdap.cdap.internal.schedule.constraint.Constraint) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) ProgramScheduleRecord(io.cdap.cdap.internal.app.runtime.schedule.ProgramScheduleRecord) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) StandardCharsets(java.nio.charset.StandardCharsets) Id(io.cdap.cdap.common.id.Id) ApplicationSpecificationAdapter(io.cdap.cdap.internal.app.ApplicationSpecificationAdapter) TriggerCodec(io.cdap.cdap.internal.app.runtime.schedule.trigger.TriggerCodec) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) Joiner(com.google.common.base.Joiner) Singleton(com.google.inject.Singleton) RunRecord(io.cdap.cdap.proto.RunRecord) GET(javax.ws.rs.GET) SatisfiableTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.SatisfiableTrigger) UnauthorizedException(io.cdap.cdap.security.spi.authorization.UnauthorizedException) ArrayList(java.util.ArrayList) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) Nullable(javax.annotation.Nullable) Charsets(com.google.common.base.Charsets) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) BatchRunnableInstances(io.cdap.cdap.proto.BatchRunnableInstances) ProgramLiveInfo(io.cdap.cdap.proto.ProgramLiveInfo) ProgramLifecycleService(io.cdap.cdap.internal.app.services.ProgramLifecycleService) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) ConflictException(io.cdap.cdap.common.ConflictException) NotImplementedException(io.cdap.cdap.common.NotImplementedException) ServiceInstances(io.cdap.cdap.proto.ServiceInstances) InputStreamReader(java.io.InputStreamReader) ProgramRuntimeService(io.cdap.cdap.app.runtime.ProgramRuntimeService) Futures(com.google.common.util.concurrent.Futures) ProgramSpecification(io.cdap.cdap.api.ProgramSpecification) Schedulers(io.cdap.cdap.internal.app.runtime.schedule.store.Schedulers) RunCountResult(io.cdap.cdap.proto.RunCountResult) BatchProgramStatus(io.cdap.cdap.proto.BatchProgramStatus) JsonObject(com.google.gson.JsonObject) NamespaceQueryAdmin(io.cdap.cdap.common.namespace.NamespaceQueryAdmin) RandomEndpointStrategy(io.cdap.cdap.common.discovery.RandomEndpointStrategy) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Inject(com.google.inject.Inject) ProgramScheduleService(io.cdap.cdap.scheduler.ProgramScheduleService) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) ServiceUnavailableException(io.cdap.cdap.common.ServiceUnavailableException) EndpointStrategy(io.cdap.cdap.common.discovery.EndpointStrategy) QueryParam(javax.ws.rs.QueryParam) Gson(com.google.gson.Gson) DefaultValue(javax.ws.rs.DefaultValue) Objects(com.google.common.base.Objects) ProgramHistory(io.cdap.cdap.proto.ProgramHistory) ConstraintCodec(io.cdap.cdap.internal.app.runtime.schedule.constraint.ConstraintCodec) DELETE(javax.ws.rs.DELETE) Containers(io.cdap.cdap.proto.Containers) Function(com.google.common.base.Function) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) BatchProgramStart(io.cdap.cdap.proto.BatchProgramStart) BatchRunnable(io.cdap.cdap.proto.BatchRunnable) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Collectors(java.util.stream.Collectors) ProgramStatusTrigger(io.cdap.cdap.internal.app.runtime.schedule.trigger.ProgramStatusTrigger) List(java.util.List) Type(java.lang.reflect.Type) CaseInsensitiveEnumTypeAdapterFactory(io.cdap.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory) Constants(io.cdap.cdap.common.conf.Constants) NotFoundException(io.cdap.cdap.common.NotFoundException) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) BatchProgramHistory(io.cdap.cdap.proto.BatchProgramHistory) BatchProgramCount(io.cdap.cdap.proto.BatchProgramCount) HashMap(java.util.HashMap) ProgramType(io.cdap.cdap.proto.ProgramType) JsonElement(com.google.gson.JsonElement) NotRunningProgramLiveInfo(io.cdap.cdap.proto.NotRunningProgramLiveInfo) HashSet(java.util.HashSet) Trigger(io.cdap.cdap.api.schedule.Trigger) BatchProgram(io.cdap.cdap.proto.BatchProgram) Instances(io.cdap.cdap.proto.Instances) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) AbstractAppFabricHttpHandler(io.cdap.cdap.gateway.handlers.util.AbstractAppFabricHttpHandler) ProtoTrigger(io.cdap.cdap.proto.ProtoTrigger) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) HttpResponder(io.cdap.http.HttpResponder) JsonSyntaxException(com.google.gson.JsonSyntaxException) SchedulerException(io.cdap.cdap.internal.app.runtime.schedule.SchedulerException) ProgramId(io.cdap.cdap.proto.id.ProgramId) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramSchedule(io.cdap.cdap.internal.app.runtime.schedule.ProgramSchedule) Store(io.cdap.cdap.app.store.Store) TimeUnit(java.util.concurrent.TimeUnit) ServiceDiscoverable(io.cdap.cdap.common.service.ServiceDiscoverable) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ArrayList(java.util.ArrayList) BatchProgramResult(io.cdap.cdap.proto.BatchProgramResult) NamespaceNotFoundException(io.cdap.cdap.common.NamespaceNotFoundException) NotFoundException(io.cdap.cdap.common.NotFoundException) ProgramId(io.cdap.cdap.proto.id.ProgramId) Constraint(io.cdap.cdap.internal.schedule.constraint.Constraint) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) BadRequestException(io.cdap.cdap.common.BadRequestException) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) BatchProgram(io.cdap.cdap.proto.BatchProgram) Path(javax.ws.rs.Path) AuditPolicy(io.cdap.cdap.common.security.AuditPolicy) POST(javax.ws.rs.POST)

Example 14 with Id

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

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 15 with Id

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

the class ProgramLifecycleHttpHandlerTest method testProgramStartStopStatusErrors.

@Category(XSlowTests.class)
@Test
public void testProgramStartStopStatusErrors() throws Exception {
    // deploy, check the status
    deploy(AllProgramsApp.class, 200, Constants.Gateway.API_VERSION_3_TOKEN, TEST_NAMESPACE1);
    String appName = AllProgramsApp.NAME;
    String serviceName = AllProgramsApp.NoOpService.NAME;
    String mrName = AllProgramsApp.NoOpMR.NAME;
    // start unknown program
    startProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, "noexist"), 404);
    // start program in unknonw app
    startProgram(Id.Program.from(TEST_NAMESPACE1, "noexist", ProgramType.SERVICE, serviceName), 404);
    // start program in unknown namespace
    startProgram(Id.Program.from("noexist", appName, ProgramType.SERVICE, serviceName), 404);
    // debug unknown program
    debugProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, "noexist"), 404);
    // debug a program that does not support it
    debugProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.MAPREDUCE, mrName), // not implemented
    501);
    // status for unknown program
    programStatus(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, "noexist"), 404);
    // status for program in unknonw app
    programStatus(Id.Program.from(TEST_NAMESPACE1, "noexist", ProgramType.SERVICE, serviceName), 404);
    // status for program in unknown namespace
    programStatus(Id.Program.from("noexist", appName, ProgramType.SERVICE, serviceName), 404);
    // stop unknown program
    stopProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, "noexist"), 404);
    // stop program in unknonw app
    stopProgram(Id.Program.from(TEST_NAMESPACE1, "noexist", ProgramType.SERVICE, serviceName), 404);
    // stop program in unknown namespace
    stopProgram(Id.Program.from("noexist", appName, ProgramType.SERVICE, serviceName), 404);
    // stop program that is not running
    stopProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), 400);
    // stop run of a program with ill-formed run id
    stopProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), "norunid", 400);
    // start program twice
    startProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName));
    verifyProgramRuns(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), ProgramRunStatus.RUNNING);
    startProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), // conflict
    409);
    // get run records for later use
    List<RunRecord> runs = getProgramRuns(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), ProgramRunStatus.RUNNING);
    Assert.assertEquals(1, runs.size());
    String runId = runs.get(0).getPid();
    // stop program
    stopProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), 200);
    waitState(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), "STOPPED");
    // get run records again, should be empty now
    Tasks.waitFor(true, () -> {
        Id.Program id = Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName);
        return getProgramRuns(id, ProgramRunStatus.RUNNING).isEmpty();
    }, 10, TimeUnit.SECONDS);
    // stop run of the program that is not running
    stopProgram(Id.Program.from(TEST_NAMESPACE1, appName, ProgramType.SERVICE, serviceName), runId, // active run not found
    400);
    // cleanup
    HttpResponse response = doDelete(getVersionedAPIPath("apps/", Constants.Gateway.API_VERSION_3_TOKEN, TEST_NAMESPACE1));
    Assert.assertEquals(200, response.getResponseCode());
}
Also used : RunRecord(io.cdap.cdap.proto.RunRecord) HttpResponse(io.cdap.common.http.HttpResponse) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) ServiceId(io.cdap.cdap.proto.id.ServiceId) Id(io.cdap.cdap.common.id.Id) ProfileId(io.cdap.cdap.proto.id.ProfileId) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) ProgramId(io.cdap.cdap.proto.id.ProgramId) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Aggregations

Id (io.cdap.cdap.common.id.Id)36 NamespaceId (io.cdap.cdap.proto.id.NamespaceId)32 ProgramId (io.cdap.cdap.proto.id.ProgramId)32 ApplicationId (io.cdap.cdap.proto.id.ApplicationId)30 Set (java.util.Set)24 ApplicationSpecification (io.cdap.cdap.api.app.ApplicationSpecification)22 NotFoundException (io.cdap.cdap.common.NotFoundException)22 Constants (io.cdap.cdap.common.conf.Constants)22 ProgramRunId (io.cdap.cdap.proto.id.ProgramRunId)22 Collections (java.util.Collections)22 HashMap (java.util.HashMap)22 List (java.util.List)22 Map (java.util.Map)22 Nullable (javax.annotation.Nullable)22 Gson (com.google.gson.Gson)20 IOException (java.io.IOException)20 Collection (java.util.Collection)20 HashSet (java.util.HashSet)20 ImmutableMap (com.google.common.collect.ImmutableMap)18 GsonBuilder (com.google.gson.GsonBuilder)18