Search in sources :

Example 41 with ApplicationSpecification

use of co.cask.cdap.api.app.ApplicationSpecification in project cdap by caskdata.

the class ProgramGenerationStageTest method testProgramGenerationForToyApp.

@Test
public void testProgramGenerationForToyApp() throws Exception {
    cConf.set(Constants.AppFabric.OUTPUT_DIR, "programs");
    LocationFactory lf = new LocalLocationFactory(TEMP_FOLDER.newFolder());
    // have to do this since we are not going through the route of create namespace -> deploy application
    // in real scenarios, the namespace directory would already be created
    Location namespaceLocation = lf.create(DefaultId.APPLICATION.getNamespace());
    Locations.mkdirsIfNotExists(namespaceLocation);
    LocationFactory jarLf = new LocalLocationFactory(TEMP_FOLDER.newFolder());
    Location appArchive = AppJarHelper.createDeploymentJar(jarLf, ToyApp.class);
    ApplicationSpecification appSpec = Specifications.from(new ToyApp());
    ApplicationSpecificationAdapter adapter = ApplicationSpecificationAdapter.create(new ReflectionSchemaGenerator());
    ApplicationSpecification newSpec = adapter.fromJson(adapter.toJson(appSpec));
    ProgramGenerationStage pgmStage = new ProgramGenerationStage();
    // Can do better here - fixed right now to run the test.
    pgmStage.process(new StageContext(Object.class));
    pgmStage.process(new ApplicationDeployable(NamespaceId.DEFAULT.artifact("ToyApp", "1.0"), appArchive, DefaultId.APPLICATION, newSpec, null, ApplicationDeployScope.USER));
    Assert.assertTrue(true);
}
Also used : ApplicationSpecification(co.cask.cdap.api.app.ApplicationSpecification) ApplicationSpecificationAdapter(co.cask.cdap.internal.app.ApplicationSpecificationAdapter) ToyApp(co.cask.cdap.ToyApp) ReflectionSchemaGenerator(co.cask.cdap.internal.io.ReflectionSchemaGenerator) LocalLocationFactory(org.apache.twill.filesystem.LocalLocationFactory) StageContext(co.cask.cdap.internal.pipeline.StageContext) LocalLocationFactory(org.apache.twill.filesystem.LocalLocationFactory) LocationFactory(org.apache.twill.filesystem.LocationFactory) Location(org.apache.twill.filesystem.Location) Test(org.junit.Test)

Example 42 with ApplicationSpecification

use of co.cask.cdap.api.app.ApplicationSpecification in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method getInstances.

/**
 * Returns the number of instances for all program runnables 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). Retrieving instances only applies to flows, and user
 * services. For flows, another parameter, "runnableId", must be provided. This corresponds to the
 * flowlet/runnable for which to retrieve the instances.
 * <p>
 * Example input:
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1", "runnableId": "Runnable1"},
 *  {"appId": "App1", "programType": "Mapreduce", "programId": "Mapreduce2"},
 *  {"appId": "App2", "programType": "Flow", "programId": "Flow1", "runnableId": "Flowlet1"}]
 * </code></pre>
 * </p><p>
 * The response will be an array of JsonObjects each of which will contain the three input parameters
 * as well as 3 fields:
 * <ul>
 * <li>"provisioned" which maps to the number of instances actually provided for the input runnable;</li>
 * <li>"requested" which maps to the number of instances the user has requested for the input runnable; and</li>
 * <li>"statusCode" which maps to the http status code for the data in that JsonObjects (200, 400, 404).</li>
 * </ul>
 * </p><p>
 * If an error occurs in the input (for the example above, Flowlet1 does not exist), then all JsonObjects for
 * which the parameters have a valid instances will have the provisioned and requested fields status code fields
 * but all JsonObjects for which the parameters are not valid will have an error message and statusCode.
 * </p><p>
 * For example, if there is no Flowlet1 in the above data, then the response could be 200 OK with the following data:
 * </p>
 * <pre><code>
 * [{"appId": "App1", "programType": "Service", "programId": "Service1", "runnableId": "Runnable1",
 *   "statusCode": 200, "provisioned": 2, "requested": 2},
 *  {"appId": "App1", "programType": "Mapreduce", "programId": "Mapreduce2", "statusCode": 400,
 *   "error": "Program type 'Mapreduce' is not a valid program type to get instances"},
 *  {"appId": "App2", "programType": "Flow", "programId": "Flow1", "runnableId": "Flowlet1", "statusCode": 404,
 *   "error": "Program": Flowlet1 not found"}]
 * </code></pre>
 */
@POST
@Path("/instances")
@AuditPolicy(AuditDetail.REQUEST_BODY)
public void getInstances(FullHttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId) throws IOException, BadRequestException {
    List<BatchRunnable> runnables = validateAndGetBatchInput(request, BATCH_RUNNABLES_TYPE);
    // cache app specs to perform fewer store lookups
    Map<ApplicationId, ApplicationSpecification> appSpecs = new HashMap<>();
    List<BatchRunnableInstances> output = new ArrayList<>(runnables.size());
    for (BatchRunnable runnable : runnables) {
        // cant get instances for things that are not flows, services, or workers
        if (!canHaveInstances(runnable.getProgramType())) {
            output.add(new BatchRunnableInstances(runnable, HttpResponseStatus.BAD_REQUEST.code(), String.format("Program type '%s' is not a valid program type to get instances", runnable.getProgramType().getPrettyName())));
            continue;
        }
        ApplicationId appId = new ApplicationId(namespaceId, runnable.getAppId());
        // populate spec cache if this is the first time we've seen the appid.
        if (!appSpecs.containsKey(appId)) {
            appSpecs.put(appId, store.getApplication(appId));
        }
        ApplicationSpecification spec = appSpecs.get(appId);
        if (spec == null) {
            output.add(new BatchRunnableInstances(runnable, HttpResponseStatus.NOT_FOUND.code(), String.format("App: %s not found", appId)));
            continue;
        }
        ProgramId programId = appId.program(runnable.getProgramType(), runnable.getProgramId());
        output.add(getProgramInstances(runnable, spec, programId));
    }
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(output));
}
Also used : BatchRunnable(co.cask.cdap.proto.BatchRunnable) ApplicationSpecification(co.cask.cdap.api.app.ApplicationSpecification) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BatchRunnableInstances(co.cask.cdap.proto.BatchRunnableInstances) ApplicationId(co.cask.cdap.proto.id.ApplicationId) ProgramId(co.cask.cdap.proto.id.ProgramId) Path(javax.ws.rs.Path) AuditPolicy(co.cask.cdap.common.security.AuditPolicy) POST(javax.ws.rs.POST)

Example 43 with ApplicationSpecification

use of co.cask.cdap.api.app.ApplicationSpecification in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method getMapReduceInfo.

/**
 * Relays job-level and task-level information about a particular MapReduce program run.
 */
@GET
@Path("/apps/{app-id}/mapreduce/{mapreduce-id}/runs/{run-id}/info")
public void getMapReduceInfo(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("app-id") String appId, @PathParam("mapreduce-id") String mapreduceId, @PathParam("run-id") String runId) throws IOException, NotFoundException {
    ProgramId programId = new ProgramId(namespaceId, appId, ProgramType.MAPREDUCE, mapreduceId);
    ProgramRunId run = programId.run(runId);
    ApplicationSpecification appSpec = store.getApplication(programId.getParent());
    if (appSpec == null) {
        throw new NotFoundException(programId.getApplication());
    }
    if (!appSpec.getMapReduce().containsKey(mapreduceId)) {
        throw new NotFoundException(programId);
    }
    RunRecordMeta runRecordMeta = store.getRun(run);
    if (runRecordMeta == null) {
        throw new NotFoundException(run);
    }
    MRJobInfo mrJobInfo = mrJobInfoFetcher.getMRJobInfo(Id.Run.fromEntityId(run));
    mrJobInfo.setState(runRecordMeta.getStatus().name());
    // Multiple startTs / endTs by 1000, to be consistent with Task-level start/stop times returned by JobClient
    // in milliseconds. RunRecord returns seconds value.
    // The start time of the MRJob is when the run record has been marked as STARTED
    mrJobInfo.setStartTime(TimeUnit.SECONDS.toMillis(runRecordMeta.getStartTs()));
    Long stopTs = runRecordMeta.getStopTs();
    if (stopTs != null) {
        mrJobInfo.setStopTime(TimeUnit.SECONDS.toMillis(stopTs));
    }
    // JobClient (in DistributedMRJobInfoFetcher) can return NaN as some of the values, and GSON otherwise fails
    Gson gson = new GsonBuilder().serializeSpecialFloatingPointValues().create();
    responder.sendJson(HttpResponseStatus.OK, gson.toJson(mrJobInfo, mrJobInfo.getClass()));
}
Also used : ApplicationSpecification(co.cask.cdap.api.app.ApplicationSpecification) MRJobInfo(co.cask.cdap.proto.MRJobInfo) GsonBuilder(com.google.gson.GsonBuilder) RunRecordMeta(co.cask.cdap.internal.app.store.RunRecordMeta) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) NotFoundException(co.cask.cdap.common.NotFoundException) Gson(com.google.gson.Gson) ProgramRunId(co.cask.cdap.proto.id.ProgramRunId) ProgramId(co.cask.cdap.proto.id.ProgramId) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 44 with ApplicationSpecification

use of co.cask.cdap.api.app.ApplicationSpecification in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method doGetSchedules.

protected void doGetSchedules(HttpResponder responder, ApplicationId applicationId, @Nullable String workflow, @Nullable String triggerTypeStr, @Nullable String statusStr) throws Exception {
    ApplicationSpecification appSpec = store.getApplication(applicationId);
    if (appSpec == null) {
        throw new NotFoundException(applicationId);
    }
    ProgramScheduleStatus status;
    try {
        status = statusStr == null ? null : ProgramScheduleStatus.valueOf(statusStr);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(String.format("Invalid schedule status '%s'. Must be one of %s.", statusStr, Joiner.on(',').join(ProgramScheduleStatus.values())), e);
    }
    ProtoTrigger.Type triggerType;
    try {
        triggerType = triggerTypeStr == null ? null : ProtoTrigger.Type.valueOfCategoryName(triggerTypeStr);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
    Predicate<ProgramScheduleRecord> predicate = record -> true;
    if (status != null) {
        predicate = predicate.and(record -> record.getMeta().getStatus().equals(status));
    }
    if (triggerType != null) {
        predicate = predicate.and(record -> record.getSchedule().getTrigger().getType().equals(triggerType));
    }
    Collection<ProgramScheduleRecord> schedules;
    if (workflow != null) {
        WorkflowId workflowId = applicationId.workflow(workflow);
        if (appSpec.getWorkflows().get(workflow) == null) {
            throw new NotFoundException(workflowId);
        }
        schedules = programScheduleService.list(workflowId, predicate);
    } else {
        schedules = programScheduleService.list(applicationId, predicate);
    }
    List<ScheduleDetail> details = schedules.stream().map(ProgramScheduleRecord::toScheduleDetail).collect(Collectors.toList());
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(details, Schedulers.SCHEDULE_DETAILS_TYPE));
}
Also used : BatchProgramResult(co.cask.cdap.proto.BatchProgramResult) TypeToken(com.google.gson.reflect.TypeToken) RunRecordMeta(co.cask.cdap.internal.app.store.RunRecordMeta) GsonBuilder(com.google.gson.GsonBuilder) ProgramType(co.cask.cdap.proto.ProgramType) Map(java.util.Map) ConstraintCodec(co.cask.cdap.internal.app.runtime.schedule.constraint.ConstraintCodec) Constraint(co.cask.cdap.internal.schedule.constraint.Constraint) ProgramId(co.cask.cdap.proto.id.ProgramId) EnumSet(java.util.EnumSet) Schedulers(co.cask.cdap.internal.app.runtime.schedule.store.Schedulers) HttpRequest(io.netty.handler.codec.http.HttpRequest) BatchRunnable(co.cask.cdap.proto.BatchRunnable) Set(java.util.Set) FlowSpecification(co.cask.cdap.api.flow.FlowSpecification) Reader(java.io.Reader) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ConflictException(co.cask.cdap.common.ConflictException) StandardCharsets(java.nio.charset.StandardCharsets) ProgramSpecification(co.cask.cdap.api.ProgramSpecification) FlowUtils(co.cask.cdap.internal.app.runtime.flow.FlowUtils) ProgramSchedule(co.cask.cdap.internal.app.runtime.schedule.ProgramSchedule) Containers(co.cask.cdap.proto.Containers) BadRequestException(co.cask.cdap.common.BadRequestException) UnauthorizedException(co.cask.cdap.security.spi.authorization.UnauthorizedException) Joiner(com.google.common.base.Joiner) Singleton(com.google.inject.Singleton) BatchRunnableInstances(co.cask.cdap.proto.BatchRunnableInstances) NotRunningProgramLiveInfo(co.cask.cdap.proto.NotRunningProgramLiveInfo) CaseInsensitiveEnumTypeAdapterFactory(co.cask.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory) NamespaceId(co.cask.cdap.proto.id.NamespaceId) GET(javax.ws.rs.GET) ProgramScheduleStatus(co.cask.cdap.internal.app.runtime.schedule.ProgramScheduleStatus) SatisfiableTrigger(co.cask.cdap.internal.app.runtime.schedule.trigger.SatisfiableTrigger) ArrayList(java.util.ArrayList) AuditPolicy(co.cask.cdap.common.security.AuditPolicy) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) ProgramRunStatus(co.cask.cdap.proto.ProgramRunStatus) Store(co.cask.cdap.app.store.Store) ProgramStatus(co.cask.cdap.proto.ProgramStatus) Constants(co.cask.cdap.common.conf.Constants) Nullable(javax.annotation.Nullable) Charsets(com.google.common.base.Charsets) MRJobInfoFetcher(co.cask.cdap.app.mapreduce.MRJobInfoFetcher) NamespaceQueryAdmin(co.cask.cdap.common.namespace.NamespaceQueryAdmin) AbstractAppFabricHttpHandler(co.cask.cdap.gateway.handlers.util.AbstractAppFabricHttpHandler) ApplicationId(co.cask.cdap.proto.id.ApplicationId) RandomEndpointStrategy(co.cask.cdap.common.discovery.RandomEndpointStrategy) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Futures(com.google.common.util.concurrent.Futures) Instances(co.cask.cdap.proto.Instances) FlowletDefinition(co.cask.cdap.api.flow.FlowletDefinition) HttpResponder(co.cask.http.HttpResponder) AuditDetail(co.cask.cdap.common.security.AuditDetail) JsonObject(com.google.gson.JsonObject) WorkflowId(co.cask.cdap.proto.id.WorkflowId) MethodNotAllowedException(co.cask.cdap.common.MethodNotAllowedException) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) NotImplementedException(co.cask.cdap.common.NotImplementedException) Trigger(co.cask.cdap.api.schedule.Trigger) ProtoTrigger(co.cask.cdap.proto.ProtoTrigger) QueryParam(javax.ws.rs.QueryParam) ServiceUnavailableException(co.cask.cdap.common.ServiceUnavailableException) Gson(com.google.gson.Gson) DefaultValue(javax.ws.rs.DefaultValue) ApplicationSpecification(co.cask.cdap.api.app.ApplicationSpecification) EndpointStrategy(co.cask.cdap.common.discovery.EndpointStrategy) FlowId(co.cask.cdap.proto.id.FlowId) MetricStore(co.cask.cdap.api.metrics.MetricStore) Objects(com.google.common.base.Objects) ProgramStatusTrigger(co.cask.cdap.internal.app.runtime.schedule.trigger.ProgramStatusTrigger) ProgramRuntimeService(co.cask.cdap.app.runtime.ProgramRuntimeService) DELETE(javax.ws.rs.DELETE) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) ProgramScheduleRecord(co.cask.cdap.internal.app.runtime.schedule.ProgramScheduleRecord) Function(com.google.common.base.Function) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) ServiceDiscoverable(co.cask.cdap.common.service.ServiceDiscoverable) ProgramRecord(co.cask.cdap.proto.ProgramRecord) Collectors(java.util.stream.Collectors) Id(co.cask.cdap.common.id.Id) MRJobInfo(co.cask.cdap.proto.MRJobInfo) List(java.util.List) Type(java.lang.reflect.Type) ServiceInstances(co.cask.cdap.proto.ServiceInstances) ProgramScheduleService(co.cask.cdap.scheduler.ProgramScheduleService) BatchProgramStatus(co.cask.cdap.proto.BatchProgramStatus) BatchProgramStart(co.cask.cdap.proto.BatchProgramStart) PathParam(javax.ws.rs.PathParam) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ProgramController(co.cask.cdap.app.runtime.ProgramController) BatchProgram(co.cask.cdap.proto.BatchProgram) ProgramLiveInfo(co.cask.cdap.proto.ProgramLiveInfo) HashMap(java.util.HashMap) ProgramLifecycleService(co.cask.cdap.internal.app.services.ProgramLifecycleService) JsonElement(com.google.gson.JsonElement) HashSet(java.util.HashSet) QueueAdmin(co.cask.cdap.data2.transaction.queue.QueueAdmin) TriggerCodec(co.cask.cdap.internal.app.runtime.schedule.trigger.TriggerCodec) ScheduleId(co.cask.cdap.proto.id.ScheduleId) ScheduleDetail(co.cask.cdap.proto.ScheduleDetail) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) JsonSyntaxException(com.google.gson.JsonSyntaxException) RunRecord(co.cask.cdap.proto.RunRecord) TimeUnit(java.util.concurrent.TimeUnit) ApplicationSpecificationAdapter(co.cask.cdap.internal.app.ApplicationSpecificationAdapter) NotFoundException(co.cask.cdap.common.NotFoundException) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ProgramRunId(co.cask.cdap.proto.id.ProgramRunId) ApplicationSpecification(co.cask.cdap.api.app.ApplicationSpecification) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) NotFoundException(co.cask.cdap.common.NotFoundException) WorkflowId(co.cask.cdap.proto.id.WorkflowId) ProgramScheduleStatus(co.cask.cdap.internal.app.runtime.schedule.ProgramScheduleStatus) ProtoTrigger(co.cask.cdap.proto.ProtoTrigger) BadRequestException(co.cask.cdap.common.BadRequestException) ProgramScheduleRecord(co.cask.cdap.internal.app.runtime.schedule.ProgramScheduleRecord) ScheduleDetail(co.cask.cdap.proto.ScheduleDetail)

Example 45 with ApplicationSpecification

use of co.cask.cdap.api.app.ApplicationSpecification in project cdap by caskdata.

the class ProgramLifecycleHttpHandler method getStatus.

/**
 * Returns status of a type specified by the type{flows,workflows,mapreduce,spark,services,schedules}.
 */
@GET
@Path("/apps/{app-id}/versions/{version-id}/{program-type}/{program-id}/status")
public void getStatus(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("app-id") String appId, @PathParam("version-id") String versionId, @PathParam("program-type") String type, @PathParam("program-id") String programId) throws Exception {
    ApplicationId applicationId = new ApplicationId(namespaceId, appId, versionId);
    if (SCHEDULES.equals(type)) {
        JsonObject json = new JsonObject();
        ScheduleId scheduleId = applicationId.schedule(programId);
        ApplicationSpecification appSpec = store.getApplication(applicationId);
        if (appSpec == null) {
            throw new NotFoundException(applicationId);
        }
        json.addProperty("status", programScheduleService.getStatus(scheduleId).toString());
        responder.sendJson(HttpResponseStatus.OK, json.toString());
        return;
    }
    ProgramType programType;
    try {
        programType = ProgramType.valueOfCategoryName(type);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e);
    }
    ProgramId program = applicationId.program(programType, programId);
    ProgramStatus programStatus = lifecycleService.getProgramStatus(program);
    Map<String, String> status = ImmutableMap.of("status", programStatus.name());
    responder.sendJson(HttpResponseStatus.OK, GSON.toJson(status));
}
Also used : ApplicationSpecification(co.cask.cdap.api.app.ApplicationSpecification) JsonObject(com.google.gson.JsonObject) NamespaceNotFoundException(co.cask.cdap.common.NamespaceNotFoundException) NotFoundException(co.cask.cdap.common.NotFoundException) BadRequestException(co.cask.cdap.common.BadRequestException) ProgramType(co.cask.cdap.proto.ProgramType) ApplicationId(co.cask.cdap.proto.id.ApplicationId) ScheduleId(co.cask.cdap.proto.id.ScheduleId) ProgramId(co.cask.cdap.proto.id.ProgramId) ProgramStatus(co.cask.cdap.proto.ProgramStatus) BatchProgramStatus(co.cask.cdap.proto.BatchProgramStatus) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

ApplicationSpecification (co.cask.cdap.api.app.ApplicationSpecification)104 ApplicationId (co.cask.cdap.proto.id.ApplicationId)47 ProgramId (co.cask.cdap.proto.id.ProgramId)28 Test (org.junit.Test)27 ProgramType (co.cask.cdap.proto.ProgramType)22 FlowSpecification (co.cask.cdap.api.flow.FlowSpecification)16 ApplicationNotFoundException (co.cask.cdap.common.ApplicationNotFoundException)15 NotFoundException (co.cask.cdap.common.NotFoundException)14 ReflectionSchemaGenerator (co.cask.cdap.internal.io.ReflectionSchemaGenerator)12 ProgramRunId (co.cask.cdap.proto.id.ProgramRunId)12 ApplicationSpecificationAdapter (co.cask.cdap.internal.app.ApplicationSpecificationAdapter)11 NamespaceId (co.cask.cdap.proto.id.NamespaceId)11 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)10 ProgramNotFoundException (co.cask.cdap.common.ProgramNotFoundException)9 WordCountApp (co.cask.cdap.WordCountApp)8 ServiceSpecification (co.cask.cdap.api.service.ServiceSpecification)8 IOException (java.io.IOException)8 RunId (org.apache.twill.api.RunId)8 Map (java.util.Map)7