跳到主要內容

socket.send with Resource temporarily unavailable error

Problem

我的python程式如下,目標是建立一個socket server等待連線,並將檔案給送到socket client:

import socket
import os
import sys
import stat
from os.path import dirname, abspath, join
 
def transmitDebugInfo():
	filename = "/bootpart.gz"
 
	debugfile = None
	s = None
	conn = None
	try:
		debugfile = open(filename,'rb')
		blocksize = os.path.getsize(filename)
 
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		s.settimeout(60)
		s.bind(('0.0.0.0', 5555))
		s.listen(1)
		conn, addr = s.accept()
		data = debugfile.read()
		conn.send(data)
	except:
		print sys.exc_info()[0]
		print sys.exc_info()[1]
	finally:	
		if s is not None:
			s.close()
		if conn is not None:
			conn.close()
		if debugfile is not None:
			debugfile.close()
 
 
transmitDebugInfo()

我的client為了方便測試,是直接使用linux的nc command:

nc 192.168.0.1 5555 > test.txt

然而,在VMWare ESXI6.0 u2下會出現以下錯誤:

<class `socket.error`>
[Errno 11] Resource temporarilty unavaliable

Diagnosis

實驗1 - 分批送+sleep

首先我發現接收到的檔案大小一定是33304 bytes,於是我加了以下程式做試驗:

print "bufsize = %s" % s.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 5000)
print "bufsize = %s" % s.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)

server程式輸出為:

bufsize  = 32768
bufsize  = 5000

而client輸出檔案大小則變為5792 bytes。我猜想可能和發送buffer有關,於是找了一台ubuntu 14.04做測試;沒想到雖然buffer size為16384卻能正常的發送完檔案。因此我猜測可能和buffer釋放時間有關,於是改寫了以下發送方式:

while 1:
	data = debugfile.read(1024)
	if not data: break
	conn.send(data)
	time.sleep(0.000001)

以每次1024 bytes發送,每次中間等待0.001秒,如此就能順利完成發送。但問我無法確定是由於send data thread搶了所有執行資源,造成buffer無法清空的問題;還是由於清buffer就是比較慢。在無法確認實際原因情況下,這方法我不敢使用。

實驗2 - Remove settimeout

在remove settimeout後,就可以正常傳送與接收資料;沒設定timeout等效於setblocking(1)。

實驗3 - setdefaulttimeout

我在建立socket前,使用socket.setdefaulttimeout(60),發現可以正常傳送與接收資料。這挺奇怪的,我還不曉得這與settimeout有何不同。

實驗4 - 使用strace去跑分批送

與實驗1的區別在於,我移除sleep並透過strace去執行也可以正常執行完畢。

strace -o output.txt -s512 python test.py

我猜測透過strace可能也造成send資料之間的延遲,好讓buffer有足夠時間釋放。

How to resolve?

根據實驗結果,有以下結論:

  1. 實驗二說明在blocking mode下,sendall應能正常傳送資料。實驗三為例外,原因還不明。
  2. 實驗一與四說明,如果將send分批進行且有緩衝,應能正常傳送資料。
  3. 並非所有OS有相同結果,可能與python或內核有關。

綜合以上,如果要設定timeout,安全作法應該使用non-blocking IO的存取方式。針對Resource temporarilty unavaliable錯誤retry:

def sendData(sock, data):
	total_sent = 0
	while len(data):
		try:
			sent = sock.send(data)
			total_sent += sent
			data = data[sent:]
			print 'Sending data'
		except socket.error, e:
			if e.errno != errno.EAGAIN:
				raise e
			print 'Blocking with', len(data), 'remaining'
			select.select([], [sock], [])  
	return total_sent

呼叫程式改為:

data = debugfile.read()
total_data = len(data)
total_send = sendData(conn, data)
print "data size = %s, send size = %s" % (total_data, total_send)

Reference

留言

這個網誌中的熱門文章

Show NIC selection when setting the network command with the device option

 Problem  在answer file中設定網卡名稱後,安裝時會停在以下畫面: 所使用的command參數如下: network --onboot = yes --bootproto =dhcp --ipv6 =auto --device =eth1 Diagnostic Result 這樣的參數,以前試驗過是可以安裝完成的。因此在發生這個問題後,我檢查了它的debug console: 從console得知,eth1可能是沒有連接網路線或者是網路太慢而導致的問題。後來和Ivy再三確認,有問題的是有接網路線的網卡,且問題是發生在activate階段: Solution 我想既然有retry應該就有次數或者timeout限制,因此發現在Anaconda的說明文件中( link ),有提到dhcptimeout這個boot參數。看了一些人的使用範例,應該是可以直接串在isolinux.cfg中,如下: default linux ksdevice = link ip =dhcp ks =cdrom: / ks.cfg dhcptimeout = 90 然而我在RHEL/CentOS 6.7與6.8試驗後都無效。 因此我就拿了顯示的錯誤字串,問問Google大師,想找一下Anaconda source code來看一下。最後找到別人根據Anaconda code修改的版本: link ,關鍵在於setupIfaceStruct函式中的setupIfaceStruct與readNetConfig: setupIfaceStruct: 會在dhcp時設定dhcptimeout。 readNetConfig: 在writeEnabledNetInfo將timeout寫入dhclient config中;在wait_for_iface_activation內會根據timeout做retry。 再來從log與code可以得知,它讀取的檔案是answer file而不是boot command line。因此我接下來的測試,就是在answer file的network command上加入dhcptimeout: network --onboot = yes --bootproto =dhcp --ipv6 =auto --device =eth1 --dhcptimeo

解決RobotFramework從3.1.2升級到3.2.2之後,Choose File突然會整個Hand住的問題

考慮到自動測試環境的維護,我們很久以前就使用java去執行robot framework。前陣子開始處理從3.1.2升級到3.2.2的事情,主要先把明確的runtime語法錯誤與deprecate item處理好,這部分內容可以參考: link 。 直到最近才發現,透過SeleniumLibrary執行Choose File去上傳檔案的動作,會導致測試案例timeout。本篇文章主要分享心路歷程與解決方法,我也送了一條issue給robot framework: link 。 我的環境如下: RobotFramework: 3.2.2 Selenium: 3.141.0 SeleniumLibrary: 3.3.1 Remote Selenium Version: selenium-server-standalone-3.141.59 首先並非所有Choose File的動作都會hang住,有些測試案例是可以執行的,但是上傳一個作業系統ISO檔案一定會發生問題。後來我透過wireshark去比對新舊版本的上傳動作,因為我使用 Remote Selenium ,所以Selenium會先把檔案透過REST API發送到Remote Selenium Server上。從下圖我們可以發現,在3.2.2的最後一個TCP封包,比3.1.2大概少了500個bytes。 於是就開始了我trace code之路。包含SeleniumLibrary產生要送給Remote Selenium Server的request內容,還有HTTP Content-Length的計算,我都確認過沒有問題。 最後發現問題是出在socket API的使用上,就是下圖的這支code: 最後發現可能因為開始使用nio的方式送資料,但沒處理到尚未送完的資料內容,而導致發生問題。加一個loop去做計算就可以解決了。 最後我有把解法提供給robot framework官方,在他們出新的版本之前,我是將改完的_socket.py放在我們自己的Lib底下,好讓我們測試可以正常進行。(shutil.py應該也是為了解某個bug而產生的樣子..)

PostgreSQL - Unattended installation on windows

Introduction 要將別人軟體包裝到自己軟體中,不可或缺的東西就是Unattended installation。以Unattended installation來說,我們可以選擇透過Installer的silent mode安裝,也可以透過把目標軟體做成portable的版本。本篇文章分享這兩種方法,教導大家如何將PostgreSQL透過Unattended installation方式安裝到目標系統成為service。 Note. 本篇以PostgreSQL 10.7為例。 Install with installer Tips 安裝程式或反安裝程式的參數,除了可以直接上官網搜尋Installation User Guide以外,也可以直接使用help參數查詢: postgresql- 10.7 - 2 -windows-x64.exe --help Windows安裝程式主要有EnterpriseDB與BigSQL兩種。BigSQL版本安裝元件是透過網路下載且支援參數不如EnterpriseDB版本多,以我們需求來說,我們傾向於使用EnterpriseDB版本。接下來分享給大家安裝與反安裝方法。 Installation @ echo off set INSTALL_DIR =C:\postgres10 set INSTALLER =postgresql- 10.7 - 2 -windows-x64.exe   rem options for installation set SSMDB_SERVICE =postgresql- 10 set MODE =--unattendedmodeui none --mode unattended   set DB_PASSWD =--superpassword postgres set DB_PORT =--serverport 5432   set SERVICE_NAME =--servicename % SSMDB_SERVICE %   set PREFIX =--prefix "%INSTALL_DIR%" set DATA_DIR =--datadir "%INSTALL_DIR%\data"   set OPTIONS =