Adapting actors code to be compatible with python 2.7 y python 3.x

This commit is contained in:
Adolfo Gómez García 2014-11-10 22:01:00 +01:00
parent 449b3df02a
commit c56ef185b6
4 changed files with 73 additions and 68 deletions

View File

@ -8,35 +8,35 @@ def testRest():
from udsactor import REST
cfg = store.readConfig()
print cfg
print "Intefaces: ", list(operations.getNetworkInfo())
print "Joined Domain: ", operations.getDomainName()
print(cfg)
print("Intefaces: ", list(operations.getNetworkInfo()))
print("Joined Domain: ", operations.getDomainName())
# renameComputer('win7-64')
# joinDomain('dom.dkmon.com', 'ou=pruebas_2,dc=dom,dc=dkmon,dc=com', 'administrador@dom.dkmon.com', 'Temporal2012', True)
# reboot()
r = REST.Api(cfg['host'], cfg['masterKey'], cfg['ssl'], scrambledResponses=True)
print "Connected: {}".format(r.isConnected)
print("Connected: {}".format(r.isConnected))
r.test()
try:
r.init('02:46:00:00:00:07')
except REST.UnmanagedHostError:
print 'Unmanaged host (confirmed)'
print('Unmanaged host (confirmed)')
uuid = r.init('02:46:00:00:00:08')
print "Notify comm:", r.notifyComm('http://172.27.0.1:8000/')
print("Notify comm:", r.notifyComm('http://172.27.0.1:8000/'))
print "Connected: {}".format(r.isConnected)
print("Connected: {}".format(r.isConnected))
print 'uuid = {}'.format(uuid)
print('uuid = {}'.format(uuid))
# print 'Login: {}'.format(r.login('test-user'))
# print 'Logout: {}'.format(r.logout('test-user'))
print "Information: >>{}<<".format(r.information())
print "Login: >>{}<<".format(r.login('Pepito'))
print("Information: >>{}<<".format(r.information()))
print("Login: >>{}<<".format(r.login('Pepito')))
print r.setReady([(v.mac, v.ip) for v in operations.getNetworkInfo()])
print r.log(10000, 'Test error message')
print(r.setReady([(v.mac, v.ip) for v in operations.getNetworkInfo()]))
print(r.log(10000, 'Test error message'))
def ipcTest():
@ -47,22 +47,24 @@ def ipcTest():
s.start()
sleep(1)
client = ipc.ClientIPC(39188)
client.start()
client2 = ipc.ClientIPC(39188)
client2.start()
sleep(1)
print('Sending message')
s.sendMessage(ipc.MSG_LOGOFF, None)
s.sendMessage(ipc.MSG_MESSAGE, 'Cierra la sesión')
s.sendMessage(33, 'invalid')
s.sendMessage(ipc.MSG_SCRIPT, 'print "hello"')
print('Message sent')
for c in (client, client2):
print c.getMessage()
print c.getMessage()
print c.getMessage()
print(c.getMessage())
print(c.getMessage())
print(c.getMessage())
client.stop()
client.join()
@ -72,9 +74,9 @@ def ipcTest():
s.sendMessage(33, 'invalid')
s.sendMessage(ipc.MSG_SCRIPT, 'print "hello"')
print client2.getMessage()
print client2.getMessage()
print client2.getMessage()
print(client2.getMessage())
print(client2.getMessage())
print(client2.getMessage())
client2.stop()
s.stop()
@ -94,7 +96,7 @@ def ipcServer():
while True:
try:
counter += 1
print "Sending new message {}".format(counter)
print("Sending new message {}".format(counter))
s.sendMessage(ipc.MSG_MESSAGE, 'This is a test message ñöitó 33.3€ {}'.format(counter))
counter += 1
s.sendMessage(ipc.MSG_SCRIPT, 'print "This is a test message ñöitó 33.3€ {}"'.format(counter))
@ -111,8 +113,8 @@ def testIdle():
from udsactor import operations
from time import sleep
for i in xrange(1, 10):
print operations.getIdleDuration()
for i in range(1, 10):
print(operations.getIdleDuration())
sleep(1)
@ -148,27 +150,27 @@ def testServer():
serverUrl = server.getServerUrl()
server.start()
print serverUrl
print(serverUrl)
res = requests.post(serverUrl + '/message', data=json.dumps({'message': 'Test message'}), headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
res = requests.post(serverUrl + '/script', data=json.dumps({'script': 'import time\ntime.sleep(1)\nfor v in xrange(10): print "Hello world, this is an script"'}), headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
res = requests.post(serverUrl + '/script', data=json.dumps({'script': 'print "Hello world, this is an script"', 'user': True}), headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
res = requests.get(serverUrl + '/information?param1=1&param2=2', headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
print "Messages:"
print client.getMessage()
print client.getMessage()
print("Messages:")
print(client.getMessage())
print(client.getMessage())
# try:
# while True:
@ -186,23 +188,23 @@ def testRemote():
import json
serverUrl = "https://172.27.0.208:52562/633a1245873848b7b4017c23283bc195"
print serverUrl
print(serverUrl)
res = requests.post(serverUrl + '/message', data=json.dumps({'message': 'Test message'}), headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
res = requests.post(serverUrl + '/script', data=json.dumps({'script': 'import time\ntime.sleep(1)\nfor v in xrange(10): print "Hello world, this is an script"'}), headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
res = requests.post(serverUrl + '/script', data=json.dumps({'script': 'print "Hello world, this is an script"', 'user': True}), headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
res = requests.get(serverUrl + '/information?param1=1&param2=2', headers={'content-type': 'application/json'}, verify=False)
print res
print res.json()
print(res)
print(res.json())
if __name__ == '__main__':

View File

@ -33,9 +33,9 @@ from __future__ import unicode_literals
import socket
import threading
import Queue
import time
import cPickle
import six
import traceback
import pickle
from udsactor.utils import toUnicode
from udsactor.log import logger
@ -73,7 +73,7 @@ class ClientProcessor(threading.Thread):
self.parent = parent
self.clientSocket = clientSocket
self.running = False
self.messages = Queue.Queue(32)
self.messages = six.moves.queue.Queue(32) # @UndefinedVariable
def stop(self):
logger.debug('Stoping client processor')
@ -86,13 +86,13 @@ class ClientProcessor(threading.Thread):
while self.running:
try:
while True:
buf = self.clientSocket.recv(512) # Empty buffer, this is set as non-blocking
if buf == b'': # No data
buf = bytearray(self.clientSocket.recv(512)) # Empty buffer, this is set as non-blocking
if len(buf) == 0: # No data
break
for b in buf:
if ord(b) == REQ_INFORMATION:
if b == REQ_INFORMATION:
infoParams = self.parent.infoParams if self.parent.infoParams is not None else {}
self.messages.put((MSG_INFORMATION, cPickle.dumps(infoParams)))
self.messages.put((MSG_INFORMATION, pickle.dumps(infoParams)))
logger.debug('Received a request for information')
else:
logger.debug('Got unexpected data {}'.format(ord(b)))
@ -103,7 +103,7 @@ class ClientProcessor(threading.Thread):
try:
msg = self.messages.get(block=True, timeout=1)
except Queue.Empty: # No message got in time
except six.moves.queue.Empty: # No message got in time @UndefinedVariable
continue
logger.debug('Got message {}'.format(msg))
@ -111,12 +111,12 @@ class ClientProcessor(threading.Thread):
try:
m = msg[1] if msg[1] is not None else b''
l = len(m)
data = MAGIC + chr(msg[0]) + chr(l & 0xFF) + chr(l >> 8) + m
data = MAGIC + six.int2byte(msg[0]) + six.int2byte(l & 0xFF) + six.int2byte(l >> 8) + m
try:
self.clientSocket.sendall(data)
except socket.error as e:
# Send data error
logger.debug('Socket connection is no more available: {}'.format(toUnicode(e)))
logger.debug('Socket connection is no more available: {}'.format(e.args))
self.running = False
except Exception as e:
logger.error('Invalid message in queue: {}'.format(e))
@ -156,7 +156,7 @@ class ServerIPC(threading.Thread):
logger.debug('Sending message {},{} to all clients'.format(msgId, msgData))
# Convert to bytes so length is correctly calculated
if isinstance(msgData, unicode):
if isinstance(msgData, six.text_type):
msgData = msgData.encode('utf8')
for t in self.threads:
@ -214,7 +214,7 @@ class ClientIPC(threading.Thread):
self.port = listenPort
self.running = False
self.clientSocket = None
self.messages = Queue.Queue(32)
self.messages = six.moves.queue.Queue(32) # @UndefinedVariable
self.connect()
@ -225,7 +225,7 @@ class ClientIPC(threading.Thread):
while self.running:
try:
return self.messages.get(timeout=1)
except Queue.Empty:
except six.moves.queue.Empty: # @UndefinedVariable
continue
return None
@ -285,14 +285,14 @@ class ClientIPC(threading.Thread):
continue
# Now we get message basic data (msg + datalen)
msg = self.receiveBytes(3)
msg = bytearray(self.receiveBytes(3))
# We have the magic header, here comes the message itself
if msg is None:
continue
msgId = ord(msg[0])
dataLen = ord(msg[1]) + (ord(msg[2]) << 8)
msgId = msg[0]
dataLen = msg[1] + (msg[2] << 8)
if msgId not in VALID_MESSAGES:
raise Exception('Invalid message id: {}'.format(msgId))
@ -308,7 +308,7 @@ class ClientIPC(threading.Thread):
self.running = False
return
except Exception as e:
logger.error('Error: {}'.format(toUnicode(e.message)))
logger.error('Error: {}'.format(e.args))
try:
self.clientSocket.close()

View File

@ -34,9 +34,10 @@ from __future__ import unicode_literals
import logging
import os
import tempfile
import six
# Valid logging levels, from UDS Broker (uds.core.utils.log)
OTHER, DEBUG, INFO, WARN, ERROR, FATAL = (10000 * (x + 1) for x in xrange(6))
OTHER, DEBUG, INFO, WARN, ERROR, FATAL = (10000 * (x + 1) for x in six.moves.xrange(6)) # @UndefinedVariable
class LocalLogger(object):
@ -56,7 +57,7 @@ class LocalLogger(object):
# our loglevels are 10000 (other), 20000 (debug), ....
# logging levels are 10 (debug), 20 (info)
# OTHER = logging.NOTSET
self.logger.log(level / 1000 - 10, message)
self.logger.log(int(level / 1000) - 10, message)
def isWindows(self):
return False

View File

@ -32,13 +32,15 @@
from __future__ import unicode_literals
import sys
import six
if sys.platform == 'win32':
from udsactor.windows.log import LocalLogger
from udsactor.windows.log import LocalLogger # @UnusedImport
else:
from udsactor.linux.log import LocalLogger
from udsactor.linux.log import LocalLogger # @Reimport
# Valid logging levels, from UDS Broker (uds.core.utils.log)
OTHER, DEBUG, INFO, WARN, ERROR, FATAL = (10000 * (x + 1) for x in xrange(6))
OTHER, DEBUG, INFO, WARN, ERROR, FATAL = (10000 * (x + 1) for x in six.moves.xrange(6)) # @UndefinedVariable
class Logger(object):
@ -58,7 +60,7 @@ class Logger(object):
if level < self.logLevel: # Skip not wanted messages
return
# If remote loger is available, notify message to it
# If remote logger is available, notify message to it
try:
if self.remoteLogger is not None and self.remoteLogger.isConnected:
self.remoteLogger.log(level, message)