use of org.apache.ignite.plugin.security.SecurityCredentials in project ignite by apache.
the class ZookeeperDiscoverySpiTestBase method getConfiguration.
/**
* {@inheritDoc}
*/
@Override
protected IgniteConfiguration getConfiguration(final String igniteInstanceName) throws Exception {
if (testSockNio)
System.setProperty(ZOOKEEPER_CLIENT_CNXN_SOCKET, ZkTestClientCnxnSocketNIO.class.getName());
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
if (nodeId != null)
cfg.setNodeId(nodeId);
if (!dfltConsistenId)
cfg.setConsistentId(igniteInstanceName);
ZookeeperDiscoverySpi zkSpi = new ZookeeperDiscoverySpi();
if (joinTimeout != 0)
zkSpi.setJoinTimeout(joinTimeout);
zkSpi.setSessionTimeout(sesTimeout > 0 ? sesTimeout : 10_000);
zkSpi.setClientReconnectDisabled(clientReconnectDisabled);
// Set authenticator for basic sanity tests.
if (auth != null) {
zkSpi.setAuthenticator(auth.apply());
zkSpi.setInternalListener(new IgniteDiscoverySpiInternalListener() {
@Override
public void beforeJoin(ClusterNode locNode, IgniteLogger log) {
ZookeeperClusterNode locNode0 = (ZookeeperClusterNode) locNode;
Map<String, Object> attrs = new HashMap<>(locNode0.getAttributes());
attrs.put(ATTR_SECURITY_CREDENTIALS, new SecurityCredentials(null, null, igniteInstanceName));
locNode0.setAttributes(attrs);
}
@Override
public boolean beforeSendCustomEvent(DiscoverySpi spi, IgniteLogger log, DiscoverySpiCustomMessage msg) {
return false;
}
});
}
spis.put(igniteInstanceName, zkSpi);
if (USE_TEST_CLUSTER) {
assert zkCluster != null;
zkSpi.setZkConnectionString(getTestClusterZkConnectionString());
if (zkRootPath != null)
zkSpi.setZkRootPath(zkRootPath);
} else
zkSpi.setZkConnectionString(getRealClusterZkConnectionString());
cfg.setDiscoverySpi(zkSpi);
cfg.setCacheConfiguration(getCacheConfiguration());
if (userAttrs != null)
cfg.setUserAttributes(userAttrs);
Map<IgnitePredicate<? extends Event>, int[]> lsnrs = new HashMap<>();
if (cfg.isClientMode()) {
UUID currNodeId = cfg.getNodeId();
lsnrs.put(new IgnitePredicate<Event>() {
/**
* Last remembered uuid before node reconnected.
*/
private UUID nodeId = currNodeId;
@Override
public boolean apply(Event evt) {
if (evt.type() == EVT_CLIENT_NODE_RECONNECTED) {
evts.remove(nodeId);
nodeId = evt.node().id();
}
return true;
}
}, new int[] { EVT_CLIENT_NODE_RECONNECTED });
}
lsnrs.put(new IgnitePredicate<Event>() {
/**
*/
@IgniteInstanceResource
private Ignite ignite;
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Override
public boolean apply(Event evt) {
try {
DiscoveryEvent discoveryEvt = (DiscoveryEvent) evt;
UUID locId = ((IgniteKernal) ignite).context().localNodeId();
Map<T2<Integer, Long>, DiscoveryEvent> nodeEvts = evts.get(locId);
if (nodeEvts == null) {
Object old = evts.put(locId, nodeEvts = new LinkedHashMap<>());
assertNull(old);
// If the current node has failed, the local join will never happened.
if (evt.type() != EVT_NODE_FAILED || discoveryEvt.eventNode().consistentId().equals(ignite.configuration().getConsistentId())) {
synchronized (nodeEvts) {
DiscoveryLocalJoinData locJoin = ((IgniteEx) ignite).context().discovery().localJoin();
if (locJoin.event().node().order() == 1)
clusterNum.incrementAndGet();
nodeEvts.put(new T2<>(clusterNum.get(), locJoin.event().topologyVersion()), locJoin.event());
}
}
}
synchronized (nodeEvts) {
DiscoveryEvent old = nodeEvts.put(new T2<>(clusterNum.get(), discoveryEvt.topologyVersion()), discoveryEvt);
assertNull(old);
}
} catch (Throwable e) {
error("Unexpected error [evt=" + evt + ", err=" + e + ']', e);
err = true;
}
return true;
}
}, new int[] { EVT_NODE_JOINED, EVT_NODE_FAILED, EVT_NODE_LEFT });
if (!isMultiJvm())
cfg.setLocalEventListeners(lsnrs);
if (persistence) {
DataStorageConfiguration memCfg = new DataStorageConfiguration().setDefaultDataRegionConfiguration(new DataRegionConfiguration().setMaxSize(100 * 1024 * 1024).setPersistenceEnabled(true)).setPageSize(1024).setWalMode(WALMode.LOG_ONLY);
cfg.setDataStorageConfiguration(memCfg);
}
if (testCommSpi)
cfg.setCommunicationSpi(new ZkTestCommunicationSpi());
if (failCommSpi)
cfg.setCommunicationSpi(new PeerToPeerCommunicationFailureSpi());
if (blockCommSpi) {
cfg.setCommunicationSpi(new TcpBlockCommunicationSpi(igniteInstanceName.contains("block")).setUsePairedConnections(true));
cfg.setNetworkTimeout(500);
}
if (commFailureRslvr != null)
cfg.setCommunicationFailureResolver(commFailureRslvr.apply());
cfg.setIncludeEventTypes(EventType.EVTS_ALL);
return cfg;
}
use of org.apache.ignite.plugin.security.SecurityCredentials in project ignite by apache.
the class GridDiscoveryManager method start.
/** {@inheritDoc} */
@Override
public void start(boolean activeOnStart) throws IgniteCheckedException {
long totSysMemory = -1;
try {
totSysMemory = U.<Long>property(os, "totalPhysicalMemorySize");
} catch (RuntimeException ignored) {
// No-op.
}
ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_PHY_RAM, totSysMemory);
DiscoverySpi spi = getSpi();
discoOrdered = discoOrdered();
histSupported = historySupported();
isLocDaemon = ctx.isDaemon();
hasRslvrs = !ctx.config().isClientMode() && !F.isEmpty(ctx.config().getSegmentationResolvers());
segChkFreq = ctx.config().getSegmentCheckFrequency();
if (hasRslvrs) {
if (segChkFreq < 0)
throw new IgniteCheckedException("Segment check frequency cannot be negative: " + segChkFreq);
if (segChkFreq > 0 && segChkFreq < 2000)
U.warn(log, "Configuration parameter 'segmentCheckFrequency' is too low " + "(at least 2000 ms recommended): " + segChkFreq);
int segResAttemp = ctx.config().getSegmentationResolveAttempts();
if (segResAttemp < 1)
throw new IgniteCheckedException("Segment resolve attempts cannot be negative or zero: " + segResAttemp);
checkSegmentOnStart();
}
metricsUpdateTask = ctx.timeout().schedule(new MetricsUpdater(), METRICS_UPDATE_FREQ, METRICS_UPDATE_FREQ);
spi.setMetricsProvider(createMetricsProvider());
if (ctx.security().enabled()) {
if (isSecurityCompatibilityMode())
ctx.addNodeAttribute(ATTR_SECURITY_COMPATIBILITY_MODE, true);
spi.setAuthenticator(new DiscoverySpiNodeAuthenticator() {
@Override
public SecurityContext authenticateNode(ClusterNode node, SecurityCredentials cred) {
try {
return ctx.security().authenticateNode(node, cred);
} catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
@Override
public boolean isGlobalNodeAuthentication() {
return ctx.security().isGlobalNodeAuthentication();
}
});
}
spi.setListener(new DiscoverySpiListener() {
private long gridStartTime;
/** {@inheritDoc} */
@Override
public void onLocalNodeInitialized(ClusterNode locNode) {
for (IgniteInClosure<ClusterNode> lsnr : localNodeInitLsnrs) lsnr.apply(locNode);
}
@Override
public void onDiscovery(final int type, final long topVer, final ClusterNode node, final Collection<ClusterNode> topSnapshot, final Map<Long, Collection<ClusterNode>> snapshots, @Nullable DiscoverySpiCustomMessage spiCustomMsg) {
DiscoveryCustomMessage customMsg = spiCustomMsg == null ? null : ((CustomMessageWrapper) spiCustomMsg).delegate();
if (skipMessage(type, customMsg))
return;
final ClusterNode locNode = localNode();
if (snapshots != null)
topHist = snapshots;
boolean verChanged;
if (type == EVT_NODE_METRICS_UPDATED)
verChanged = false;
else {
if (type != EVT_NODE_SEGMENTED && type != EVT_CLIENT_NODE_DISCONNECTED && type != EVT_CLIENT_NODE_RECONNECTED && type != DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) {
minorTopVer = 0;
verChanged = true;
} else
verChanged = false;
}
if (type == EVT_NODE_FAILED || type == EVT_NODE_LEFT) {
for (DiscoCache c : discoCacheHist.values()) c.updateAlives(node);
updateClientNodes(node.id());
}
final AffinityTopologyVersion nextTopVer;
if (type == DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) {
assert customMsg != null;
boolean incMinorTopVer = ctx.cache().onCustomEvent(customMsg, new AffinityTopologyVersion(topVer, minorTopVer));
if (incMinorTopVer) {
minorTopVer++;
verChanged = true;
}
nextTopVer = new AffinityTopologyVersion(topVer, minorTopVer);
if (verChanged)
ctx.cache().onDiscoveryEvent(type, node, nextTopVer);
} else {
nextTopVer = new AffinityTopologyVersion(topVer, minorTopVer);
ctx.cache().onDiscoveryEvent(type, node, nextTopVer);
}
if (type == DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) {
for (Class cls = customMsg.getClass(); cls != null; cls = cls.getSuperclass()) {
List<CustomEventListener<DiscoveryCustomMessage>> list = customEvtLsnrs.get(cls);
if (list != null) {
for (CustomEventListener<DiscoveryCustomMessage> lsnr : list) {
try {
lsnr.onCustomEvent(nextTopVer, node, customMsg);
} catch (Exception e) {
U.error(log, "Failed to notify direct custom event listener: " + customMsg, e);
}
}
}
}
}
final DiscoCache discoCache;
// event notifications, since SPI notifies manager about all events from this listener.
if (verChanged) {
discoCache = createDiscoCache(locNode, topSnapshot);
discoCacheHist.put(nextTopVer, discoCache);
boolean set = updateTopologyVersionIfGreater(nextTopVer, discoCache);
assert set || topVer == 0 : "Topology version has not been updated [this.topVer=" + topSnap + ", topVer=" + topVer + ", node=" + node + ", evt=" + U.gridEventName(type) + ']';
} else
// Current version.
discoCache = discoCache();
// If this is a local join event, just save it and do not notify listeners.
if (type == EVT_NODE_JOINED && node.id().equals(locNode.id())) {
if (gridStartTime == 0)
gridStartTime = getSpi().getGridStartTime();
updateTopologyVersionIfGreater(new AffinityTopologyVersion(locNode.order()), discoCache);
startLatch.countDown();
DiscoveryEvent discoEvt = new DiscoveryEvent();
discoEvt.node(ctx.discovery().localNode());
discoEvt.eventNode(node);
discoEvt.type(EVT_NODE_JOINED);
discoEvt.topologySnapshot(topVer, new ArrayList<>(F.view(topSnapshot, FILTER_DAEMON)));
locJoin.onDone(new T2<>(discoEvt, discoCache));
return;
} else if (type == EVT_CLIENT_NODE_DISCONNECTED) {
assert locNode.isClient() : locNode;
assert node.isClient() : node;
((IgniteKernal) ctx.grid()).onDisconnected();
locJoin = new GridFutureAdapter<>();
registeredCaches.clear();
for (AffinityTopologyVersion histVer : discoCacheHist.keySet()) {
Object rmvd = discoCacheHist.remove(histVer);
assert rmvd != null : histVer;
}
topHist.clear();
topSnap.set(new Snapshot(AffinityTopologyVersion.ZERO, createDiscoCache(locNode, Collections.<ClusterNode>emptySet())));
} else if (type == EVT_CLIENT_NODE_RECONNECTED) {
assert locNode.isClient() : locNode;
assert node.isClient() : node;
boolean clusterRestarted = gridStartTime != getSpi().getGridStartTime();
gridStartTime = getSpi().getGridStartTime();
((IgniteKernal) ctx.grid()).onReconnected(clusterRestarted);
ctx.cluster().clientReconnectFuture().listen(new CI1<IgniteFuture<?>>() {
@Override
public void apply(IgniteFuture<?> fut) {
try {
fut.get();
discoWrk.addEvent(type, nextTopVer, node, discoCache, topSnapshot, null);
} catch (IgniteException ignore) {
// No-op.
}
}
});
return;
}
if (type == EVT_CLIENT_NODE_DISCONNECTED || type == EVT_NODE_SEGMENTED || !ctx.clientDisconnected())
discoWrk.addEvent(type, nextTopVer, node, discoCache, topSnapshot, customMsg);
}
});
spi.setDataExchange(new DiscoverySpiDataExchange() {
@Override
public DiscoveryDataBag collect(DiscoveryDataBag dataBag) {
assert dataBag != null;
assert dataBag.joiningNodeId() != null;
if (ctx.localNodeId().equals(dataBag.joiningNodeId())) {
for (GridComponent c : ctx.components()) c.collectJoiningNodeData(dataBag);
} else {
for (GridComponent c : ctx.components()) c.collectGridNodeData(dataBag);
}
return dataBag;
}
@Override
public void onExchange(DiscoveryDataBag dataBag) {
if (ctx.localNodeId().equals(dataBag.joiningNodeId())) {
//NodeAdded msg reached joining node after round-trip over the ring
for (GridComponent c : ctx.components()) {
if (c.discoveryDataType() != null)
c.onGridDataReceived(dataBag.gridDiscoveryData(c.discoveryDataType().ordinal()));
}
} else {
//discovery data from newly joined node has to be applied to the current old node
for (GridComponent c : ctx.components()) {
if (c.discoveryDataType() != null) {
JoiningNodeDiscoveryData data = dataBag.newJoinerDiscoveryData(c.discoveryDataType().ordinal());
if (data != null)
c.onJoiningNodeDataReceived(data);
}
}
}
}
});
startSpi();
registeredDiscoSpi = true;
try {
U.await(startLatch);
} catch (IgniteInterruptedException e) {
throw new IgniteCheckedException("Failed to start discovery manager (thread has been interrupted).", e);
}
// Start segment check worker only if frequency is greater than 0.
if (hasRslvrs && segChkFreq > 0) {
segChkWrk = new SegmentCheckWorker();
segChkThread = new IgniteThread(segChkWrk);
segChkThread.start();
}
locNode = spi.getLocalNode();
checkAttributes(discoCache().remoteNodes());
ctx.service().initCompatibilityMode(discoCache().remoteNodes());
// Start discovery worker.
new IgniteThread(discoWrk).start();
if (log.isDebugEnabled())
log.debug(startInfo());
}
use of org.apache.ignite.plugin.security.SecurityCredentials in project ignite by apache.
the class GridJettyRestHandler method createRequest.
/**
* Creates REST request.
*
* @param cmd Command.
* @param params Parameters.
* @param req Servlet request.
* @return REST request.
* @throws IgniteCheckedException If creation failed.
*/
@Nullable
private GridRestRequest createRequest(GridRestCommand cmd, Map<String, Object> params, HttpServletRequest req) throws IgniteCheckedException {
GridRestRequest restReq;
switch(cmd) {
case GET_OR_CREATE_CACHE:
{
GridRestCacheRequest restReq0 = new GridRestCacheRequest();
restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
String templateName = (String) params.get(TEMPLATE_NAME_PARAM);
if (!F.isEmpty(templateName))
restReq0.templateName(templateName);
String backups = (String) params.get(BACKUPS_PARAM);
CacheConfigurationOverride cfg = new CacheConfigurationOverride();
// Set cache backups.
if (!F.isEmpty(backups)) {
try {
cfg.backups(Integer.parseInt(backups));
} catch (NumberFormatException e) {
throw new IgniteCheckedException("Failed to parse number of cache backups: " + backups, e);
}
}
// Set cache group name.
String cacheGrp = (String) params.get(CACHE_GROUP_PARAM);
if (!F.isEmpty(cacheGrp))
cfg.cacheGroup(cacheGrp);
// Set cache data region name.
String dataRegion = (String) params.get(DATA_REGION_PARAM);
if (!F.isEmpty(dataRegion))
cfg.dataRegion(dataRegion);
// Set cache write mode.
String wrtSyncMode = (String) params.get(WRITE_SYNCHRONIZATION_MODE_PARAM);
if (!F.isEmpty(wrtSyncMode)) {
try {
cfg.writeSynchronizationMode(CacheWriteSynchronizationMode.valueOf(wrtSyncMode));
} catch (IllegalArgumentException e) {
throw new IgniteCheckedException("Failed to parse cache write synchronization mode: " + wrtSyncMode, e);
}
}
if (!cfg.isEmpty())
restReq0.configuration(cfg);
restReq = restReq0;
break;
}
case DESTROY_CACHE:
{
GridRestCacheRequest restReq0 = new GridRestCacheRequest();
restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
restReq = restReq0;
break;
}
case ATOMIC_DECREMENT:
case ATOMIC_INCREMENT:
{
DataStructuresRequest restReq0 = new DataStructuresRequest();
restReq0.key(params.get("key"));
restReq0.initial(longValue("init", params, null));
restReq0.delta(longValue("delta", params, null));
restReq = restReq0;
break;
}
case CACHE_CONTAINS_KEY:
case CACHE_CONTAINS_KEYS:
case CACHE_GET:
case CACHE_GET_ALL:
case CACHE_GET_AND_PUT:
case CACHE_GET_AND_REPLACE:
case CACHE_PUT_IF_ABSENT:
case CACHE_GET_AND_PUT_IF_ABSENT:
case CACHE_PUT:
case CACHE_PUT_ALL:
case CACHE_REMOVE:
case CACHE_REMOVE_VALUE:
case CACHE_REPLACE_VALUE:
case CACHE_GET_AND_REMOVE:
case CACHE_REMOVE_ALL:
case CACHE_CLEAR:
case CACHE_ADD:
case CACHE_CAS:
case CACHE_METRICS:
case CACHE_SIZE:
case CACHE_METADATA:
case CACHE_REPLACE:
case CACHE_APPEND:
case CACHE_PREPEND:
{
GridRestCacheRequest restReq0 = new GridRestCacheRequest();
String cacheName = (String) params.get(CACHE_NAME_PARAM);
restReq0.cacheName(F.isEmpty(cacheName) ? null : cacheName);
String keyType = (String) params.get("keyType");
String valType = (String) params.get("valueType");
restReq0.key(convert(keyType, params.get("key")));
restReq0.value(convert(valType, params.get("val")));
restReq0.value2(convert(valType, params.get("val2")));
Object val1 = convert(valType, params.get("val1"));
if (val1 != null)
restReq0.value(val1);
// Cache operations via REST will use binary objects.
restReq0.cacheFlags(intValue("cacheFlags", params, KEEP_BINARIES_MASK));
restReq0.ttl(longValue("exp", params, null));
if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL || cmd == CACHE_CONTAINS_KEYS) {
List<Object> keys = values(keyType, "k", params);
List<Object> vals = values(valType, "v", params);
if (keys.size() < vals.size())
throw new IgniteCheckedException("Number of keys must be greater or equals to number of values.");
Map<Object, Object> map = U.newHashMap(keys.size());
Iterator<Object> keyIt = keys.iterator();
Iterator<Object> valIt = vals.iterator();
while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);
restReq0.values(map);
}
restReq = restReq0;
break;
}
case TOPOLOGY:
case NODE:
{
GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();
restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));
restReq0.nodeIp((String) params.get("ip"));
restReq0.nodeId(uuidValue("id", params));
restReq = restReq0;
break;
}
case EXE:
case RESULT:
case NOOP:
{
GridRestTaskRequest restReq0 = new GridRestTaskRequest();
restReq0.taskId((String) params.get("id"));
restReq0.taskName((String) params.get("name"));
restReq0.params(values(null, "p", params));
restReq0.async(Boolean.parseBoolean((String) params.get("async")));
restReq0.timeout(longValue("timeout", params, 0L));
restReq = restReq0;
break;
}
case LOG:
{
GridRestLogRequest restReq0 = new GridRestLogRequest();
restReq0.path((String) params.get("path"));
restReq0.from(intValue("from", params, -1));
restReq0.to(intValue("to", params, -1));
restReq = restReq0;
break;
}
case NAME:
case VERSION:
{
restReq = new GridRestRequest();
break;
}
case CLUSTER_ACTIVE:
case CLUSTER_INACTIVE:
case CLUSTER_CURRENT_STATE:
{
GridRestChangeStateRequest restReq0 = new GridRestChangeStateRequest();
if (cmd == CLUSTER_CURRENT_STATE)
restReq0.reqCurrentState();
else
restReq0.active(cmd == CLUSTER_ACTIVE);
restReq = restReq0;
break;
}
case ADD_USER:
case REMOVE_USER:
case UPDATE_USER:
{
RestUserActionRequest restReq0 = new RestUserActionRequest();
restReq0.user((String) params.get("user"));
restReq0.password((String) params.get("password"));
restReq = restReq0;
break;
}
case EXECUTE_SQL_QUERY:
case EXECUTE_SQL_FIELDS_QUERY:
{
RestQueryRequest restReq0 = new RestQueryRequest();
restReq0.sqlQuery((String) params.get("qry"));
restReq0.arguments(values(null, "arg", params).toArray());
restReq0.typeName((String) params.get("type"));
String pageSize = (String) params.get("pageSize");
if (pageSize != null)
restReq0.pageSize(Integer.parseInt(pageSize));
String distributedJoins = (String) params.get("distributedJoins");
if (distributedJoins != null)
restReq0.distributedJoins(Boolean.parseBoolean(distributedJoins));
restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
if (cmd == EXECUTE_SQL_QUERY)
restReq0.queryType(RestQueryRequest.QueryType.SQL);
else
restReq0.queryType(RestQueryRequest.QueryType.SQL_FIELDS);
restReq = restReq0;
break;
}
case EXECUTE_SCAN_QUERY:
{
RestQueryRequest restReq0 = new RestQueryRequest();
restReq0.sqlQuery((String) params.get("qry"));
String pageSize = (String) params.get("pageSize");
if (pageSize != null)
restReq0.pageSize(Integer.parseInt(pageSize));
restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
restReq0.className((String) params.get("className"));
restReq0.queryType(RestQueryRequest.QueryType.SCAN);
restReq = restReq0;
break;
}
case FETCH_SQL_QUERY:
{
RestQueryRequest restReq0 = new RestQueryRequest();
String qryId = (String) params.get("qryId");
if (qryId != null)
restReq0.queryId(Long.parseLong(qryId));
String pageSize = (String) params.get("pageSize");
if (pageSize != null)
restReq0.pageSize(Integer.parseInt(pageSize));
restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
restReq = restReq0;
break;
}
case CLOSE_SQL_QUERY:
{
RestQueryRequest restReq0 = new RestQueryRequest();
String qryId = (String) params.get("qryId");
if (qryId != null)
restReq0.queryId(Long.parseLong(qryId));
restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
restReq = restReq0;
break;
}
default:
throw new IgniteCheckedException("Invalid command: " + cmd);
}
restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));
restReq.command(cmd);
if (params.containsKey(IGNITE_LOGIN) || params.containsKey(IGNITE_PASSWORD)) {
SecurityCredentials cred = new SecurityCredentials((String) params.get(IGNITE_LOGIN), (String) params.get(IGNITE_PASSWORD));
restReq.credentials(cred);
}
String clientId = (String) params.get("clientId");
try {
if (clientId != null)
restReq.clientId(UUID.fromString(clientId));
} catch (Exception ignored) {
// Ignore invalid client id. Rest handler will process this logic.
}
String destId = (String) params.get("destId");
try {
if (destId != null)
restReq.destinationId(UUID.fromString(destId));
} catch (IllegalArgumentException ignored) {
// Don't fail - try to execute locally.
}
String sesTokStr = (String) params.get("sessionToken");
try {
if (sesTokStr != null)
restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
} catch (IllegalArgumentException ignored) {
// Ignore invalid session token.
}
return restReq;
}
use of org.apache.ignite.plugin.security.SecurityCredentials in project ignite by apache.
the class CommandHandler method getSecurityCredentialsProvider.
/**
* @param userName User name for authorization.
* @param password Password for authorization.
* @param clientCfg Thin client configuration to connect to cluster.
* @return Security credentials provider with usage of given user name and password.
* @throws IgniteCheckedException If error occur.
*/
@NotNull
private SecurityCredentialsProvider getSecurityCredentialsProvider(String userName, String password, GridClientConfiguration clientCfg) throws IgniteCheckedException {
SecurityCredentialsProvider securityCredential = clientCfg.getSecurityCredentialsProvider();
if (securityCredential == null)
return new SecurityCredentialsBasicProvider(new SecurityCredentials(userName, password));
final SecurityCredentials credential = securityCredential.credentials();
credential.setLogin(userName);
credential.setPassword(password);
return securityCredential;
}
use of org.apache.ignite.plugin.security.SecurityCredentials in project ignite by apache.
the class CacheCreateDestroyEventSecurityContextTest method testGridClient.
/**
* Tests cache create/destroy event security context in case operation is initiated from the {@link GridClient}.
*/
@Test
public void testGridClient() throws Exception {
operationInitiatorLogin = "grid_client";
GridClientConfiguration cfg = new GridClientConfiguration().setServers(singletonList("127.0.0.1:11211")).setSecurityCredentialsProvider(new SecurityCredentialsBasicProvider(new SecurityCredentials(operationInitiatorLogin, "")));
grid("crd").createCache(cacheConfiguration());
try (GridClient cli = GridClientFactory.start(cfg)) {
checkCacheEvents(() -> cli.state().state(INACTIVE, true), EVT_CACHE_STOPPED);
checkCacheEvents(() -> cli.state().state(ACTIVE, true), EVT_CACHE_STARTED);
}
}
Aggregations