com.hazelcast.core.Member Java Examples

The following examples show how to use com.hazelcast.core.Member. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HazelcastTest.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Test
public void doTest() {
    logger.info( "do test" );
    Hazelcast.addInstanceListener( this );

    ITopic<Object> topic = Hazelcast.getTopic( "default" );
    topic.addMessageListener( this );
    topic.publish( "my-message-object" );

    Collection<Instance> instances = Hazelcast.getInstances();
    for ( Instance instance : instances ) {
        logger.info( "ID: [" + instance.getId() + "] Type: [" + instance.getInstanceType() + "]" );
    }

    Set<Member> setMembers = Hazelcast.getCluster().getMembers();
    for ( Member member : setMembers ) {
        logger.info( "isLocalMember " + member.localMember() );
        logger.info( "member.inetsocketaddress " + member.getInetSocketAddress() );
    }
}
 
Example #2
Source File: ClusterNode.java    From modernmt with Apache License 2.0 6 votes vote down vote up
public Future<Translation> submit(TranslationTask task) throws DecoderUnavailableException {
    LanguageDirection language = task.getLanguageDirection();
    LanguageBridge bridge = engine.getLanguageIndex().getLanguageBridge(language);

    Member member;
    if (this.loadBalancing) {
        member = getRandomMember(language, bridge);
    } else {
        member = hazelcast.getCluster().getLocalMember();
        if (!NodeInfo.statusIs(member, Status.RUNNING, Status.DEGRADED))
            throw new DecoderUnavailableException("Local node is not active");
        if (!hasTranslationDirection(member, language, bridge))
            throw new UnsupportedLanguageException(language);
    }

    return translationService.submit(task, member.getAddress());
}
 
Example #3
Source File: MessageServerCluster.java    From sctalk with Apache License 2.0 6 votes vote down vote up
@Async
public void sendToUser(long userId, IMHeader header, MessageLite messageLit) {

    UserClientInfo clientInfo = userClientInfoManager.getUserInfo(userId);

    if (clientInfo != null) {
        Set<String> uuids = messageServerManager.getMemberByNetIds(clientInfo.getRouteConns());
        List<Member> members = toMembers(uuids);

        if (members != null) {

            MessageToUserTask command = new MessageToUserTask(userId, null,
                    new MyClusterMessage(header, messageLit));
            hazelcastInstance.getExecutorService("default").submitToMembers(command, members);
        }
    }
}
 
Example #4
Source File: TimeSeriesMiniCubeManagerHzImpl.java    From minicubes with Apache License 2.0 6 votes vote down vote up
private void handleNewMember(HazelcastInstance instance, Member member) {
    
    // Relationship between Member and MiniCube ID
    IMap<String, String> miniCubeManager = instance.getMap(MINICUBE_MANAGER);
    LOGGER.info("Minicube manager status {}", ObjectUtils.getDisplayString(miniCubeManager));
    
    String key = member.getSocketAddress().toString();
    // FIXME: load-pending status need refactor
    instance.getCluster().getLocalMember().setBooleanAttribute("load-pending", false);
    
    if (miniCubeManager.containsKey(key) && !miniCubeManager.get(key).startsWith("?")) {
        // Maybe node-restart
        LOGGER.info("A node{} restarted, so we need rebuild cube{}", key, miniCubeManager.get(key));
        // Reassign task.
        reassignRole(miniCubeManager.get(key), miniCubeManager.get(key).split("::")[0]);
    } else {
        // First time join into cluster
        String id = "?" + "::" + hzGroupName + "@" + key;
        miniCubeManager.put(key, id);
        
        member.setStringAttribute("cubeId", id);
        LOGGER.info("Add {} into cluster {}", id, hzGroupName);
    }
    LOGGER.info("Set load-pending status to false, enable reassign feature on {}", member);
}
 
Example #5
Source File: TimeSeriesMiniCubeManagerHzImpl.java    From minicubes with Apache License 2.0 6 votes vote down vote up
@Override
protected String pre() {
    Member localMember = instance.getCluster().getLocalMember();
    String member = cubeId.split("@")[1];
    // Check load-pending status
    boolean loadPending = localMember.getBooleanAttribute("load-pending");
    if (loadPending) {
        String newCubeId = timeSeries + "::" + impl.hzGroupName + "@" + member;
        IMap<String, String> miniCubeManager = instance.getMap(MINICUBE_MANAGER);
        miniCubeManager.put(member, newCubeId);
        LOGGER.warn("Only change relationship {} {} when load-pending status.", member, newCubeId);
        return newCubeId;
    }
    
    return null;
}
 
Example #6
Source File: TimeSeriesMiniCubeManagerHzImpl.java    From minicubes with Apache License 2.0 6 votes vote down vote up
@Override
protected String post(MiniCube newMiniCube) {
    
    Member localMember = instance.getCluster().getLocalMember();
    String member = cubeId.split("@")[1];
    
    // Ending build operation
    impl.miniCube = newMiniCube;
    
    String newCubeId = timeSeries + "::" + impl.hzGroupName + "@" + member;
    LOGGER.info("Success to build cube {} from {} and {}", newCubeId, cubeId, timeSeries);
    
    // Put relationship into member
    localMember.setStringAttribute("cubeId", newCubeId);
    IMap<String, String> miniCubeManager = instance.getMap(MINICUBE_MANAGER);
    miniCubeManager.put(member, newCubeId);
    
    return newCubeId;
}
 
Example #7
Source File: LumongoIndex.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public void loadAllSegments() throws Exception {
	indexLock.writeLock().lock();
	try {
		Member self = hazelcastManager.getSelf();
		this.memberToSegmentMap = new HashMap<>();
		this.memberToSegmentMap.put(self, new HashSet<>());
		for (int segmentNumber = 0; segmentNumber < numberOfSegments; segmentNumber++) {
			loadSegment(segmentNumber);
			this.memberToSegmentMap.get(self).add(segmentNumber);
		}

		this.segmentToMemberMap = new HashMap<>();

		for (Member m : memberToSegmentMap.keySet()) {
			for (int i : memberToSegmentMap.get(m)) {
				segmentToMemberMap.put(i, m);
			}
		}
	}
	finally {
		indexLock.writeLock().unlock();
	}
}
 
Example #8
Source File: LumongoIndex.java    From lumongo with Apache License 2.0 6 votes vote down vote up
/**
 * Called on older cluster node when member is removed
 *
 * @param currentMembers
 *            - current cluster members
 * @param memberRemoved
 *            - member that is being removed
 */
public void handleServerRemoved(Set<Member> currentMembers, Member memberRemoved) {
	indexLock.writeLock().lock();
	try {
		Set<Integer> segmentsToRedist = memberToSegmentMap.remove(memberRemoved);
		if (segmentsToRedist != null) {
			Member first = currentMembers.iterator().next();
			memberToSegmentMap.get(first).addAll(segmentsToRedist);
		}

		forceBalance(currentMembers);
	}
	finally {
		indexLock.writeLock().unlock();
	}

}
 
Example #9
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public void handleServerAdded(Set<Member> currentMembers, Member memberAdded, boolean master) throws Exception {
	globalLock.writeLock().lock();
	try {
		if (master) {
			// make sure we can resolve it before transferring segments
			Nodes nodes = clusterHelper.getNodes();
			@SuppressWarnings("unused") LocalNodeConfig localNodeConfig = nodes.find(memberAdded);

			handleServerAdded(currentMembers, memberAdded);
		}

		internalClient.addMember(memberAdded);
	}
	finally {
		globalLock.writeLock().unlock();
	}

}
 
Example #10
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public void updateSegmentMap(String indexName, Map<Member, Set<Integer>> newMemberToSegmentMap) throws Exception {
	globalLock.writeLock().lock();
	try {
		if (!indexMap.containsKey(indexName)) {
			loadIndex(indexName, false);
		}

		LumongoIndex i = indexMap.get(indexName);
		if (i == null) {
			throw new IndexDoesNotExist(indexName);
		}
		i.updateSegmentMap(newMemberToSegmentMap);
	}
	finally {
		globalLock.writeLock().unlock();
	}
}
 
Example #11
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public IndexSettingsResponse updateIndex(String indexName, org.lumongo.cluster.message.LumongoIndex.IndexSettings request)
		throws InvalidIndexConfig, MongoException, IOException {
	globalLock.readLock().lock();
	try {
		log.info("Updating index settings for <" + indexName + ">:\n" + JsonFormat.printer().print(request));
		LumongoIndex i = indexMap.get(indexName);
		if (i == null) {
			throw new IndexDoesNotExist(indexName);
		}

		i.updateIndexSettings(request);

		Set<Member> currentMembers = hazelcastManager.getMembers();
		IExecutorService executorService = hazelcastManager.getExecutorService();

		Member self = hazelcastManager.getSelf();

		for (Member m : currentMembers) {
			try {
				ReloadIndexSettingsTask rist = new ReloadIndexSettingsTask(m.getSocketAddress().getPort(), indexName);
				if (!self.equals(m)) {
					Future<Void> dt = executorService.submitToMember(rist, m);
					dt.get();
				}
				else {
					rist.call();
				}
			}
			catch (Exception e) {
				log.error(e.getClass().getSimpleName() + ": ", e);
			}

		}

		return IndexSettingsResponse.newBuilder().build();
	}
	finally {
		globalLock.readLock().unlock();
	}
}
 
Example #12
Source File: ServerApp.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
private InstanceInfo createInstanceInfo(Member member, Map<String, InstanceInfo> clusterinfo, int webPortOrdinal) throws UnknownHostException {
    LOG.info("clusterinfo size {}", clusterinfo.size());
    int webServerPort = 8080 + webPortOrdinal; //let's start with 8080 and check if this port is free

    Address address = Address.newBuilder()
            .setHostName(member.getAddress().getInetSocketAddress().getHostName())
            .setPort(member.getAddress().getInetSocketAddress().getPort())
            .build();
    InstanceInfo instanceInfo = InstanceInfo.newBuilder()
            .setId(member.getUuid())
            .setAddress(address)
            .setWebServerPort(webServerPort)
            .build();

    LOG.info("webServerPort: {}", webServerPort);
    return instanceInfo;
}
 
Example #13
Source File: Nodes.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public LocalNodeConfig find(Member member) throws Exception {
	InetAddress inetAddress = member.getSocketAddress().getAddress();
	
	String memberIp = inetAddress.getHostAddress();
	String fullHostName = inetAddress.getCanonicalHostName();
	
	int hazelcastPort = member.getSocketAddress().getPort();
	
	Set<HazelcastNode> matches = new HashSet<>();
	matches.add(new HazelcastNode(memberIp, hazelcastPort));
	matches.add(new HazelcastNode(fullHostName, hazelcastPort));
	
	for (HazelcastNode node : nodes.keySet()) {
		if (matches.contains(node)) {
			return nodes.get(node);
		}
		
	}
	
	throw new Exception("Member with memberIp <" + memberIp + "> and fullHostName <" + fullHostName + "> and hazelcast port <" + hazelcastPort
					+ "> not found in cluster membership.  Correctly register the machine with server address or ip that all machines can resolve");
	
}
 
Example #14
Source File: InternalClient.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public ClearResponse clear(Member m, ClearRequest request) throws Exception {
	ReadWriteLock lock = getLockForMember(m);
	lock.readLock().lock();

	InternalRpcConnection rpcConnection = null;
	try {
		rpcConnection = getInternalRpcConnection(m);

		ClearResponse response = rpcConnection.getService().clear(request);

		returnInternalBlockingConnection(m, rpcConnection, true);

		return response;
	}
	catch (Exception e) {
		returnInternalBlockingConnection(m, rpcConnection, false);
		throw e;
	}
	finally {
		lock.readLock().unlock();
	}
}
 
Example #15
Source File: InternalClient.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public GetNumberOfDocsResponse getNumberOfDocs(Member m, GetNumberOfDocsRequest request) throws Exception {
	ReadWriteLock lock = getLockForMember(m);
	lock.readLock().lock();

	InternalRpcConnection rpcConnection = null;
	try {
		rpcConnection = getInternalRpcConnection(m);
		GetNumberOfDocsResponse response = rpcConnection.getService().getNumberOfDocs(request);

		returnInternalBlockingConnection(m, rpcConnection, true);

		return response;
	}
	catch (Exception e) {
		returnInternalBlockingConnection(m, rpcConnection, false);
		throw e;
	}
	finally {
		lock.readLock().unlock();
	}
}
 
Example #16
Source File: InternalClient.java    From lumongo with Apache License 2.0 6 votes vote down vote up
private void returnInternalBlockingConnection(Member m, InternalRpcConnection rpcConnection, boolean valid) {
	InternalRpcConnectionPool connectionPool = internalConnectionPoolMap.get(m);
	if (connectionPool != null) {
		try {
			if (valid) {
				connectionPool.returnObject(rpcConnection);
			}
			else {
				connectionPool.invalidateObject(rpcConnection);
			}
		}
		catch (Exception e) {
			log.error("Failed to return blocking connection to member <" + m + "> pool: ", e);
		}
	}
	else {
		log.error("Failed to return blocking connection to member <" + m + "> pool. Pool does not exist.");
		log.error("Current pool members <" + internalConnectionPoolMap.keySet() + ">");
		if (rpcConnection != null) {
			rpcConnection.close();
		}
	}
}
 
Example #17
Source File: InternalClient.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public void removeMember(Member m) {

		ReadWriteLock lock = getLockForMember(m);
		lock.writeLock().lock();
		try {
			log.info("Removing connection pool for member <" + m + ">");
			InternalRpcConnectionPool connectionPool = internalConnectionPoolMap.remove(m);
			try {
				connectionPool.close();
			}
			catch (Exception e) {
				// exception is deprecated by BaseObjectPool close
			}
		}
		finally {
			lock.writeLock().unlock();
		}

	}
 
Example #18
Source File: InternalClient.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public void addMember(Member m) throws Exception {
	ReadWriteLock lock = getLockForMember(m);
	lock.writeLock().lock();
	try {

		if (!internalConnectionPoolMap.containsKey(m)) {
			Nodes nodes = clusterHelper.getNodes();

			LocalNodeConfig localNodeConfig = nodes.find(m);

			int internalServicePort = localNodeConfig.getInternalServicePort();

			log.info("Adding connection pool for member <" + m + "> using port <" + internalServicePort + ">");

			int maxConnections = clusterConfig.getMaxInternalClientConnections();

			internalConnectionPoolMap.put(m, new InternalRpcConnectionPool(m.getSocketAddress().getHostName(), internalServicePort, maxConnections));
		}
		else {
			log.info("Already loaded connection for member <" + m + ">");
		}
	}
	finally {
		lock.writeLock().unlock();
	}
}
 
Example #19
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 6 votes vote down vote up
public void openConnections(Set<Member> members) throws Exception {

		globalLock.writeLock().lock();
		try {
			Member self = hazelcastManager.getSelf();
			for (Member m : members) {
				if (!self.equals(m)) {
					internalClient.addMember(m);
				}
			}
		}
		finally {
			globalLock.writeLock().unlock();
		}

	}
 
Example #20
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 5 votes vote down vote up
private void handleServerAdded(Set<Member> currentMembers, Member memberAdded) {
	globalLock.writeLock().lock();
	try {
		for (String key : indexMap.keySet()) {
			LumongoIndex i = indexMap.get(key);
			i.handleServerAdded(currentMembers, memberAdded);
		}
	}
	finally {
		globalLock.writeLock().unlock();
	}
}
 
Example #21
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 5 votes vote down vote up
public StoreResponse storeDocument(StoreRequest storeRequest) throws Exception {
	globalLock.readLock().lock();
	try {

		String uniqueId = storeRequest.getUniqueId();
		String indexName = storeRequest.getIndexName();

		LumongoIndex i = indexMap.get(indexName);
		if (i == null) {
			throw new IndexDoesNotExist(indexName);
		}

		Member m = i.findMember(uniqueId);

		Member self = hazelcastManager.getSelf();

		if (!self.equals(m)) {
			return internalClient.executeStore(m, storeRequest);
		}
		else {
			return storeInternal(storeRequest);
		}

	}
	finally {
		globalLock.readLock().unlock();
	}

}
 
Example #22
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 5 votes vote down vote up
public DeleteResponse deleteDocument(DeleteRequest deleteRequest) throws Exception {
	globalLock.readLock().lock();
	try {

		String indexName = deleteRequest.getIndexName();
		String uniqueId = deleteRequest.getUniqueId();

		LumongoIndex i = indexMap.get(indexName);
		if (i == null) {
			throw new IndexDoesNotExist(indexName);
		}

		Member m = i.findMember(uniqueId);

		Member self = hazelcastManager.getSelf();

		if (!self.equals(m)) {
			return internalClient.executeDelete(m, deleteRequest);
		}
		else {
			return internalDeleteDocument(deleteRequest);
		}

	}
	finally {
		globalLock.readLock().unlock();
	}
}
 
Example #23
Source File: MyClusterMessageListener.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
     * @param commandId
     * @param clusterMessage
     * @since 1.0
     */
    private void doBuddyList(short commandId, MyClusterMessage clusterMessage, Member member) {
        logger.debug("doBuddyList");
        IMHeader header = clusterMessage.getHeader();
        try {
            MessageLite body = clusterMessage.getMessage();
            switch (commandId) {
                case BuddyListCmdID.CID_BUDDY_LIST_STATUS_NOTIFY_VALUE:
                    // send friend online message to client
                    handleStatusNotify(header, body);
                    break;
//                case BuddyListCmdID.CID_BUDDY_LIST_USERS_STATUS_RESPONSE_VALUE:
//                    // send back to user
//                    handleUsersStatus(header, body);
//                    break;
                case BuddyListCmdID.CID_BUDDY_LIST_REMOVE_SESSION_NOTIFY_VALUE:
                    if (!member.localMember()) {
                        removeSessionNotify(header, body);
                    }
                    break;
                case BuddyListCmdID.CID_BUDDY_LIST_AVATAR_CHANGED_NOTIFY_VALUE:
                    handleAvatarChangedNotify(header, body);
                    break;
                case BuddyListCmdID.CID_BUDDY_LIST_SIGN_INFO_CHANGED_NOTIFY_VALUE:
                    signInfoChangedNotify(header, body);
                    break;
                case BuddyListCmdID.CID_BUDDY_LIST_USER_INFO_CHANGED_NOTIFY_VALUE:
                    userInfoChangedNotify(header, body);
                    break;
                default:
                    logger.warn("Unsupport command id {}", commandId);
                    break;
            }
        } catch (IOException e) {
            logger.error("decode failed.", e);
        }
    }
 
Example #24
Source File: MyClusterMessageListener.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * 处理webrtc
 * @param commandId 命令ID
 * @param clusterMessage 消息
 * @param member hazelcast成员
 * @since  1.3
 */
private void doWebrtc(short commandId, MyClusterMessage clusterMessage, Member member) {
    // FIXME webrtc
    logger.debug("doWebrtc");
    IMHeader header = clusterMessage.getHeader();
    try {
        MessageLite body = clusterMessage.getMessage();
        switch (commandId) {
            case AVCallCmdId.CID_AVCALL_CANCEL_REQ_VALUE:
                if (!member.localMember()) {
                    handleInitateCallReq(header, body);
                }
                break;
            case AVCallCmdId.CID_AVCALL_CANCEL_RES_VALUE:
                handleCallCancelReq(header, body);
                break;
            case AVCallCmdId.CID_AVCALL_HUNGUP_REQ_VALUE:
                
                break;
            default:
                logger.warn("Unsupport command id {}", commandId);
                break;
        }
    } catch (IOException e) {
        logger.error("decode failed.", e);
    }
    
}
 
Example #25
Source File: ClusterNode.java    From modernmt with Apache License 2.0 5 votes vote down vote up
private boolean setStatus(Status status, Status... expected) {
    if (expected == null || contains(expected, this.status)) {
        synchronized (this) {
            if (expected == null || contains(expected, this.status)) {
                Status previousStatus = this.status;
                this.status = status;

                if (this.hazelcast != null) {
                    Member localMember = this.hazelcast.getCluster().getLocalMember();
                    NodeInfo.updateStatusInMember(localMember, status);
                }

                if (logger.isDebugEnabled())
                    logger.debug("Cluster node status changed: " + previousStatus + " -> " + status);

                for (StatusListener listener : statusListeners) {
                    try {
                        listener.onStatusChanged(this, this.status, previousStatus);
                    } catch (RuntimeException e) {
                        logger.error("Unexpected exception while updating Node status. Resuming normal operations.", e);
                    }
                }

                return true;
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
}
 
Example #26
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 5 votes vote down vote up
public void handleServerRemoved(Set<Member> currentMembers, Member memberRemoved, boolean master) {
	globalLock.writeLock().lock();
	try {
		if (master) {
			handleServerRemoved(currentMembers, memberRemoved);
		}

		internalClient.removeMember(memberRemoved);
	}
	finally {
		globalLock.writeLock().unlock();
	}

}
 
Example #27
Source File: LumongoIndex.java    From lumongo with Apache License 2.0 5 votes vote down vote up
private void moveSegment(Member fromMember, Member toMember) {
	int valueToMove = memberToSegmentMap.get(fromMember).iterator().next();

	log.info("Moving segment <" + valueToMove + "> from <" + fromMember + "> to <" + toMember + "> of Index <" + indexName + ">");
	memberToSegmentMap.get(fromMember).remove(valueToMove);

	if (!memberToSegmentMap.containsKey(toMember)) {
		memberToSegmentMap.put(toMember, new HashSet<>());
	}

	memberToSegmentMap.get(toMember).add(valueToMove);
}
 
Example #28
Source File: LumongoIndex.java    From lumongo with Apache License 2.0 5 votes vote down vote up
public Member findMember(String uniqueId) {
	indexLock.readLock().lock();
	try {
		int segmentNumber = getSegmentNumberForUniqueId(uniqueId);
		return segmentToMemberMap.get(segmentNumber);
	}
	finally {
		indexLock.readLock().unlock();
	}
}
 
Example #29
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 5 votes vote down vote up
private void handleServerRemoved(Set<Member> currentMembers, Member memberRemoved) {
	globalLock.writeLock().lock();
	try {
		for (String key : indexMap.keySet()) {
			LumongoIndex i = indexMap.get(key);
			i.handleServerRemoved(currentMembers, memberRemoved);
		}
	}
	finally {
		globalLock.writeLock().unlock();
	}
}
 
Example #30
Source File: LumongoIndexManager.java    From lumongo with Apache License 2.0 5 votes vote down vote up
public FetchResponse fetch(FetchRequest request) throws Exception {
	globalLock.readLock().lock();
	try {

		String indexName = request.getIndexName();

		LumongoIndex i = indexMap.get(indexName);
		if (i == null) {
			throw new IndexDoesNotExist(indexName);
		}

		Member m = i.findMember(request.getUniqueId());

		Member self = hazelcastManager.getSelf();

		if (!self.equals(m)) {
			return internalClient.executeFetch(m, request);
		}
		else {
			return internalFetch(request);
		}

	}
	finally {
		globalLock.readLock().unlock();
	}
}