UDT协议实现分析——数据的发送

连接建立起来之后,我们就可以通过UDT Socket进行数据的收发了。先来看用来发送数据的几个函数。UDT提供了如下的几个函数用于不同目的下的数据发送:

1UDT_API int send(UDTSOCKET u, const char* buf, int len, int flags); 2 3UDT_API int sendmsg(UDTSOCKET u, const char* buf, int len, int ttl = -1, bool inorder = false); 4 5UDT_API int64_t sendfile(UDTSOCKET u, std::fstream& ifs, int64_t& offset, int64_t size, int block = 364000); 6 7UDT_API int64_t sendfile2(UDTSOCKET u, const char* path, int64_t* offset, int64_t size, int block = 364000);

send()用来进行流式的数据发送;sendmsg()用来进行数据报式的数据发送;sendfile()与sendfile2()用来执行文件的发送,流式发送,这两者基本一样,仅有的差异在于,前者接收文件的流来发送,而后者则接收文件的路径。

UDT sendmsg()

这里先来看UDT::sendmsg():

1int CUDT::sendmsg(UDTSOCKET u, const char* buf, int len, int ttl, bool inorder) { 2 try { 3 CUDT* udt = s_UDTUnited.lookup(u); 4 return udt->sendmsg(buf, len, ttl, inorder); 5 } catch (CUDTException &e) { 6 s_UDTUnited.setError(new CUDTException(e)); 7 return ERROR; 8 } catch (bad_alloc&) { 9 s_UDTUnited.setError(new CUDTException(3, 2, 0)); 10 return ERROR; 11 } catch (...) { 12 s_UDTUnited.setError(new CUDTException(-1, 0, 0)); 13 return ERROR; 14 } 15} 16 17 18int sendmsg(UDTSOCKET u, const char* buf, int len, int ttl, bool inorder) { 19 return CUDT::sendmsg(u, buf, len, ttl, inorder); 20}

这个API的实现结构与之前看到的listen()、bind()这些略微有点区别,在CUDT的API层,会调用CUDT 对应的实现函数,调用过程:UDT::sendmsg() -> CUDT::sendmsg(UDTSOCKET u, const char* buf, int len, int ttl, bool inorder) -> CUDT::sendmsg(const char* data, int len, int msttl, bool inorder)。直接来看CUDT::sendmsg(const char* data, int len, int msttl, bool inorder)(src/core.cpp):

1void CUDT::waitBlockingSending(int space) { 2 if (!m_bSynSending) 3 throw CUDTException(6, 1, 0); 4 else { 5 // wait here during a blocking sending 6#ifndef WIN32 7 pthread_mutex_lock(&m_SendBlockLock); 8 if (m_iSndTimeOut < 0) { 9 while (!m_bBroken && m_bConnected && !m_bClosing 10 && ((m_iSndBufSize - m_pSndBuffer->getCurrBufSize()) * m_iPayloadSize < space) && m_bPeerHealth) 11 pthread_cond_wait(&m_SendBlockCond, &m_SendBlockLock); 12 } else { 13 uint64_t exptime = CTimer::getTime() + m_iSndTimeOut * 1000ULL; 14 timespec locktime; 15 16 locktime.tv_sec = exptime / 1000000; 17 locktime.tv_nsec = (exptime % 1000000) * 1000; 18 19 while (!m_bBroken && m_bConnected && !m_bClosing 20 && ((m_iSndBufSize - m_pSndBuffer->getCurrBufSize()) * m_iPayloadSize < space) && m_bPeerHealth 21 && (CTimer::getTime() < exptime)) 22 pthread_cond_timedwait(&m_SendBlockCond, &m_SendBlockLock, &locktime); 23 } 24 pthread_mutex_unlock(&m_SendBlockLock); 25#else 26 if (m_iSndTimeOut < 0) { 27 while (!m_bBroken && m_bConnected && !m_bClosing 28 && ((m_iSndBufSize - m_pSndBuffer->getCurrBufSize()) * m_iPayloadSize < space) && m_bPeerHealth) 29 WaitForSingleObject(m_SendBlockCond, INFINITE); 30 } else { 31 uint64_t exptime = CTimer::getTime() + m_iSndTimeOut * 1000ULL; 32 33 while (!m_bBroken && m_bConnected && !m_bClosing 34 && ((m_iSndBufSize - m_pSndBuffer->getCurrBufSize()) * m_iPayloadSize < space) && m_bPeerHealth 35 && (CTimer::getTime() < exptime)) 36 WaitForSingleObject(m_SendBlockCond, DWORD((exptime - CTimer::getTime()) / 1000)); 37 } 38#endif 39 40 // check the connection status 41 if (m_bBroken || m_bClosing) 42 throw CUDTException(2, 1, 0); 43 else if (!m_bConnected) 44 throw CUDTException(2, 2, 0); 45 else if (!m_bPeerHealth) { 46 m_bPeerHealth = true; 47 throw CUDTException(7); 48 } 49 } 50} 51 52int CUDT::sendmsg(const char* data, int len, int msttl, bool inorder) { 53 if (UDT_STREAM == m_iSockType) 54 throw CUDTException(5, 9, 0); 55 56 // throw an exception if not connected 57 if (m_bBroken || m_bClosing) 58 throw CUDTException(2, 1, 0); 59 else if (!m_bConnected) 60 throw CUDTException(2, 2, 0); 61 62 if (len <= 0) 63 return 0; 64 65 if (len > m_iSndBufSize * m_iPayloadSize) 66 throw CUDTException(5, 12, 0); 67 68 CGuard sendguard(m_SendLock); 69 70 if (m_pSndBuffer->getCurrBufSize() == 0) { 71 // delay the EXP timer to avoid mis-fired timeout 72 uint64_t currtime; 73 CTimer::rdtsc(currtime); 74 m_ullLastRspTime = currtime; 75 } 76 77 if ((m_iSndBufSize - m_pSndBuffer->getCurrBufSize()) * m_iPayloadSize < len) { 78 waitBlockingSending(len); 79 } 80 81 if ((m_iSndBufSize - m_pSndBuffer->getCurrBufSize()) * m_iPayloadSize < len) { 82 if (m_iSndTimeOut >= 0) 83 throw CUDTException(6, 3, 0); 84 85 return 0; 86 } 87 88 // record total time used for sending 89 if (0 == m_pSndBuffer->getCurrBufSize()) 90 m_llSndDurationCounter = CTimer::getTime(); 91 92 // insert the user buffer into the sening list 93 m_pSndBuffer->addBuffer(data, len, msttl, inorder); 94 95 // insert this socket to the snd list if it is not on the list yet 96 m_pSndQueue->m_pSndUList->update(this, false); 97 98 if (m_iSndBufSize <= m_pSndBuffer->getCurrBufSize()) { 99 // write is not available any more 100 s_UDTUnited.m_EPoll.update_events(m_SocketID, m_sPollID, UDT_EPOLL_OUT, false); 101 } 102 103 return len; 104}

CUDT::sendmsg()主要做了如下这样的一些事情:

1. 检查UDT Socket的类型SockType,若为UDT_STREAM则直接抛异常退出,否则继续执行。

2. 检查CUDT的状态,若UDT Socket不处于Connected状态,就抛异常退出,否则继续执行。

3. 检查传入的参数,主要是数据的长度,既不能太大也不能太小。数据长度太小是指,小于等于0;太大是指,超出了CUDT发送缓冲区的最大大小。若参数无效,就返回,否则继续执行。在默认不通过UDT::setsockopt()修改m_iSndBufSize和m_iMSS这些选项的情况下,m_iSndBufSize为8192,m_iPayloadSize为1456,也就是大概12MB。

4. 当CUDT发送缓冲区的已用大小为0时,会将m_ullLastRspTime更新为当前时间。

5. 检查CUDT发送缓冲区中可用大小,若可用大小不足消息的长度时,执行waitBlockingSending()等待有足够大小可用。在waitBlockingSending()中可以看到,它主要处理了这样3中情况:

(1). UDT Socket不是处于同步发送模式。抛异常,结束发送的整个流程。

(2). 发送的超时时间m_iSndTimeOut为一个小于0的无效值,则永久等待,直到UDT Socket被关掉。

(3). 发送的超时时间m_iSndTimeOut为一个大于等于0的有效值,则等待m_iSndTimeOut个ms或UDT Socket被关闭。在CUDT的构造函数中,iSndTimeOut默认是被设置为-1的,但可以通过UDT::setsockopt()进行设置。

对于后两种情况里,若等待过程是由于CUDT状态变得无效而终止,则还将抛出异常以结束发送过程。

6. 检查CUDT发送缓冲区中可用大小,若可用大小不足消息的长度时,则说明waitBlockingSending()可能是因如下的几种情况中的一种出现而结束:

(1). CUDT处于非同步发送模式而直接结束。

(2). CUDT处于同步模式,m_iSndTimeOut为一个有效值,但超市时间到来时仍然没有等到发送缓冲区中有足够的空间。

对于第一种情况的处理是直接返回0。对于第二种情况的处理则是抛出异常。waitBlockingSending()等待过程终结由于UDT Socket而造成的情况,waitBlockingSending()自己会抛出异常的,而不会走到这一步。

7. 当发送缓冲区的已用大小为0时,更新m_llSndDurationCounter为当前时间。

8. 执行m_pSndBuffer->addBuffer(data, len, msttl, inorder)将要发送的数据放入发送缓冲区。

9. 将这个socket加入发送队列SndQueue的发送列表m_pSndUList中。

10. 返回数据长度,也即发送的数据长度。

这也是一个生产与消费的故事。在这里发起发送的线程为生产者,真正将数据发送到网络上的的发送队列RcvQueue的worker线程则为消费者。在UDT::sendmsg()的执行过程中,我们同样只能看到这个故事的一半,生产的那一半。后面会再来分析故事的另一半。

UDT send()

然后来看UDT::send()(src/api.cpp):

1int CUDT::send(UDTSOCKET u, const char* buf, int len, int) { 2 try { 3 CUDT* udt = s_UDTUnited.lookup(u); 4 return udt->send(buf, len); 5 } catch (CUDTException &e) { 6 s_UDTUnited.setError(new CUDTException(e)); 7 return ERROR; 8 } catch (bad_alloc&) { 9 s_UDTUnited.setError(new CUDTException(3, 2, 0)); 10 return ERROR; 11 } catch (...) { 12 s_UDTUnited.setError(new CUDTException(-1, 0, 0)); 13 return ERROR; 14 } 15} 16 17 18int send(UDTSOCKET u, const char* buf, int len, int flags) { 19 return CUDT::send(u, buf, len, flags); 20}

调用用过程:UDT::send() -> CUDT::send(UDTSOCKET u, const char* buf, int len, int) -> CUDT::send(const char* data, int len)。直接来看CUDT::send(const char* data, int len)(src/core.cpp):

1int CUDT::send(const char* data, int len) { 2 if (UDT_DGRAM == m_iSockType) 3 throw CUDTException(5, 10, 0); 4 5 // throw an exception if not connected 6 if (m_bBroken || m_bClosing) 7 throw CUDTException(2, 1, 0); 8 else if (!m_bConnected) 9 throw CUDTException(2, 2, 0); 10 11 if (len <= 0) 12 return 0; 13 14 CGuard sendguard(m_SendLock); 15 16 if (m_pSndBuffer->getCurrBufSize() == 0) { 17 // delay the EXP timer to avoid mis-fired timeout 18 uint64_t currtime; 19 CTimer::rdtsc(currtime); 20 m_ullLastRspTime = currtime; 21 } 22 23 if (m_iSndBufSize <= m_pSndBuffer->getCurrBufSize()) { 24 waitBlockingSending(1); 25 } 26 27 if (m_iSndBufSize <= m_pSndBuffer->getCurrBufSize()) { 28 if (m_iSndTimeOut >= 0) 29 throw CUDTException(6, 3, 0); 30 31 return 0; 32 } 33 34 int size = (m_iSndBufSize - m_pSndBuffer->getCurrBufSize()) * m_iPayloadSize; 35 if (size > len) 36 size = len; 37 38 // record total time used for sending 39 if (0 == m_pSndBuffer->getCurrBufSize()) 40 m_llSndDurationCounter = CTimer::getTime(); 41 42 // insert the user buffer into the sening list 43 m_pSndBuffer->addBuffer(data, size); 44 45 // insert this socket to snd list if it is not on the list yet 46 m_pSndQueue->m_pSndUList->update(this, false); 47 48 if (m_iSndBufSize <= m_pSndBuffer->getCurrBufSize()) { 49 // write is not available any more 50 s_UDTUnited.m_EPoll.update_events(m_SocketID, m_sPollID, UDT_EPOLL_OUT, false); 51 } 52 53 return size; 54}

这个函数与CUDT::sendmsg(const char* data, int len, int msttl, bool inorder)的执行过程极为相似,但还是有如下这样的一些区别:

1. 这个函数的执行要求UDT Socket的类型必须为UDT_STREAM,而不是UDT_DGRAM,这一点与CUDT::sendmsg()正好相反。

2. 要发送的数据的长度,只要大于0就可以了。而在CUDT::sendmsg()中会限制要发送的数据的大小不能超过发送缓冲区的最大大小。

3. 在CUDT::sendmsg()中对数据发送的规则执行的是,要么全部发送,要么一点也不发送。而在这里则是,只要发送缓冲区还没有满,则会将数据尽可能多的加进发送缓冲区以待发送。

其它则完全一样。

发送缓冲区CSndBuffer

来看一下CUDT中用来管理待发送数据的发送缓冲区CSndBuffer,先来看它的定义:

1class CSndBuffer { 2 public: 3 CSndBuffer(int size = 32, int mss = 1500); 4 ~CSndBuffer(); 5 6 // Functionality: 7 // Insert a user buffer into the sending list. 8 // Parameters: 9 // 0) [in] data: pointer to the user data block. 10 // 1) [in] len: size of the block. 11 // 2) [in] ttl: time to live in milliseconds 12 // 3) [in] order: if the block should be delivered in order, for DGRAM only 13 // Returned value: 14 // None. 15 16 void addBuffer(const char* data, int len, int ttl = -1, bool order = false); 17 18 // Functionality: 19 // Read a block of data from file and insert it into the sending list. 20 // Parameters: 21 // 0) [in] ifs: input file stream. 22 // 1) [in] len: size of the block. 23 // Returned value: 24 // actual size of data added from the file. 25 26 int addBufferFromFile(std::fstream& ifs, int len); 27 28 // Functionality: 29 // Find data position to pack a DATA packet from the furthest reading point. 30 // Parameters: 31 // 0) [out] data: the pointer to the data position. 32 // 1) [out] msgno: message number of the packet. 33 // Returned value: 34 // Actual length of data read. 35 36 int readData(char** data, int32_t& msgno); 37 38 // Functionality: 39 // Find data position to pack a DATA packet for a retransmission. 40 // Parameters: 41 // 0) [out] data: the pointer to the data position. 42 // 1) [in] offset: offset from the last ACK point. 43 // 2) [out] msgno: message number of the packet. 44 // 3) [out] msglen: length of the message 45 // Returned value: 46 // Actual length of data read. 47 48 int readData(char** data, const int offset, int32_t& msgno, int& msglen); 49 50 // Functionality: 51 // Update the ACK point and may release/unmap/return the user data according to the flag. 52 // Parameters: 53 // 0) [in] offset: number of packets acknowledged. 54 // Returned value: 55 // None. 56 57 void ackData(int offset); 58 59 // Functionality: 60 // Read size of data still in the sending list. 61 // Parameters: 62 // None. 63 // Returned value: 64 // Current size of the data in the sending list. 65 66 int getCurrBufSize() const; 67 68 private: 69 void increase(); 70 71 private: 72 pthread_mutex_t m_BufLock; // used to synchronize buffer operation 73 74 struct Block { 75 char* m_pcData; // pointer to the data block 76 int m_iLength; // length of the block 77 78 int32_t m_iMsgNo; // message number 79 uint64_t m_OriginTime; // original request time 80 int m_iTTL; // time to live (milliseconds) 81 82 Block* m_pNext; // next block 83 }*m_pBlock, *m_pFirstBlock, *m_pCurrBlock, *m_pLastBlock; 84 85 // m_pBlock: The head pointer 86 // m_pFirstBlock: The first block 87 // m_pCurrBlock: The current block 88 // m_pLastBlock: The last block (if first == last, buffer is empty) 89 90 struct Buffer { 91 char* m_pcData; // buffer 92 int m_iSize; // size 93 Buffer* m_pNext; // next buffer 94 }*m_pBuffer; // physical buffer 95 96 int32_t m_iNextMsgNo; // next message number 97 98 int m_iSize; // buffer size (number of packets) 99 int m_iMSS; // maximum seqment/packet size 100 101 int m_iCount; // number of used blocks 102 103 private: 104 CSndBuffer(const CSndBuffer&); 105 CSndBuffer& operator=(const CSndBuffer&); 106};

在这个结构中,似乎在用几个单链表来管理发送缓冲区的数据存储区,struct Buffer的链表,和struct Block的链表,但这些结构究竟如何组织,每个链表的意义是什么,还是要看下几个成员函数的定义。首先是构造函数:

1CSndBuffer::CSndBuffer(int size, int mss) 2 : m_BufLock(), 3 m_pBlock(NULL), 4 m_pFirstBlock(NULL), 5 m_pCurrBlock(NULL), 6 m_pLastBlock(NULL), 7 m_pBuffer(NULL), 8 m_iNextMsgNo(1), 9 m_iSize(size), 10 m_iMSS(mss), 11 m_iCount(0) { 12 // initial physical buffer of "size" 13 m_pBuffer = new Buffer; 14 m_pBuffer->m_pcData = new char[m_iSize * m_iMSS]; 15 m_pBuffer->m_iSize = m_iSize; 16 m_pBuffer->m_pNext = NULL; 17 18 // circular linked list for out bound packets 19 m_pBlock = new Block; 20 Block* pb = m_pBlock; 21 for (int i = 1; i < m_iSize; ++i) { 22 pb->m_pNext = new Block; 23 pb->m_iMsgNo = 0; 24 pb = pb->m_pNext; 25 } 26 pb->m_pNext = m_pBlock; 27 28 pb = m_pBlock; 29 char* pc = m_pBuffer->m_pcData; 30 for (int i = 0; i < m_iSize; ++i) { 31 pb->m_pcData = pc; 32 pb = pb->m_pNext; 33 pc += m_iMSS; 34 } 35 36 m_pFirstBlock = m_pCurrBlock = m_pLastBlock = m_pBlock; 37 38#ifndef WIN32 39 pthread_mutex_init(&m_BufLock, NULL); 40#else 41 m_BufLock = CreateMutex(NULL, false, NULL); 42#endif 43}

在这个构造函数中会做如下这样一些事情:

1. 在成员初始化列表中初始化所有的成员变量。注意,m_iNextMsgNo被初始化为了1,表示已用blocks数量的m_iCount被初始化为了0。

初始化物理buffer,即分配一个Buffer结构m_pBuffer,为这个Buffer结构分配一块大小为m_iSize * m_iMSS的内存,初始化Buffer结构的m_iSize为m_iSize。m_iSize和m_iMSS的值来自于传入的两个参数size和mss。在connect成功(无论是主动发起连接的UDT Socket,还是由Listening的UDT Socket创建的都一样),创建CSndBuffer时,size值为32,而mss值为m_iPayloadSize。在前面 UDT协议实现分析——连接的建立 一文中我们有仔细地分析过m_iPayloadSize这个值的计算过程。

2. 创建一个Block结构的循环链表,m_pBlock指向链表头。链表的长度同样为m_iSize,也就是32。

3. 初始化前一步创建的链表。使每个Block结构的m_pcData指向m_pBuffer->m_pcData的不同位置,相邻的两个Block结构,所指位置的距离为m_iMSS。

由此不难猜测,Buffer用于实际保存要发送的数据。而Block结构则用于将Buffer的数据缓冲区分段管理。

4. 将m_pFirstBlock、m_pCurrBlock和m_pLastBlock的值都初始化为m_pBlock的值。

5. 初始化用于同步缓冲区操作的m_BufLock。

这里我们弄清了struct Buffer和struct Block,但还是有许多问题还没有弄清楚。m_pBlock,m_pFirstBlock,m_pCurrBlock和m_pLastBlock这几个指针的含义是什么?struct Buffer链表的扩展与收缩,MsgNo的意义等。

接着就来看一下CSndBuffer的其它一些成员函数。来看向CSndBuffer中添加数据的CSndBuffer::addBuffer():

1void CSndBuffer::addBuffer(const char* data, int len, int ttl, bool order) { 2 int size = len / m_iMSS; 3 if ((len % m_iMSS) != 0) 4 size++; 5 6 // dynamically increase sender buffer 7 while (size + m_iCount >= m_iSize) 8 increase(); 9 10 uint64_t time = CTimer::getTime(); 11 int32_t inorder = order; 12 inorder <<= 29; 13 14 Block* s = m_pLastBlock; 15 for (int i = 0; i < size; ++i) { 16 int pktlen = len - i * m_iMSS; 17 if (pktlen > m_iMSS) 18 pktlen = m_iMSS; 19 20 memcpy(s->m_pcData, data + i * m_iMSS, pktlen); 21 s->m_iLength = pktlen; 22 23 s->m_iMsgNo = m_iNextMsgNo | inorder; 24 if (i == 0) 25 s->m_iMsgNo |= 0x80000000; 26 if (i == size - 1) 27 s->m_iMsgNo |= 0x40000000; 28 29 s->m_OriginTime = time; 30 s->m_iTTL = ttl; 31 32 s = s->m_pNext; 33 } 34 m_pLastBlock = s; 35 36 CGuard::enterCS(m_BufLock); 37 m_iCount += size; 38 CGuard::leaveCS(m_BufLock); 39 40 m_iNextMsgNo++; 41 if (m_iNextMsgNo == CMsgNo::m_iMaxMsgNo) 42 m_iNextMsgNo = 1; 43}

这个函数的执行过程大体如下:

1. 向CSndBuffer中添加数据总是以整块Block为单位的,对于最后不满整块Block的数据仍然占用整块Block。在这个函数中做的第一件事情就是,计算添加所有的数据需要的Block的个数。

2. 如果CSndBuffer中的可用空间不足,则扩展CSndBuffer空间的大小,直到能满足添加的数据的需求为止。

3. 计算inorder。

4. 通过一个循环将数据复制到CSndBuffer中。

在这段code中,我们不难想到m_pLastBlock指向的是最后一块已用Block之后的那块Block。

关于UDT的Msg,Msg指的是一次UDT::send()或UDT::sendmsg()所发的全部数据。一个Msg中所有的Block共用了相同的一个m_iNextMsgNo。

这里可以看到UDT中Msg的开始与结束的表示方法:Block的m_iMsgNo的最高两位被用来指示Msg的开始和结束,最高位为1表示Msg的开始,第二高位为1则表示Msg的结束。

5. 更新表示一用Block数的m_iCount。

6. 更新m_iNextMsgNo,达到最大值时会重新回到1。

再来看一个与CSndBuffer::addBuffer()类似的函数CSndBuffer::addBufferFromFile():

1int CSndBuffer::addBufferFromFile(fstream& ifs, int len) { 2 int size = len / m_iMSS; 3 if ((len % m_iMSS) != 0) 4 size++; 5 6 // dynamically increase sender buffer 7 while (size + m_iCount >= m_iSize) 8 increase(); 9 10 Block* s = m_pLastBlock; 11 int total = 0; 12 for (int i = 0; i < size; ++i) { 13 if (ifs.bad() || ifs.fail() || ifs.eof()) 14 break; 15 16 int pktlen = len - i * m_iMSS; 17 if (pktlen > m_iMSS) 18 pktlen = m_iMSS; 19 20 ifs.read(s->m_pcData, pktlen); 21 if ((pktlen = ifs.gcount()) <= 0) 22 break; 23 24 // currently file transfer is only available in streaming mode, message is always in order, ttl = infinite 25 s->m_iMsgNo = m_iNextMsgNo | 0x20000000; 26 if (i == 0) 27 s->m_iMsgNo |= 0x80000000; 28 if (i == size - 1) 29 s->m_iMsgNo |= 0x40000000; 30 31 s->m_iLength = pktlen; 32 s->m_iTTL = -1; 33 s = s->m_pNext; 34 35 total += pktlen; 36 } 37 m_pLastBlock = s; 38 39 CGuard::enterCS(m_BufLock); 40 m_iCount += size; 41 CGuard::leaveCS(m_BufLock); 42 43 m_iNextMsgNo++; 44 if (m_iNextMsgNo == CMsgNo::m_iMaxMsgNo) 45 m_iNextMsgNo = 1; 46 47 return total; 48}

这个函数的执行过程,与CSndBuffer::addBuffer()的执行过程极为相似,仅有的差别在于,在这个函数,是将文件的数据逐步的read进CSndBuffer,而在addBuffer()中则是memcpy。

在CSndBuffer::addBuffer()与CSndBuffer::addBufferFromFile()中有这么多的重复code,实在是很有进一步进行抽象的空间。在循环中拷贝数据时,每次计算剩余了多少字节,然后和m_iMSS进行比较以确定到底要复制多少数据。这种计算和比较在大多数情况下都比较多余,只有在循环的最后一次执行时才真正需要这样的操作。可以通过特殊处理最后一块数据的复制,并将循环的退出条件值改为(size -1)来提升性能。

我们前面提到了CSndBuffer容量的扩展,那这里就来看一下执行单次扩展的increase():

1void CSndBuffer::increase() { 2 int unitsize = m_pBuffer->m_iSize; 3 4 // new physical buffer 5 Buffer* nbuf = NULL; 6 try { 7 nbuf = new Buffer; 8 nbuf->m_pcData = new char[unitsize * m_iMSS]; 9 } catch (...) { 10 delete nbuf; 11 throw CUDTException(3, 2, 0); 12 } 13 nbuf->m_iSize = unitsize; 14 nbuf->m_pNext = NULL; 15 16 // insert the buffer at the end of the buffer list 17 Buffer* p = m_pBuffer; 18 while (NULL != p->m_pNext) 19 p = p->m_pNext; 20 p->m_pNext = nbuf; 21 22 // new packet blocks 23 Block* nblk = NULL; 24 try { 25 nblk = new Block; 26 } catch (...) { 27 delete nblk; 28 throw CUDTException(3, 2, 0); 29 } 30 Block* pb = nblk; 31 for (int i = 1; i < unitsize; ++i) { 32 pb->m_pNext = new Block; 33 pb = pb->m_pNext; 34 } 35 36 // insert the new blocks onto the existing one 37 pb->m_pNext = m_pLastBlock->m_pNext; 38 m_pLastBlock->m_pNext = nblk; 39 40 pb = nblk; 41 char* pc = nbuf->m_pcData; 42 for (int i = 0; i < unitsize; ++i) { 43 pb->m_pcData = pc; 44 pb = pb->m_pNext; 45 pc += m_iMSS; 46 } 47 48 m_iSize += unitsize; 49}

可以看下执行单次容量扩充的含义及过程:

1. 获取CSndBuffer中已有的Block的总数量unitsize。

2. 创建一个Buffer结构,并为它分配数据缓冲区,数据缓冲区的大小为unitsize个Block。由此可见,每一次CSndBuffer的扩展,都会使它的容量加倍。

3. 将前一步创建的Buffer插入到已有的Buffer单链表的尾部。

4. 为前面创建的Buffer,创建对应的Block结构链表,nblk指向这个单链表的头节点,而pb指向这个单链表的尾节点。

5. 如我们前面提到的CSndBuffer中的Block结构是一个循环单向链表,这一步即是将前一步创建的Block单向链表插入CSndBuffer的Block循环链表中。

6. 设置前面创建的所有Block,使它们指向前面创建的Buffer的数据部分的适当位置。

7. 更新表示CSndBuffer中总的Block大小的m_iSize。

如我们前面了解到的,发送数据也是一个生产与消费的故事,UDT::send()和UDT::sendmsg()讲的是生产的故事,至此我们基本上将生产的故事都理清了,接着就来看下消费的故事,也就是CSndQueue中的实际数据发送。

发送队列CSndQueue中数据的实际发送

接着来讲数据发送这个生产-消费故事的另一半,也就是消费的那一半,发送队列CSndQueue中实际的数据发送。先来瞅一下CSndQueue的定义(src/queue.h):

1class CSndQueue { 2 friend class CUDT; 3 friend class CUDTUnited; 4 5 public: 6 CSndQueue(); 7 ~CSndQueue(); 8 9 public: 10 11 // Functionality: 12 // Initialize the sending queue. 13 // Parameters: 14 // 1) [in] c: UDP channel to be associated to the queue 15 // 2) [in] t: Timer 16 // Returned value: 17 // None. 18 void init(CChannel* c, CTimer* t); 19 20 // Functionality: 21 // Send out a packet to a given address. 22 // Parameters: 23 // 1) [in] addr: destination address 24 // 2) [in] packet: packet to be sent out 25 // Returned value: 26 // Size of data sent out. 27 int sendto(const sockaddr* addr, CPacket& packet); 28 29 private: 30#ifndef WIN32 31 static void* worker(void* param); 32#else 33 static DWORD WINAPI worker(LPVOID param); 34#endif 35 36 pthread_t m_WorkerThread; 37 38 private: 39 CSndUList* m_pSndUList; // List of UDT instances for data sending 40 CChannel* m_pChannel; // The UDP channel for data sending 41 CTimer* m_pTimer; // Timing facility 42 43 pthread_mutex_t m_WindowLock; 44 pthread_cond_t m_WindowCond; 45 46 volatile bool m_bClosing; // closing the worker 47 pthread_cond_t m_ExitCond; 48 49 private: 50 CSndQueue(const CSndQueue&); 51 CSndQueue& operator=(const CSndQueue&); 52};

这个class,不管是成员变量,还是成员函数,看上去基本都还比较亲切,其作用不会让人完全无感,但唯独一个成员变量,也就是CSndUList的m_pSndUList。因而这里就先来看一下这个类。先来看CSndUList的定义:

1struct CSNode { 2 CUDT* m_pUDT; // Pointer to the instance of CUDT socket 3 uint64_t m_llTimeStamp; // Time Stamp 4 5 int m_iHeapLoc; // location on the heap, -1 means not on the heap 6}; 7 8class CSndUList { 9 friend class CSndQueue; 10 11 public: 12 CSndUList(); 13 ~CSndUList(); 14 15 public: 16 17 // Functionality: 18 // Insert a new UDT instance into the list. 19 // Parameters: 20 // 1) [in] ts: time stamp: next processing time 21 // 2) [in] u: pointer to the UDT instance 22 // Returned value: 23 // None. 24 25 void insert(int64_t ts, const CUDT* u); 26 27 // Functionality: 28 // Update the timestamp of the UDT instance on the list. 29 // Parameters: 30 // 1) [in] u: pointer to the UDT instance 31 // 2) [in] resechedule: if the timestampe shoudl be rescheduled 32 // Returned value: 33 // None. 34 35 void update(const CUDT* u, bool reschedule = true); 36 37 // Functionality: 38 // Retrieve the next packet and peer address from the first entry, and reschedule it in the queue. 39 // Parameters: 40 // 0) [out] addr: destination address of the next packet 41 // 1) [out] pkt: the next packet to be sent 42 // Returned value: 43 // 1 if successfully retrieved, -1 if no packet found. 44 45 int pop(sockaddr*& addr, CPacket& pkt); 46 47 // Functionality: 48 // Remove UDT instance from the list. 49 // Parameters: 50 // 1) [in] u: pointer to the UDT instance 51 // Returned value: 52 // None. 53 54 void remove(const CUDT* u); 55 56 // Functionality: 57 // Retrieve the next scheduled processing time. 58 // Parameters: 59 // None. 60 // Returned value: 61 // Scheduled processing time of the first UDT socket in the list. 62 63 uint64_t getNextProcTime(); 64 65 private: 66 void insert_(int64_t ts, const CUDT* u); 67 void remove_(const CUDT* u); 68 69 private: 70 CSNode** m_pHeap; // The heap array 71 int m_iArrayLength; // physical length of the array 72 int m_iLastEntry; // position of last entry on the heap array 73 74 pthread_mutex_t m_ListLock; 75 76 pthread_mutex_t* m_pWindowLock; 77 pthread_cond_t* m_pWindowCond; 78 79 CTimer* m_pTimer; 80 81 private: 82 CSndUList(const CSndUList&); 83 CSndUList& operator=(const CSndUList&); 84};

从这个类的定义中,我们大概能感觉到这是一个CSNode的容器,但容器的许多组织的细节则仍然是一头雾水,那就从它的构造函数和成员函数中来厘清这些细节。来看它的构造函数(src/queue.cpp):

1CSndUList::CSndUList() 2 : m_pHeap(NULL), 3 m_iArrayLength(4096), 4 m_iLastEntry(-1), 5 m_ListLock(), 6 m_pWindowLock(NULL), 7 m_pWindowCond(NULL), 8 m_pTimer(NULL) { 9 m_pHeap = new CSNode*[m_iArrayLength]; 10 11#ifndef WIN32 12 pthread_mutex_init(&m_ListLock, NULL); 13#else 14 m_ListLock = CreateMutex(NULL, false, NULL); 15#endif 16}

在这个函数中做的事情就是分配了一个CSNode指针的数组,并初始化了一个mutex m_ListLock,但这似乎也无法透漏出太多的讯息。然后来看向其中插入元素的insert():

1void CSndUList::insert(int64_t ts, const CUDT* u) { 2 CGuard listguard(m_ListLock); 3 4 // increase the heap array size if necessary 5 if (m_iLastEntry == m_iArrayLength - 1) { 6 CSNode** temp = NULL; 7 8 try { 9 temp = new CSNode*[m_iArrayLength * 2]; 10 } catch (...) { 11 return; 12 } 13 14 memcpy(temp, m_pHeap, sizeof(CSNode*) * m_iArrayLength); 15 m_iArrayLength *= 2; 16 delete[] m_pHeap; 17 m_pHeap = temp; 18 } 19 20 insert_(ts, u); 21}

m_iLastEntry是数组中已经被占用的最后一个位置。在这个函数中,做了两件事:

1. 检查m_iLastEntry是否等于m_iArrayLength - 1,若是,则表明数组中所有的位置都被占用了此时则需要扩充容量,这里的做法就是创建一个长度为之前数组长度2倍的新数组,将之前数组中的内容拷贝到新数组里,更新m_iArrayLength,删除之前的数组,更新m_pHeap只想新数组。

2. 执行CSndUList::insert_()进行实际的插入动作。

再来看CSndUList::insert_():

1void CSndUList::insert_(int64_t ts, const CUDT* u) { 2 CSNode* n = u->m_pSNode; 3 4 // do not insert repeated node 5 if (n->m_iHeapLoc >= 0) 6 return; 7 8 m_iLastEntry++; 9 m_pHeap[m_iLastEntry] = n; 10 n->m_llTimeStamp = ts; 11 12 int q = m_iLastEntry; 13 int p = q; 14 while (p != 0) { 15 p = (q - 1) >> 1; 16 if (m_pHeap[p]->m_llTimeStamp > m_pHeap[q]->m_llTimeStamp) { 17 CSNode* t = m_pHeap[p]; 18 m_pHeap[p] = m_pHeap[q]; 19 m_pHeap[q] = t; 20 t->m_iHeapLoc = q; 21 q = p; 22 } else 23 break; 24 } 25 26 n->m_iHeapLoc = q; 27 28 // an earlier event has been inserted, wake up sending worker 29 if (n->m_iHeapLoc == 0) 30 m_pTimer->interrupt(); 31 32 // first entry, activate the sending queue 33 if (0 == m_iLastEntry) { 34#ifndef WIN32 35 pthread_mutex_lock(m_pWindowLock); 36 pthread_cond_signal(m_pWindowCond); 37 pthread_mutex_unlock(m_pWindowLock); 38#else 39 SetEvent(*m_pWindowCond); 40#endif 41 } 42}

在这个函数中主要做了这样一些事:

1. 检查要插入的元素是否已经插入了,主要是根据CUDT的CSNode n的HeapLoc字段是否大于0来判断的。若已经插入,则直接返回。

2. 将CSNode放在数组的尾部。

3. 调整CSNode n在数组中的位置,以使它处于适当的位置。要厘清这个地方的调整过程,可能要复习一下我们曾经学习过的堆数据结构了。可以将堆理解为一个用数组表示的二叉树,如下图所示:

如上图,每个框框中的数字表示该节点在数组中的位置。可以看到一个节点的位置与它的两个子节点及父节点的位置之间的关系:

假设一个节点的位置,也就是该节点在数组中的index为n,则它的父节点的位置为((n -1)/2),而它的两个子几点的位置分别为(2×N+1)和(2×n+2)。

回到CSndUList::insert_()的节点CSNode n的位置调整过程。可以看到,这个过程主要是根据CSNode n的m_llTimeStamp值,若CSNode n的m_llTimeStamp值比它的父节点的m_llTimeStamp小的话就把CSNode n往二叉树的上层浮,而把它的父节点向二叉树的下层沉,依次类推,直到找到某个位置,其父节点的m_llTimeStamp值比它的m_llTimeStamp值小,或者浮到二叉树的最顶层。

由此可见m_pHeap是一个根据CSNode的m_llTimeStamp值建的堆,越往上层,该值越小。而m_pHeap[0]则是整个堆中所有CSNode元素m_llTimeStamp值最小的那个。

4. 更新CSNode n的m_iHeapLoc指向它在数组m_pHeap中的索引。

5. CSNode n被浮到堆的顶部时,唤醒发送队列的worker线程。

6. 插入的如果是堆中的第一个元素的话,唤醒等待在m_pWindowCond上的线程。

看完了插入元素,再来看移除元素也就是CSndUList::remove():

1void CSndUList::remove(const CUDT* u) { 2 CGuard listguard(m_ListLock); 3 4 remove_(u); 5} 6 7 8void CSndUList::remove_(const CUDT* u) { 9 CSNode* n = u->m_pSNode; 10 11 if (n->m_iHeapLoc >= 0) { 12 // remove the node from heap 13 m_pHeap[n->m_iHeapLoc] = m_pHeap[m_iLastEntry]; 14 m_iLastEntry--; 15 m_pHeap[n->m_iHeapLoc]->m_iHeapLoc = n->m_iHeapLoc; 16 17 int q = n->m_iHeapLoc; 18 int p = q * 2 + 1; 19 while (p <= m_iLastEntry) { 20 if ((p + 1 <= m_iLastEntry) && (m_pHeap[p]->m_llTimeStamp > m_pHeap[p + 1]->m_llTimeStamp)) 21 p++; 22 23 if (m_pHeap[q]->m_llTimeStamp > m_pHeap[p]->m_llTimeStamp) { 24 CSNode* t = m_pHeap[p]; 25 m_pHeap[p] = m_pHeap[q]; 26 m_pHeap[p]->m_iHeapLoc = p; 27 m_pHeap[q] = t; 28 m_pHeap[q]->m_iHeapLoc = q; 29 30 q = p; 31 p = q * 2 + 1; 32 } else 33 break; 34 } 35 36 n->m_iHeapLoc = -1; 37 } 38 39 // the only event has been deleted, wake up immediately 40 if (0 == m_iLastEntry) 41 m_pTimer->interrupt(); 42}

CSndUList::remove()是直接调用了CSndUList::remove_(),而在CSndUList::remove_()主要做了如下这样一些事情:

1. 先检查要移除的CSNode n是否存在与堆中,主要根据CSNode n的HeapLoc字段是否大于0来判断的。若没有插入,则跳到第5步,否则继续执行。

2. 将m_pHeap中的最末尾的元素放进原本由要移除的CSNode n所占用的位置,更新m_iLastEntry,及被改变了位置的原来的最末尾元素CSNode的m_iHeapLoc指向它当前被放置的位置。

3. 如果被调整了位置的CSNode的新位置不是最末尾的位置,则调整该节点的位置。这里主要是在这个节点的m_llTimeStamp值比它的子节点的m_llTimeStamp值更大时,将这个节点向二叉树层次结构的下层沉,而将它的字节点向上浮的过程。一个节点总是有两个字节点,也就是两棵子树,那它又会向哪一棵那边沉呢?可以看到是字节点中m_llTimeStamp值更小的那一边。

总觉得这里应该再有一个节点上浮的过程。如果移除的节点是最末尾节点的直系父节点,这当然没有问题,但如果不是,则关系还是有许多不确定的地方。

4. 更新CSNode n的m_iHeapLoc指向-1。

5. 如果m_iLastEntry为0,即表示堆中不再有元素了,则还会执行唤醒。

回头看我们前面分析的CUDT::send()和CUDT::sendmsg(),它们都通过m_pSndQueue->m_pSndUList->update(this, false)将CUDT插入CSndUList m_pSndUList,这里再来看一下CSndUList::update():

1void CSndUList::update(const CUDT* u, bool reschedule) { 2 CGuard listguard(m_ListLock); 3 4 CSNode* n = u->m_pSNode; 5 6 if (n->m_iHeapLoc >= 0) { 7 if (!reschedule) 8 return; 9 10 if (n->m_iHeapLoc == 0) { 11 n->m_llTimeStamp = 1; 12 m_pTimer->interrupt(); 13 return; 14 } 15 16 remove_(u); 17 } 18 19 insert_(1, u); 20}

reschedule参数表示的是,如果之前的已经有发送任务,且还没有执行完,则将新的发送任务放在老的之后。

可以看到在这个函数中,如果CSNode还没有被插入堆中,则尽可能将CSNode放如堆的顶部以便于发送任务尽快执行。若已经插入,且reschedule为false,则直接返回。若已经插入,且reschedule为true,则检查一下CSNode当前是否已经在堆的顶部了,若是就退出。若不是,则先将CSNode从堆中移除,然后再尽可能将CSNode插入堆的顶部。

对发送队列CSndQueue所用的数据结构做这么多分析之后,我们再来看它的worker线程,也就是CSndQueue::worker():

1CSndQueue::CSndQueue() 2 : m_WorkerThread(), 3 m_pSndUList(NULL), 4 m_pChannel(NULL), 5 m_pTimer(NULL), 6 m_WindowLock(), 7 m_WindowCond(), 8 m_bClosing(false), 9 m_ExitCond() { 10#ifndef WIN32 11 pthread_cond_init(&m_WindowCond, NULL); 12 pthread_mutex_init(&m_WindowLock, NULL); 13#else 14 m_WindowLock = CreateMutex(NULL, false, NULL); 15 m_WindowCond = CreateEvent(NULL, false, false, NULL); 16 m_ExitCond = CreateEvent(NULL, false, false, NULL); 17#endif 18} 19 20CSndQueue::~CSndQueue() { 21 m_bClosing = true; 22 23#ifndef WIN32 24 pthread_mutex_lock(&m_WindowLock); 25 pthread_cond_signal(&m_WindowCond); 26 pthread_mutex_unlock(&m_WindowLock); 27 if (0 != m_WorkerThread) 28 pthread_join(m_WorkerThread, NULL); 29 pthread_cond_destroy(&m_WindowCond); 30 pthread_mutex_destroy(&m_WindowLock); 31#else 32 SetEvent(m_WindowCond); 33 if (NULL != m_WorkerThread) 34 WaitForSingleObject(m_ExitCond, INFINITE); 35 CloseHandle(m_WorkerThread); 36 CloseHandle(m_WindowLock); 37 CloseHandle(m_WindowCond); 38 CloseHandle(m_ExitCond); 39#endif 40 41 delete m_pSndUList; 42} 43 44void CSndQueue::init(CChannel* c, CTimer* t) { 45 m_pChannel = c; 46 m_pTimer = t; 47 m_pSndUList = new CSndUList; 48 m_pSndUList->m_pWindowLock = &m_WindowLock; 49 m_pSndUList->m_pWindowCond = &m_WindowCond; 50 m_pSndUList->m_pTimer = m_pTimer; 51 52#ifndef WIN32 53 if (0 != pthread_create(&m_WorkerThread, NULL, CSndQueue::worker, this)) { 54 m_WorkerThread = 0; 55 throw CUDTException(3, 1); 56 } 57#else 58 DWORD threadID; 59 m_WorkerThread = CreateThread(NULL, 0, CSndQueue::worker, this, 0, &threadID); 60 if (NULL == m_WorkerThread) 61 throw CUDTException(3, 1); 62#endif 63} 64 65#ifndef WIN32 66void* CSndQueue::worker(void* param) 67#else 68 DWORD WINAPI CSndQueue::worker(LPVOID param) 69#endif 70 { 71 CSndQueue* self = (CSndQueue*) param; 72 73 while (!self->m_bClosing) { 74 uint64_t ts = self->m_pSndUList->getNextProcTime(); 75 76 if (ts > 0) { 77 // wait until next processing time of the first socket on the list 78 uint64_t currtime; 79 CTimer::rdtsc(currtime); 80 if (currtime < ts) 81 self->m_pTimer->sleepto(ts); 82 83 // it is time to send the next pkt 84 sockaddr* addr; 85 CPacket pkt; 86 if (self->m_pSndUList->pop(addr, pkt) < 0) 87 continue; 88 89 self->m_pChannel->sendto(addr, pkt); 90 } else { 91 // wait here if there is no sockets with data to be sent 92#ifndef WIN32 93 pthread_mutex_lock(&self->m_WindowLock); 94 if (!self->m_bClosing && (self->m_pSndUList->m_iLastEntry < 0)) 95 pthread_cond_wait(&self->m_WindowCond, &self->m_WindowLock); 96 pthread_mutex_unlock(&self->m_WindowLock); 97#else 98 WaitForSingleObject(self->m_WindowCond, INFINITE); 99#endif 100 } 101 } 102 103#ifndef WIN32 104 return NULL; 105#else 106 SetEvent(self->m_ExitCond); 107 return 0; 108#endif 109}

CSndQueue::worker()中的while循环几乎就是CSndQueue的worker线程执行的全部任务了,这个循环的循环体中主要做了如下这样的一些事情:

1. 调用self->m_pSndUList->getNextProcTime(),来查看最近的一次发送任务所需要执行的时间ts。这里来看一下CSndUList::getNextProcTime()的定义:

1uint64_t CSndUList::getNextProcTime() { 2 CGuard listguard(m_ListLock); 3 4 if (-1 == m_iLastEntry) 5 return 0; 6 7 return m_pHeap[0]->m_llTimeStamp; 8}

若返回值小于等于0,就表示当前没有需要发送的数据,没有需要执行的发送任务。则进入等待状态。在CSndQueue::init()的定义中,CSndUList m_pSndUList的m_pWindowLock和m_pWindowCond会分别指向CSndQueue的m_WindowLock和m_WindowCond,因而可见,这个地方的等待,是被CSndUList::insert_()唤醒的。

若返回值大于0,则表明存在着需要执行的发送任务。此时则执行下一步。

2. 获取当前的时间currtime。比较currtime与ts,若前者较小,则表明最近需要执行的发送任务它请求的执行时间还没到,则休眠等待直到ts的到来。如我们前面的分析,并根据CSndQueue::init()的定义可见,向m_pSndUList中插入、移除或更新元素,都可能会唤醒这里的等待。若前者较大,或者等待的时刻到了则执行下一步。

3. 执行self->m_pSndUList->pop(addr, pkt),从CSndUList m_pSndUList中抓一个CPacket出来。若没抓到,则进入下一次循环,否则发送抓到的CPacket。来看CSndUList::pop():

1int CSndUList::pop(sockaddr*& addr, CPacket& pkt) { 2 CGuard listguard(m_ListLock); 3 4 if (-1 == m_iLastEntry) 5 return -1; 6 7 // no pop until the next schedulled time 8 uint64_t ts; 9 CTimer::rdtsc(ts); 10 if (ts < m_pHeap[0]->m_llTimeStamp) 11 return -1; 12 13 CUDT* u = m_pHeap[0]->m_pUDT; 14 remove_(u); 15 16 if (!u->m_bConnected || u->m_bBroken) 17 return -1; 18 19 // pack a packet from the socket 20 if (u->packData(pkt, ts) <= 0) 21 return -1; 22 23 addr = u->m_pPeerAddr; 24 25 // insert a new entry, ts is the next processing time 26 if (ts > 0) 27 insert_(ts, u); 28 29 return 1; 30}

可以看到CSndUList::pop()做了这样一些事情:

1. 检查m_iLastEntry是否为-1,若为-1,表明没有要执行发送的任务,因而直接返回-1。否则继续执行。

2. 检查当前时间是否小于堆顶元素的m_llTimeStamp,若小于则表明,最近一次发送任务的发送时间还没到,则返回-1,否则继续执行。

3. 获取堆顶元素的CUDT对象u,也就是发送任务的请求者,并将堆顶元素先从对中移除。

4. 检查u的状态,若不处于有效的连接状态,则返回-1,否则继续执行。

5. 执行u->packData(pkt, ts)打出一个数据包来。

6. 使传进来的addr只想CUDT u的PeerAddr,CSndQueue会将这个地址作为包的发送目的地址。

7. 将CUDT u重新插入堆中,时间戳为当前时间,这也就意味着,如果可以的话,就在下一个循环中继续发送CUDT u的数据。

8. 返回1。

在发送队列CSndQueue的worker线程中,最最需要的是尽可能快的获得最近需要执行的发送任务的一些信息。CSndUList::getNextProcTime()和CSndUList::pop()中获取的最主要的信息也是堆顶元素的一些信息。一个严格依照请求的执行时间进行排列的列表意义并不是很大,为了保证这种有序性反倒可能需要消耗不少的时间,采用堆却可以想CSndQueue的worker线程尽可能快的返回最近将要执行的发送任务请求执行的时间。

Done。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

mysql设置时区

mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0

UDT协议实现分析——数据的发送 - HelloWorld