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();
}
}
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();
}
}
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;
}
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());
}
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);
}
}
}
Aggregations