use of org.apache.ignite.spi.metric.ReadOnlyMetricRegistry in project ignite by apache.
the class TcpCommunicationMetricsListener method resetMetrics.
/**
* Resets metrics for this instance.
*/
public void resetMetrics() {
rcvdMsgsMetric.reset();
sentMsgsMetric.reset();
sentBytesMetric.reset();
rcvdBytesMetric.reset();
for (Metric metric : mreg) {
if (metric.name().startsWith(SENT_MESSAGES_BY_TYPE_METRIC_NAME))
metric.reset();
else if (metric.name().startsWith(RECEIVED_MESSAGES_BY_TYPE_METRIC_NAME))
metric.reset();
}
for (ReadOnlyMetricRegistry mreg : spiCtx.metricRegistries()) {
if (mreg.name().startsWith(COMMUNICATION_METRICS_GROUP_NAME + SEPARATOR)) {
mreg.findMetric(SENT_MESSAGES_BY_NODE_CONSISTENT_ID_METRIC_NAME).reset();
mreg.findMetric(RECEIVED_MESSAGES_BY_NODE_CONSISTENT_ID_METRIC_NAME).reset();
}
}
}
use of org.apache.ignite.spi.metric.ReadOnlyMetricRegistry in project ignite by apache.
the class GridManagerAdapter method onKernalStart.
/**
* {@inheritDoc}
*/
@Override
public final void onKernalStart(boolean active) throws IgniteCheckedException {
for (final IgniteSpi spi : spis) {
try {
spi.onContextInitialized(new IgniteSpiContext() {
@Override
public boolean isStopping() {
return ctx.isStopping();
}
@Override
public Collection<ClusterNode> remoteNodes() {
return ctx.discovery().remoteNodes();
}
@Override
public Collection<ClusterNode> nodes() {
return ctx.discovery().allNodes();
}
@Override
public ClusterNode localNode() {
return ctx.discovery().localNode();
}
@Override
public Collection<ClusterNode> remoteDaemonNodes() {
final Collection<ClusterNode> all = ctx.discovery().daemonNodes();
return !localNode().isDaemon() ? all : F.view(all, new IgnitePredicate<ClusterNode>() {
@Override
public boolean apply(ClusterNode n) {
return n.isDaemon();
}
});
}
@Nullable
@Override
public ClusterNode node(UUID nodeId) {
A.notNull(nodeId, "nodeId");
return ctx.discovery().node(nodeId);
}
@Override
public boolean pingNode(UUID nodeId) {
A.notNull(nodeId, "nodeId");
try {
return ctx.discovery().pingNode(nodeId);
} catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
@Override
public void send(ClusterNode node, Serializable msg, String topic) throws IgniteSpiException {
A.notNull(node, "node");
A.notNull(msg, "msg");
A.notNull(topic, "topic");
try {
if (msg instanceof Message)
ctx.io().sendToCustomTopic(node, topic, (Message) msg, SYSTEM_POOL);
else
ctx.io().sendUserMessage(Collections.singletonList(node), msg, topic, false, 0, false);
} catch (IgniteCheckedException e) {
throw unwrapException(e);
}
}
@Override
public void addLocalMessageListener(Object topic, IgniteBiPredicate<UUID, ?> p) {
A.notNull(topic, "topic");
A.notNull(p, "p");
ctx.io().addUserMessageListener(topic, p);
}
@Override
public void removeLocalMessageListener(Object topic, IgniteBiPredicate<UUID, ?> p) {
A.notNull(topic, "topic");
A.notNull(topic, "p");
ctx.io().removeUserMessageListener(topic, p);
}
@Override
public void addMessageListener(GridMessageListener lsnr, String topic) {
A.notNull(lsnr, "lsnr");
A.notNull(topic, "topic");
ctx.io().addMessageListener(topic, lsnr);
}
@Override
public boolean removeMessageListener(GridMessageListener lsnr, String topic) {
A.notNull(lsnr, "lsnr");
A.notNull(topic, "topic");
return ctx.io().removeMessageListener(topic, lsnr);
}
@Override
public void addLocalEventListener(GridLocalEventListener lsnr, int... types) {
A.notNull(lsnr, "lsnr");
ctx.event().addLocalEventListener(lsnr, types);
}
@Override
public boolean removeLocalEventListener(GridLocalEventListener lsnr) {
A.notNull(lsnr, "lsnr");
return ctx.event().removeLocalEventListener(lsnr);
}
@Override
public boolean isEventRecordable(int... types) {
for (int t : types) if (!ctx.event().isRecordable(t))
return false;
return true;
}
@Override
public void recordEvent(Event evt) {
A.notNull(evt, "evt");
if (ctx.event().isRecordable(evt.type()))
ctx.event().record(evt);
}
@Override
public void registerPort(int port, IgnitePortProtocol proto) {
ctx.ports().registerPort(port, proto, spi.getClass());
}
@Override
public void deregisterPort(int port, IgnitePortProtocol proto) {
ctx.ports().deregisterPort(port, proto, spi.getClass());
}
@Override
public void deregisterPorts() {
ctx.ports().deregisterPorts(spi.getClass());
}
@Nullable
@Override
public <K, V> V get(String cacheName, K key) {
return ctx.cache().<K, V>jcache(cacheName).get(key);
}
@Nullable
@Override
public <K, V> V put(String cacheName, K key, V val, long ttl) {
try {
if (ttl > 0) {
ExpiryPolicy plc = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl));
IgniteCache<K, V> cache = ctx.cache().<K, V>publicJCache(cacheName).withExpiryPolicy(plc);
return cache.getAndPut(key, val);
} else
return ctx.cache().<K, V>jcache(cacheName).getAndPut(key, val);
} catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
}
@Nullable
@Override
public <K, V> V putIfAbsent(String cacheName, K key, V val, long ttl) {
try {
if (ttl > 0) {
ExpiryPolicy plc = new TouchedExpiryPolicy(new Duration(MILLISECONDS, ttl));
IgniteCache<K, V> cache = ctx.cache().<K, V>publicJCache(cacheName).withExpiryPolicy(plc);
return cache.getAndPutIfAbsent(key, val);
} else
return ctx.cache().<K, V>jcache(cacheName).getAndPutIfAbsent(key, val);
} catch (IgniteCheckedException e) {
throw CU.convertToCacheException(e);
}
}
@Nullable
@Override
public <K, V> V remove(String cacheName, K key) {
return ctx.cache().<K, V>jcache(cacheName).getAndRemove(key);
}
@Override
public <K> boolean containsKey(String cacheName, K key) {
return ctx.cache().cache(cacheName).containsKey(key);
}
@Override
public int partition(String cacheName, Object key) {
return ctx.cache().cache(cacheName).affinity().partition(key);
}
@Override
public IgniteNodeValidationResult validateNode(ClusterNode node) {
for (GridComponent comp : ctx) {
IgniteNodeValidationResult err = comp.validateNode(node);
if (err != null)
return err;
}
return null;
}
@Nullable
@Override
public IgniteNodeValidationResult validateNode(ClusterNode node, DiscoveryDataBag discoData) {
for (GridComponent comp : ctx) {
if (comp.discoveryDataType() == null)
continue;
IgniteNodeValidationResult err = comp.validateNode(node, discoData.newJoinerDiscoveryData(comp.discoveryDataType().ordinal()));
if (err != null)
return err;
}
return null;
}
@Override
public Collection<SecuritySubject> authenticatedSubjects() {
try {
return ctx.security().authenticatedSubjects();
} catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
@Override
public SecuritySubject authenticatedSubject(UUID subjId) {
try {
return ctx.security().authenticatedSubject(subjId);
} catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
@Override
public MessageFormatter messageFormatter() {
return ctx.io().formatter();
}
@Override
public MessageFactory messageFactory() {
return ctx.io().messageFactory();
}
@Override
public boolean tryFailNode(UUID nodeId, @Nullable String warning) {
return ctx.discovery().tryFailNode(nodeId, warning);
}
@Override
public void failNode(UUID nodeId, @Nullable String warning) {
ctx.discovery().failNode(nodeId, warning);
}
@Override
public void addTimeoutObject(IgniteSpiTimeoutObject obj) {
ctx.timeout().addTimeoutObject(new GridSpiTimeoutObject(obj));
}
@Override
public void removeTimeoutObject(IgniteSpiTimeoutObject obj) {
ctx.timeout().removeTimeoutObject(new GridSpiTimeoutObject(obj));
}
@Override
public Map<String, Object> nodeAttributes() {
return ctx.nodeAttributes();
}
@Override
public boolean communicationFailureResolveSupported() {
return ctx.discovery().communicationErrorResolveSupported();
}
@Override
public void resolveCommunicationFailure(ClusterNode node, Exception err) {
ctx.discovery().resolveCommunicationError(node, err);
}
@Override
public ReadOnlyMetricRegistry getOrCreateMetricRegistry(String name) {
return ctx.metric().registry(name);
}
@Override
public void removeMetricRegistry(String name) {
ctx.metric().remove(name);
}
@Override
public Iterable<ReadOnlyMetricRegistry> metricRegistries() {
return ctx.metric();
}
@Override
public void addMetricRegistryCreationListener(Consumer<ReadOnlyMetricRegistry> lsnr) {
ctx.metric().addMetricRegistryCreationListener(lsnr);
}
/**
* @param e Exception to handle.
* @return GridSpiException Converted exception.
*/
private IgniteSpiException unwrapException(IgniteCheckedException e) {
// Avoid double-wrapping.
if (e.getCause() instanceof IgniteSpiException)
return (IgniteSpiException) e.getCause();
return new IgniteSpiException("Failed to execute SPI context method.", e);
}
});
} catch (IgniteSpiException e) {
throw new IgniteCheckedException("Failed to initialize SPI context.", e);
}
}
onKernalStart0();
}
use of org.apache.ignite.spi.metric.ReadOnlyMetricRegistry in project ignite by apache.
the class GridServiceMetricsTest method testServiceMetrics.
/**
* Invokes service in various ways: from clients, servers, etc. Checks these calls reflect in the metrics.
*
* @param serverCnt Number of server nodes.
* @param clientCnt Number of client nodes.
* @param perClusterCnt Number of service instances per cluster.
* @param perNodeCnt Number of service instances per node.
*/
private void testServiceMetrics(int serverCnt, int clientCnt, int perClusterCnt, int perNodeCnt) throws Throwable {
List<IgniteEx> servers = startGrids(serverCnt, false);
List<IgniteEx> clients = startGrids(clientCnt, true);
servers.get(0).services().deploy(serviceCfg(MyServiceFactory.create(), perClusterCnt, perNodeCnt));
awaitPartitionMapExchange();
List<MyService> serverStickyProxies = servers.stream().map(ignite -> (MyService) ignite.services().serviceProxy(SRVC_NAME, MyService.class, true)).collect(Collectors.toList());
List<MyService> clientStickyProxies = clients.stream().map(ignite -> (MyService) ignite.services().serviceProxy(SRVC_NAME, MyService.class, true)).collect(Collectors.toList());
long invokeCollector = 0;
// Call service through the server proxies.
for (int i = 0; i < INVOKE_CNT; ++i) {
// Call from server.
IgniteEx ignite = servers.get(i % servers.size());
callService4Times(ignite, serverStickyProxies.get(i % serverStickyProxies.size()));
// Call from client.
ignite = clients.get(i % clients.size());
callService4Times(ignite, clientStickyProxies.get(i % clientStickyProxies.size()));
invokeCollector += 8;
}
long invokesInMetrics = 0;
// Calculate and check invocations within the metrics.
for (IgniteEx ignite : servers) {
ReadOnlyMetricRegistry metrics = findMetricRegistry(ignite.context().metric(), SRVC_NAME);
// Metrics may not be deployed on this server node.
if (metrics == null)
continue;
for (Metric metric : metrics) {
if (metric instanceof HistogramMetric)
invokesInMetrics += sumHistogramEntries((HistogramMetric) metric);
}
}
// Compare calls number and metrics number.
assertEquals("Calculated wrong service invocation number.", invokesInMetrics, invokeCollector);
}
use of org.apache.ignite.spi.metric.ReadOnlyMetricRegistry in project ignite by apache.
the class MetricRegistryLocalSystemView method getRows.
/**
* {@inheritDoc}
*/
@Override
public Iterator<Row> getRows(Session ses, SearchRow first, SearchRow last) {
return new Iterator<Row>() {
/**
*/
private Iterator<ReadOnlyMetricRegistry> grps = mreg.iterator();
/**
*/
private Iterator<Metric> curr = Collections.emptyIterator();
/**
*/
private boolean advance() {
while (grps.hasNext()) {
ReadOnlyMetricRegistry mreg = grps.next();
curr = mreg.iterator();
if (curr.hasNext())
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
if (curr.hasNext())
return true;
return advance();
}
/**
* {@inheritDoc}
*/
@Override
public Row next() {
Metric m = curr.next();
return createRow(ses, m.name(), m.getAsString(), m.description());
}
};
}
use of org.apache.ignite.spi.metric.ReadOnlyMetricRegistry in project ignite by apache.
the class IgniteServiceProcessor method redeploy.
/**
* Redeploys local services based on assignments.
* <p/>
* Invokes from services deployment worker.
*
* @param srvcId Service id.
* @param cfg Service configuration.
* @param top Service topology.
* @throws IgniteCheckedException In case of deployment errors.
*/
void redeploy(IgniteUuid srvcId, ServiceConfiguration cfg, Map<UUID, Integer> top) throws IgniteCheckedException {
String name = cfg.getName();
String cacheName = cfg.getCacheName();
Object affKey = cfg.getAffinityKey();
int assignCnt = top.getOrDefault(ctx.localNodeId(), 0);
Collection<ServiceContextImpl> ctxs = locServices.computeIfAbsent(srvcId, c -> new ArrayList<>());
Collection<ServiceContextImpl> toInit = new ArrayList<>();
synchronized (ctxs) {
if (ctxs.size() > assignCnt) {
int cancelCnt = ctxs.size() - assignCnt;
cancel(ctxs, cancelCnt);
} else if (ctxs.size() < assignCnt) {
int createCnt = assignCnt - ctxs.size();
for (int i = 0; i < createCnt; i++) {
ServiceContextImpl srvcCtx = new ServiceContextImpl(name, UUID.randomUUID(), cacheName, affKey, Executors.newSingleThreadExecutor(threadFactory), cfg.isStatisticsEnabled());
ctxs.add(srvcCtx);
toInit.add(srvcCtx);
}
}
}
ReadOnlyMetricRegistry invocationMetrics = null;
for (final ServiceContextImpl srvcCtx : toInit) {
final Service srvc;
try {
srvc = copyAndInject(cfg, srvcCtx);
// Initialize service.
srvc.init(srvcCtx);
srvcCtx.service(srvc);
} catch (Throwable e) {
U.error(log, "Failed to initialize service (service will not be deployed): " + name, e);
synchronized (ctxs) {
ctxs.removeAll(toInit);
}
throw new IgniteCheckedException("Error occured during service initialization: " + "[locId=" + ctx.localNodeId() + ", name=" + name + ']', e);
}
if (log.isInfoEnabled())
log.info("Starting service instance [name=" + srvcCtx.name() + ", execId=" + srvcCtx.executionId() + ']');
if (cfg.isStatisticsEnabled()) {
if (invocationMetrics == null)
invocationMetrics = createServiceMetrics(srvcCtx);
srvcCtx.metrics(invocationMetrics);
}
// Start service in its own thread.
final ExecutorService exe = srvcCtx.executor();
exe.execute(new Runnable() {
@Override
public void run() {
try {
srvc.execute(srvcCtx);
} catch (InterruptedException | IgniteInterruptedCheckedException ignore) {
if (log.isDebugEnabled())
log.debug("Service thread was interrupted [name=" + srvcCtx.name() + ", execId=" + srvcCtx.executionId() + ']');
} catch (IgniteException e) {
if (e.hasCause(InterruptedException.class) || e.hasCause(IgniteInterruptedCheckedException.class)) {
if (log.isDebugEnabled())
log.debug("Service thread was interrupted [name=" + srvcCtx.name() + ", execId=" + srvcCtx.executionId() + ']');
} else {
U.error(log, "Service execution stopped with error [name=" + srvcCtx.name() + ", execId=" + srvcCtx.executionId() + ']', e);
}
} catch (Throwable e) {
U.error(log, "Service execution stopped with error [name=" + srvcCtx.name() + ", execId=" + srvcCtx.executionId() + ']', e);
if (e instanceof Error)
throw (Error) e;
} finally {
// Suicide.
exe.shutdownNow();
}
}
});
}
}
Aggregations