Search in sources :

Example 11 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class CaptureAgentStateRestService method getAgentState.

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("agents/{name}.{format:xml|json}")
@RestQuery(name = "getAgent", description = "Return the state of a given capture agent", pathParameters = { @RestParameter(name = "name", description = "Name of the capture agent", isRequired = true, type = Type.STRING), @RestParameter(name = "format", description = "The output format (json or xml) of the response body.", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = {}, reponses = { @RestResponse(description = "{agentState}", responseCode = SC_OK), @RestResponse(description = "The agent {agentName} does not exist", responseCode = SC_NOT_FOUND), @RestResponse(description = "If the {format} is not xml or json", responseCode = SC_METHOD_NOT_ALLOWED), @RestResponse(description = "iCapture agent state service unavailable", responseCode = SC_SERVICE_UNAVAILABLE) }, returnDescription = "")
public Response getAgentState(@PathParam("name") String agentName, @PathParam("format") String format) throws NotFoundException {
    if (service == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build();
    Agent ret = service.getAgent(agentName);
    logger.debug("Returning agent state for {}", agentName);
    if ("json".equals(format)) {
        return Response.ok(new AgentStateUpdate(ret)).type(MediaType.APPLICATION_JSON).build();
    } else {
        return Response.ok(new AgentStateUpdate(ret)).type(MediaType.APPLICATION_XML).build();
    }
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) AgentStateUpdate(org.opencastproject.capture.admin.api.AgentStateUpdate) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 12 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class CaptureAgentStateServiceImpl method getKnownAgents.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.capture.admin.api.CaptureAgentStateService#getKnownAgents()
 */
@Override
public Map<String, Agent> getKnownAgents() {
    agentCache.cleanUp();
    EntityManager em = null;
    User user = securityService.getUser();
    Organization org = securityService.getOrganization();
    String orgAdmin = org.getAdminRole();
    Set<Role> roles = user.getRoles();
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("Agent.byOrganization");
        q.setParameter("org", securityService.getOrganization().getId());
        // Filter the results in memory if this user is not an administrator
        List<AgentImpl> agents = q.getResultList();
        if (!user.hasRole(SecurityConstants.GLOBAL_ADMIN_ROLE) && !user.hasRole(orgAdmin)) {
            for (Iterator<AgentImpl> iter = agents.iterator(); iter.hasNext(); ) {
                AgentImpl agent = iter.next();
                Set<String> schedulerRoles = agent.getSchedulerRoles();
                // coarse-grained web layer security
                if (schedulerRoles == null || schedulerRoles.isEmpty()) {
                    continue;
                }
                boolean hasSchedulerRole = false;
                for (Role role : roles) {
                    if (schedulerRoles.contains(role.getName())) {
                        hasSchedulerRole = true;
                        break;
                    }
                }
                if (!hasSchedulerRole) {
                    iter.remove();
                }
            }
        }
        // Build the map that the API defines as agent name->agent
        Map<String, Agent> map = new TreeMap<>();
        for (AgentImpl agent : agents) {
            map.put(agent.getName(), updateCachedLastHeardFrom(agent, org.getId()));
        }
        return map;
    } finally {
        if (em != null)
            em.close();
    }
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) Query(javax.persistence.Query) TreeMap(java.util.TreeMap) Role(org.opencastproject.security.api.Role) EntityManager(javax.persistence.EntityManager)

Example 13 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class CaptureAgentStateServiceImpl method setAgentUrl.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.capture.admin.api.CaptureAgentStateService#setAgentUrl(String, String)
 */
@Override
public boolean setAgentUrl(String agentName, String agentUrl) throws NotFoundException {
    Agent agent = getAgent(agentName);
    if (agent.getUrl().equals(agentUrl))
        return false;
    agent.setUrl(agentUrl);
    updateAgentInDatabase((AgentImpl) agent);
    return true;
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent)

Example 14 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class CaptureAgentStateServiceImplTest method testAllAgentsStateTimeout.

@Test
public void testAllAgentsStateTimeout() throws Exception {
    service.setupAgentCache(1, TimeUnit.SECONDS);
    String name = "agent1";
    Long lastHeardFrom = 0L;
    Agent agent = null;
    service.setAgentState(name, IDLE);
    agent = service.getAgent(name);
    assertTrue(lastHeardFrom <= agent.getLastHeardFrom());
    assertTrue(agent.getLastHeardFrom() <= System.currentTimeMillis());
    Thread.sleep(1500);
    Map<String, Agent> agents = service.getKnownAgents();
    assertEquals(OFFLINE, agents.get(name).getState());
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) Test(org.junit.Test)

Example 15 with Agent

use of org.opencastproject.capture.admin.api.Agent in project opencast by opencast.

the class SchedulerRestService method stopCapture.

@DELETE
@Path("capture/{agent}")
@Produces(MediaType.TEXT_PLAIN)
@RestQuery(name = "stopcapture", description = "Stops an immediate capture.", returnDescription = "OK if event were successfully stopped", pathParameters = { @RestParameter(name = "agent", isRequired = true, description = "The agent identifier", type = Type.STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Recording stopped"), @RestResponse(responseCode = HttpServletResponse.SC_NOT_MODIFIED, description = "The recording was already stopped"), @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "There is no such agent"), @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "You do not have permission to stop this immediate capture. Maybe you need to authenticate."), @RestResponse(responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE, description = "The agent is not ready to communicate") })
public Response stopCapture(@PathParam("agent") String agentId) throws NotFoundException, UnauthorizedException {
    if (service == null || agentService == null || prolongingService == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).entity("Scheduler service is unavailable, please wait...").build();
    boolean isAdHoc = false;
    try {
        Agent agent = agentService.getAgent(agentId);
        String registrationType = (String) agent.getConfiguration().get(AGENT_REGISTRATION_TYPE);
        isAdHoc = AGENT_REGISTRATION_TYPE_ADHOC.equals(registrationType);
    } catch (NotFoundException e) {
        logger.debug("Temporarily registered agent '{}' for ad-hoc recording already removed", agentId);
    }
    try {
        String eventId;
        MediaPackage mp;
        DublinCoreCatalog eventCatalog;
        try {
            List<MediaPackage> search = service.search(Opt.some(agentId), Opt.<Date>none(), Opt.some(new Date()), Opt.some(new Date()), Opt.<Date>none());
            if (search.isEmpty()) {
                logger.info("No recording to stop found for agent '{}'!", agentId);
                return Response.notModified().build();
            } else {
                mp = search.get(0);
                eventCatalog = DublinCoreUtil.loadEpisodeDublinCore(workspace, search.get(0)).get();
                eventId = search.get(0).getIdentifier().compact();
            }
        } catch (Exception e) {
            logger.error("Unable to get the immediate recording for agent '{}': {}", agentId, e);
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
        try {
            DCMIPeriod period = EncodingSchemeUtils.decodeMandatoryPeriod(eventCatalog.getFirst(DublinCore.PROPERTY_TEMPORAL));
            eventCatalog.set(PROPERTY_TEMPORAL, EncodingSchemeUtils.encodePeriod(new DCMIPeriod(period.getStart(), new Date()), Precision.Second));
            mp = addCatalog(workspace, IOUtils.toInputStream(eventCatalog.toXmlString(), "UTF-8"), "dublincore.xml", MediaPackageElements.EPISODE, mp);
            service.updateEvent(eventId, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), Opt.some(mp), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
            prolongingService.stop(agentId);
            return Response.ok().build();
        } catch (UnauthorizedException e) {
            throw e;
        } catch (Exception e) {
            logger.error("Unable to update the temporal of event '{}': {}", eventId, e);
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    } catch (Throwable t) {
        throw t;
    } finally {
        if (isAdHoc) {
            agentService.removeAgent(agentId);
            logger.info("Removed temporary agent registration '{}'", agentId);
        }
    }
}
Also used : Agent(org.opencastproject.capture.admin.api.Agent) WebApplicationException(javax.ws.rs.WebApplicationException) DCMIPeriod(org.opencastproject.metadata.dublincore.DCMIPeriod) NotFoundException(org.opencastproject.util.NotFoundException) Date(java.util.Date) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) ParseException(java.text.ParseException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

Agent (org.opencastproject.capture.admin.api.Agent)15 Path (javax.ws.rs.Path)5 RestQuery (org.opencastproject.util.doc.rest.RestQuery)5 Produces (javax.ws.rs.Produces)4 Test (org.junit.Test)4 NotFoundException (org.opencastproject.util.NotFoundException)4 GET (javax.ws.rs.GET)3 JValue (com.entwinemedia.fn.data.json.JValue)2 ParseException (java.text.ParseException)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 EntityManager (javax.persistence.EntityManager)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 AgentStateUpdate (org.opencastproject.capture.admin.api.AgentStateUpdate)2 MediaPackage (org.opencastproject.mediapackage.MediaPackage)2 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)2 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)2 IOException (java.io.IOException)1 LinkedList (java.util.LinkedList)1 Properties (java.util.Properties)1