zp_clusternode.cpp 10.6 KB
Newer Older
丁劲犇's avatar
丁劲犇 已提交
1
#include "zp_clusternode.h"
2
#include "zp_clusterterm.h"
丁劲犇's avatar
丁劲犇 已提交
3
namespace ZP_Cluster{
4
	zp_ClusterNode::zp_ClusterNode(zp_ClusterTerm * pTerm, QObject * psock,QObject *parent) :
丁劲犇's avatar
丁劲犇 已提交
5
		ZPTaskEngine::zp_plTaskBase(parent)
6 7 8
	  ,m_pTerm(pTerm)
	  ,m_pSock(psock)
	  ,bTermSet(false)
丁劲犇's avatar
丁劲犇 已提交
9
	{
10 11
		m_currentReadOffset = 0;
		m_currentMessageSize = 0;
12
		m_nPortLAN = m_nPortPub = 0;
13
		m_last_Report = QDateTime::currentDateTime();
14 15 16 17 18
		m_nRemoteClientNums = 0;
	}
	quint32 zp_ClusterNode::clientNums()
	{
		return m_nRemoteClientNums;
丁劲犇's avatar
丁劲犇 已提交
19
	}
20 21 22 23 24 25 26 27 28

	QDateTime zp_ClusterNode::lastActiveTime()
	{
		return m_last_Report;
	}
	QString zp_ClusterNode::termName()
	{
		return m_strTermName;
	}
29
	QHostAddress zp_ClusterNode::addrLAN()
30
	{
31
		return m_addrLAN;
32
	}
33
	int zp_ClusterNode::portLAN()
34
	{
35
		return m_nPortLAN;
36
	}
37 38 39 40 41 42 43 44 45 46

	QHostAddress zp_ClusterNode::addrPub()
	{
		return m_addrPub;
	}
	int zp_ClusterNode::portPub()
	{
		return m_nPortPub;
	}

47 48 49 50 51
	QObject * zp_ClusterNode::sock()
	{
		return m_pSock;
	}

丁劲犇's avatar
丁劲犇 已提交
52
	int zp_ClusterNode::run()
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
	{
		if (bTermSet==true)
		{
			//qDebug()<<QString("%1(%2) Node Martked Deleted, return.\n").arg((unsigned int)this).arg(ref());
			return 0;
		}
		int nCurrSz = -1;
		int nMessage = m_nMessageBlockSize;
		while (--nMessage>=0 && nCurrSz!=0  )
		{
			QByteArray block;
			m_mutex_rawData.lock();
			if (m_list_RawData.size())
				block =  *m_list_RawData.begin();
			m_mutex_rawData.unlock();
			if (block.isEmpty()==false && block.isNull()==false)
			{
				m_currentReadOffset = filter_message(block,m_currentReadOffset);
				if (m_currentReadOffset >= block.size())
				{
					m_mutex_rawData.lock();
					m_list_RawData.pop_front();
					m_currentReadOffset = 0;
					m_mutex_rawData.unlock();
				}
			}
			else
			{
				m_mutex_rawData.lock();
				//pop empty cabs
				if (m_list_RawData.empty()==false)
					m_list_RawData.pop_front();
				m_mutex_rawData.unlock();
			}
			m_mutex_rawData.lock();
			nCurrSz = m_list_RawData.size();
			m_mutex_rawData.unlock();
		}
		m_mutex_rawData.lock();
		nCurrSz = m_list_RawData.size();
		m_mutex_rawData.unlock();
		if (nCurrSz==0)
			return 0;
		return -1;
	}
	//push new binary data into queue
	int zp_ClusterNode::push_new_data(const  QByteArray &  dtarray)
	{
		int res = 0;
		m_mutex_rawData.lock();

		m_list_RawData.push_back(dtarray);
		res = m_list_RawData.size();
		m_mutex_rawData.unlock();
		m_last_Report = QDateTime::currentDateTime();
		return res;
	}

	//!deal one message, affect m_currentRedOffset,m_currentMessageSize,m_currentHeader
	//!return bytes Used.
	int zp_ClusterNode::filter_message(const QByteArray & block, int offset)
	{
		const int blocklen = block.length();
		while (blocklen>offset)
		{
			const char * dataptr = block.constData();

			//Recieve First 2 byte
			while (m_currentMessageSize<2 && blocklen>offset )
			{
				m_currentBlock.push_back(dataptr[offset++]);
				m_currentMessageSize++;
			}
			if (m_currentMessageSize < 2) //First 2 byte not complete
				continue;

			if (m_currentMessageSize==2)
			{
				const char * headerptr = m_currentBlock.constData();
				memcpy((void *)&m_currentHeader,headerptr,2);
			}

			const char * ptrCurrData = m_currentBlock.constData();
			if (m_currentHeader.Mark == 0x1234)
				//Valid Message
			{
				while (m_currentMessageSize< sizeof(CROSS_SVR_MSG::tag_header) && blocklen>offset)
				{
					m_currentBlock.push_back(dataptr[offset++]);
					m_currentMessageSize++;
				}
				if (m_currentMessageSize < sizeof(CROSS_SVR_MSG::tag_header)) //Header not completed.
					continue;
				else if (m_currentMessageSize == sizeof(CROSS_SVR_MSG::tag_header))//Header just  completed.
				{
					const char * headerptr = m_currentBlock.constData();
					memcpy((void *)&m_currentHeader,headerptr,sizeof(CROSS_SVR_MSG::tag_header));

					//continue reading if there is data left behind
					if (block.length()>offset)
					{
						qint32 bitLeft = m_currentHeader.data_length + sizeof(CROSS_SVR_MSG::tag_header)
								-m_currentMessageSize ;
						while (bitLeft>0 && blocklen>offset)
						{
							m_currentBlock.push_back(dataptr[offset++]);
							m_currentMessageSize++;
							bitLeft--;
						}
						//deal block, may be send data as soon as possible;
						deal_current_message_block();
						if (bitLeft>0)
							continue;
						//This Message is Over. Start a new one.
						m_currentMessageSize = 0;
						m_currentBlock = QByteArray();
						continue;
					}
				}
				else
				{
					if (block.length()>offset)
					{
						qint32 bitLeft = m_currentHeader.data_length + sizeof(CROSS_SVR_MSG::tag_header)
								-m_currentMessageSize ;
						while (bitLeft>0 && blocklen>offset)
						{
							m_currentBlock.push_back(dataptr[offset++]);
							m_currentMessageSize++;
							bitLeft--;
						}
						//deal block, may be processed as soon as possible;
						deal_current_message_block();
						if (bitLeft>0)
							continue;
						//This Message is Over. Start a new one.
						m_currentMessageSize = 0;
						m_currentBlock = QByteArray();
						continue;
					}
				} // end if there is more bytes to append
			} //end deal trans message
			else
			{
				emit evt_Message(this,tr("Client Send a unknown start Header %1 %2. Close client immediately.")
								 .arg((int)(ptrCurrData[0])).arg((int)(ptrCurrData[1])));
				m_currentMessageSize = 0;
				m_currentBlock = QByteArray();
				offset = blocklen;
				emit evt_close_client(this->sock());
			}
		} // end while block len > offset

		return offset;
	}
	//in Trans-Level, do nothing.
	int zp_ClusterNode::deal_current_message_block()
丁劲犇's avatar
丁劲犇 已提交
210
	{
211 212 213 214 215 216
		qint32 bytesLeft = m_currentHeader.data_length + sizeof(CROSS_SVR_MSG::tag_header)
				-m_currentMessageSize ;
		const CROSS_SVR_MSG * pMsg =(const CROSS_SVR_MSG *) m_currentBlock.constData();
		switch(m_currentHeader.messagetype)
		{
		case 0x00://Heart Beating
217 218 219 220
			if (bytesLeft==0)
			{
				m_nRemoteClientNums = pMsg->payload.heartBeating.nClients;
			}
221 222
			break;
		case 0x01://basicInfo, when connection established, this message should be used
223 224 225 226 227
//			UnComment code below, will generate debug output.
//			if (m_currentBlock.length()>=64)
//				emit evt_Message(this,"Debug:" + m_currentBlock.toHex().left(64) + "..." + m_currentBlock.toHex().right(64));
//			else
//				emit evt_Message(this,"Debug:" + m_currentBlock.toHex());
丁劲犇's avatar
丁劲犇 已提交
228

229 230 231 232 233 234
			if (bytesLeft==0)
			{
				QString strName ((const char *)pMsg->payload.basicInfo.name);
				if (strName != m_pTerm->name())
				{
					this->m_strTermName = strName;
235 236 237 238
					m_nPortLAN = pMsg->payload.basicInfo.port_LAN;
					m_addrLAN = QHostAddress((const char *)pMsg->payload.basicInfo.Address_LAN);
					m_nPortPub = pMsg->payload.basicInfo.port_Pub;
					m_addrPub = QHostAddress((const char *)pMsg->payload.basicInfo.Address_Pub);
239 240
					if (false==m_pTerm->regisitNewServer(this))
					{
丁劲犇's avatar
丁劲犇 已提交
241
						this->m_strTermName.clear();
丁劲犇's avatar
丁劲犇 已提交
242
						emit evt_Message(this,tr("Info: New Svr already regisited. Ignored.")+strName);
243 244
						emit evt_close_client(this->sock());
					}
245 246 247 248 249
					else
					{
						emit evt_NewSvrConnected(this->termName());
						m_pTerm->BroadcastServers();
					}
250 251 252 253 254 255 256 257 258
				}
				else
				{
					emit evt_Message(this,tr("Can not connect to it-self, Loopback connections is forbidden."));
					emit evt_close_client(this->sock());
				}
			}
			break;
		case 0x02: //Server - broadcast messages
259 260 261 262 263
//			UnComment code below, will generate debug output.
//			if (m_currentBlock.length()>=64)
//				emit evt_Message(this,"Debug:" + m_currentBlock.toHex().left(64) + "..." + m_currentBlock.toHex().right(64));
//			else
//				emit evt_Message(this,"Debug:" + m_currentBlock.toHex());
丁劲犇's avatar
丁劲犇 已提交
264

265 266 267 268 269 270 271 272
			if (bytesLeft==0)
			{
				int nSvrs = pMsg->hearder.data_length / sizeof(CROSS_SVR_MSG::uni_payload::tag_CSM_Broadcast);
				for (int i=0;i<nSvrs;i++)
				{
					QString strName ((const char *)pMsg->payload.broadcastMsg[i].name);
					if (strName != m_pTerm->name() && m_pTerm->SvrNodeFromName(strName)==NULL)
					{
273 274
						QHostAddress addrToConnectTo((const char *)pMsg->payload.broadcastMsg[i].Address_LAN);
						quint16 PortToConnectTo = pMsg->payload.broadcastMsg[i].port_LAN;
丁劲犇's avatar
丁劲犇 已提交
275
						//because cross-connection is not good, we just want the low Addr:port connect to max Addr:Port.
276
						//Connect to New Servers
丁劲犇's avatar
丁劲犇 已提交
277 278 279 280
						if (strName > m_pTerm->name())
							emit evt_connect_to(addrToConnectTo,PortToConnectTo,false);
						else
							emit evt_Message(this,tr("Name %1 <= %2, omitted.").arg(strName).arg(m_pTerm->name()));
281 282 283 284
					}
				}
			}
			break;
285
		case 0x03:
286 287 288 289 290
			//			UnComment code below, will generate debug output.
//			if (m_currentBlock.length()>=64)
//				emit evt_Message(this,"Debug:" + m_currentBlock.toHex().left(64) + "..." + m_currentBlock.toHex().right(64));
//			else
//				emit evt_Message(this,"Debug:" + m_currentBlock.toHex());
丁劲犇's avatar
丁劲犇 已提交
291

292 293 294 295
			if (m_currentMessageSize==m_currentBlock.size())
			{
				QByteArray arraySend ((const char *)(pMsg) + sizeof(CROSS_SVR_MSG::tag_header),
									  m_currentMessageSize - sizeof(CROSS_SVR_MSG::tag_header));
296 297
				if (deal_user_data(arraySend)==true)
					m_currentBlock = QByteArray();
298 299 300
			}
			else
			{
301 302
				if (deal_user_data(m_currentBlock)==true)
					m_currentBlock = QByteArray();
303 304
			}
			break;
305
		default:
306 307
			emit evt_Message(this,tr("Info:Unknown Msg Type got."));
			emit evt_close_client(this->sock());
308 309 310
			break;
		};

丁劲犇's avatar
丁劲犇 已提交
311 312
		return 0;
	}
313 314 315 316 317 318 319

	bool zp_ClusterNode::deal_user_data(const QByteArray & data)
	{
		emit evt_RemoteData_recieved(this->termName(),data);
		return true;
	}

320 321 322 323
	void zp_ClusterNode::CheckHeartBeating()
	{
		QDateTime dtm = QDateTime::currentDateTime();
		qint64 usc = this->m_last_Report.secsTo(dtm);
324
		int nThredHold = m_pTerm->heartBeatingThrdHold();
325 326 327 328 329 330
		if (usc >= nThredHold)
		{
			emit evt_Message(this,tr("Client ") + QString("%1").arg((unsigned int)((quint64)this)) + tr(" is dead, kick out."));
			emit evt_close_client(this->sock());
		}
	}
331 332
	void zp_ClusterNode::SendHelloPackage()
	{
丁劲犇's avatar
丁劲犇 已提交
333
		int nMsgLen = sizeof(CROSS_SVR_MSG::tag_header) + sizeof (CROSS_SVR_MSG::uni_payload::tag_CSM_BasicInfo);
334 335 336 337 338
		QByteArray array(nMsgLen,0);
		CROSS_SVR_MSG * pMsg =(CROSS_SVR_MSG *) array.data();
		pMsg->hearder.Mark = 0x1234;
		pMsg->hearder.data_length = sizeof (CROSS_SVR_MSG::uni_payload::tag_CSM_BasicInfo);
		pMsg->hearder.messagetype = 0x01;
339
		strncpy((char *)(pMsg->payload.basicInfo.name),
340 341
				m_pTerm->name().toStdString().c_str(),
				sizeof(pMsg->payload.basicInfo.name)-1);
342 343 344 345 346 347 348 349 350
		strncpy((char *)(pMsg->payload.basicInfo.Address_LAN),
				m_pTerm->LANAddr().toString().toStdString().c_str(),
				sizeof(pMsg->payload.basicInfo.Address_LAN)-1);

		pMsg->payload.basicInfo.port_LAN = m_pTerm->LANPort();

		strncpy((char *)(pMsg->payload.basicInfo.Address_Pub),
				m_pTerm->PublishAddr().toString().toStdString().c_str(),
				sizeof(pMsg->payload.basicInfo.Address_Pub)-1);
351

352
		pMsg->payload.basicInfo.port_Pub = m_pTerm->PublishPort();
353 354


355 356
		emit evt_SendDataToClient(sock(),array);
	}
丁劲犇's avatar
丁劲犇 已提交
357
}