-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdevicemanagerSUT.py
More file actions
1249 lines (1082 loc) · 37.5 KB
/
devicemanagerSUT.py
File metadata and controls
1249 lines (1082 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Test Automation Framework.
#
# The Initial Developer of the Original Code is Joel Maher.
#
# Portions created by the Initial Developer are Copyright (C) 2009
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Joel Maher <joel.maher@gmail.com> (Original Developer)
# Clint Talbert <cmtalbert@gmail.com>
# Mark Cote <mcote@mozilla.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
import socket
import SocketServer
import time, datetime
import os
import re
import hashlib
import subprocess
from threading import Thread
import traceback
import sys
from devicemanager import DeviceManager, DMError, FileError, NetworkTools
class DeviceManagerSUT(DeviceManager):
host = ''
port = 0
debug = 3
retries = 0
tempRoot = os.getcwd()
base_prompt = '$>'
base_prompt_re = '\$\>'
prompt_sep = '\x00'
prompt_regex = '.*(' + base_prompt_re + prompt_sep + ')'
agentErrorRE = re.compile('^##AGENT-WARNING##.*')
# TODO: member variable to indicate error conditions.
# This should be set to a standard error from the errno module.
# So, for example, when an error occurs because of a missing file/directory,
# before returning, the function would do something like 'self.error = errno.ENOENT'.
# The error would be set where appropriate--so sendCMD() could set socket errors,
# pushFile() and other file-related commands could set filesystem errors, etc.
def __init__(self, host, port = 20701, retrylimit = 5):
self.host = host
self.port = port
self.retrylimit = retrylimit
self.retries = 0
self._sock = None
self.getDeviceRoot()
def cmdNeedsResponse(self, cmd):
""" Not all commands need a response from the agent:
* if the cmd matches the pushRE then it is the first half of push
and therefore we want to wait until the second half before looking
for a response
* rebt obviously doesn't get a response
* uninstall performs a reboot to ensure starting in a clean state and
so also doesn't look for a response
"""
noResponseCmds = [re.compile('^push .*$'),
re.compile('^rebt'),
re.compile('^uninst .*$'),
re.compile('^pull .*$')]
for c in noResponseCmds:
if (c.match(cmd)):
return False
# If the command is not in our list, then it gets a response
return True
def shouldCmdCloseSocket(self, cmd):
""" Some commands need to close the socket after they are sent:
* push
* rebt
* uninst
* quit
"""
socketClosingCmds = [re.compile('^push .*$'),
re.compile('^quit.*'),
re.compile('^rebt.*'),
re.compile('^uninst .*$')]
for c in socketClosingCmds:
if (c.match(cmd)):
return True
return False
# convenience function to enable checks for agent errors
def verifySendCMD(self, cmdline, newline = True):
return self.sendCMD(cmdline, newline, False)
#
# create a wrapper for sendCMD that loops up to self.retrylimit iterations.
# this allows us to move the retry logic outside of the _doCMD() to make it
# easier for debugging in the future.
# note that since cmdline is a list of commands, they will all be retried if
# one fails. this is necessary in particular for pushFile(), where we don't want
# to accidentally send extra data if a failure occurs during data transmission.
#
def sendCMD(self, cmdline, newline = True, ignoreAgentErrors = True):
done = False
while (not done):
retVal = self._doCMD(cmdline, newline)
if (retVal is None):
self.retries += 1
else:
self.retries = 0
if ignoreAgentErrors == False:
if (self.agentErrorRE.match(retVal)):
raise DMError("error on the agent executing '%s'" % cmdline)
return retVal
if (self.retries >= self.retrylimit):
done = True
raise DMError("unable to connect to %s after %s attempts" % (self.host, self.retrylimit))
def _doCMD(self, cmdline, newline = True):
promptre = re.compile(self.prompt_regex + '$')
data = ""
shouldCloseSocket = False
recvGuard = 1000
if (self._sock == None):
try:
if (self.debug >= 1):
print "reconnecting socket"
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
self._sock = None
if (self.debug >= 2):
print "unable to create socket"
return None
try:
self._sock.connect((self.host, int(self.port)))
self._sock.recv(1024)
except:
self._sock.close()
self._sock = None
if (self.debug >= 2):
print "unable to connect socket"
return None
for cmd in cmdline:
if newline: cmd += '\r\n'
try:
numbytes = self._sock.send(cmd)
if (numbytes != len(cmd)):
print "ERROR: our cmd was " + str(len(cmd)) + " bytes and we only sent " + str(numbytes)
return None
if (self.debug >= 4): print "send cmd: " + str(cmd)
except:
self._sock.close()
self._sock = None
return None
# Check if the command should close the socket
shouldCloseSocket = self.shouldCmdCloseSocket(cmd)
# Handle responses from commands
if (self.cmdNeedsResponse(cmd)):
found = False
loopguard = 0
while (found == False and (loopguard < recvGuard)):
temp = ''
if (self.debug >= 4): print "recv'ing..."
# Get our response
try:
temp = self._sock.recv(1024)
if (self.debug >= 4): print "response: " + str(temp)
except:
self._sock.close()
self._sock = None
return None
# If something goes wrong in the agent it will send back a string that
# starts with '##AGENT-ERROR##'
if (self.agentErrorRE.match(temp)):
data = temp
break
lines = temp.split('\n')
for line in lines:
if (promptre.match(line)):
found = True
data += temp
# If we violently lose the connection to the device, this loop tends to spin,
# this guard prevents that
if (temp == ''):
loopguard += 1
if (shouldCloseSocket == True):
try:
self._sock.close()
self._sock = None
except:
self._sock = None
return None
return data
# internal function
# take a data blob and strip instances of the prompt '$>\x00'
def stripPrompt(self, data):
promptre = re.compile(self.prompt_regex + '.*')
retVal = []
lines = data.split('\n')
for line in lines:
try:
while (promptre.match(line)):
pieces = line.split(self.prompt_sep)
index = pieces.index('$>')
pieces.pop(index)
line = self.prompt_sep.join(pieces)
except(ValueError):
pass
retVal.append(line)
return '\n'.join(retVal)
# external function
# returns:
# success: True
# failure: False
def pushFile(self, localname, destname):
if (os.name == "nt"):
destname = destname.replace('\\', '/')
if (self.debug >= 3): print "in push file with: " + localname + ", and: " + destname
if (self.validateFile(destname, localname) == True):
if (self.debug >= 3): print "files are validated"
return True
if self.mkDirs(destname) == None:
print "unable to make dirs: " + destname
return False
if (self.debug >= 3): print "sending: push " + destname
filesize = os.path.getsize(localname)
f = open(localname, 'rb')
data = f.read()
f.close()
try:
retVal = self.verifySendCMD(['push ' + destname + ' ' + str(filesize) + '\r\n', data], newline = False)
except(DMError):
retVal = False
if (self.debug >= 3): print "push returned: " + str(retVal)
validated = False
if (retVal):
retline = self.stripPrompt(retVal).strip()
if (retline == None):
# Then we failed to get back a hash from agent, try manual validation
validated = self.validateFile(destname, localname)
else:
# Then we obtained a hash from push
localHash = self.getLocalHash(localname)
if (str(localHash) == str(retline)):
validated = True
else:
# We got nothing back from sendCMD, try manual validation
validated = self.validateFile(destname, localname)
if (validated):
if (self.debug >= 3): print "Push File Validated!"
return True
else:
if (self.debug >= 2): print "Push File Failed to Validate!"
return False
# external function
# returns:
# success: directory name
# failure: None
def mkDir(self, name):
if (self.dirExists(name)):
return name
else:
try:
retVal = self.verifySendCMD(['mkdr ' + name])
except(DMError):
retVal = None
return retVal
# make directory structure on the device
# external function
# returns:
# success: directory structure that we created
# failure: None
def mkDirs(self, filename):
parts = filename.split('/')
name = ""
for part in parts:
if (part == parts[-1]): break
if (part != ""):
name += '/' + part
if (self.mkDir(name) == None):
print "failed making directory: " + str(name)
return None
return name
# push localDir from host to remoteDir on the device
# external function
# returns:
# success: remoteDir
# failure: None
def pushDir(self, localDir, remoteDir):
if (self.debug >= 2): print "pushing directory: %s to %s" % (localDir, remoteDir)
for root, dirs, files in os.walk(localDir):
parts = root.split(localDir)
for file in files:
remoteRoot = remoteDir + '/' + parts[1]
remoteName = remoteRoot + '/' + file
if (parts[1] == ""): remoteRoot = remoteDir
if (self.pushFile(os.path.join(root, file), remoteName) == False):
# retry once
self.removeFile(remoteName)
if (self.pushFile(os.path.join(root, file), remoteName) == False):
return None
return remoteDir
# external function
# returns:
# success: True
# failure: False
def dirExists(self, dirname):
match = ".*" + dirname + "$"
dirre = re.compile(match)
try:
data = self.verifySendCMD(['cd ' + dirname, 'cwd'])
except(DMError):
return False
retVal = self.stripPrompt(data)
data = retVal.split('\n')
found = False
for d in data:
if (dirre.match(d)):
found = True
return found
# Because we always have / style paths we make this a lot easier with some
# assumptions
# external function
# returns:
# success: True
# failure: False
def fileExists(self, filepath):
s = filepath.split('/')
containingpath = '/'.join(s[:-1])
listfiles = self.listFiles(containingpath)
for f in listfiles:
if (f == s[-1]):
return True
return False
# list files on the device, requires cd to directory first
# external function
# returns:
# success: array of filenames, ['file1', 'file2', ...]
# failure: []
def listFiles(self, rootdir):
rootdir = rootdir.rstrip('/')
if (self.dirExists(rootdir) == False):
return []
try:
data = self.verifySendCMD(['cd ' + rootdir, 'ls'])
except(DMError):
return []
retVal = self.stripPrompt(data)
files = filter(lambda x: x, retVal.split('\n'))
if len(files) == 1 and files[0] == '<empty>':
# special case on the agent: empty directories return just the string "<empty>"
return []
return files
# external function
# returns:
# success: output of telnet, i.e. "removing file: /mnt/sdcard/tests/test.txt"
# failure: None
def removeFile(self, filename):
if (self.debug>= 2): print "removing file: " + filename
try:
retVal = self.verifySendCMD(['rm ' + filename])
except(DMError):
return None
return retVal
# does a recursive delete of directory on the device: rm -Rf remoteDir
# external function
# returns:
# success: output of telnet, i.e. "removing file: /mnt/sdcard/tests/test.txt"
# failure: None
def removeDir(self, remoteDir):
try:
retVal = self.verifySendCMD(['rmdr ' + remoteDir])
except(DMError):
return None
return retVal
# external function
# returns:
# success: array of process tuples
# failure: []
def getProcessList(self):
try:
data = self.verifySendCMD(['ps'])
except DMError:
return []
retVal = self.stripPrompt(data)
lines = retVal.split('\n')
files = []
for line in lines:
if (line.strip() != ''):
pidproc = line.strip().split()
if (len(pidproc) == 2):
files += [[pidproc[0], pidproc[1]]]
elif (len(pidproc) == 3):
#android returns <userID> <procID> <procName>
files += [[pidproc[1], pidproc[2], pidproc[0]]]
return files
# external function
# returns:
# success: pid
# failure: None
def fireProcess(self, appname, failIfRunning=False, appnameToCheck=None):
if (not appname):
if (self.debug >= 1): print "WARNING: fireProcess called with no command to run"
return None
if (self.debug >= 2): print "FIRE PROC: '" + appname + "'"
if (self.processExist(appname) != None):
print "WARNING: process %s appears to be running already\n" % appname
if (failIfRunning):
return None
try:
data = self.verifySendCMD(['exec ' + appname])
except(DMError):
return None
# wait up to 30 seconds for process to start up
# Ensure we wait for the process we started of if specified,
# wait for the one in the appnameToCheck param
if appnameToCheck:
appname = appnameToCheck
timeslept = 0
while (timeslept <= 30):
process = self.processExist(appname)
if (process is not None):
break
time.sleep(3)
timeslept += 3
if (self.debug >= 4): print "got pid: %s for process: %s" % (process, appname)
return process
# external function
# returns:
# success: output filename
# failure: None
def launchProcess(self, cmd, outputFile = "process.txt", cwd = '', env = '',
failIfRunning=False, appnameToCheck=None):
if not cmd:
if (self.debug >= 1): print "WARNING: launchProcess called without command to run"
return None
cmdline = subprocess.list2cmdline(cmd)
if (outputFile == "process.txt" or outputFile == None):
outputFile = self.getDeviceRoot();
if outputFile is None:
return None
outputFile += "/process.txt"
cmdline += " > " + outputFile
# Prepend our env to the command
cmdline = '%s %s' % (self.formatEnvString(env), cmdline)
if self.fireProcess(cmdline, failIfRunning, appnameToCheck) is None:
return None
return outputFile
# iterates process list and returns pid if exists, otherwise None
# external function
# returns:
# success: pid
# failure: None
def processExist(self, appname):
pid = None
#filter out extra spaces
parts = filter(lambda x: x != '', appname.split(' '))
appname = ' '.join(parts)
#filter out the quoted env string if it exists
#ex: '"name=value;name2=value2;etc=..." process args' -> 'process args'
parts = appname.split('"')
if (len(parts) > 2):
appname = ' '.join(parts[2:]).strip()
pieces = appname.split(' ')
parts = pieces[0].split('/')
app = parts[-1]
procre = re.compile('.*' + app + '.*')
procList = self.getProcessList()
if (procList == []):
return None
for proc in procList:
if (procre.match(proc[1])):
pid = proc[0]
break
return pid
# external function
# returns:
# success: output from testagent
# failure: None
def killProcess(self, appname):
try:
data = self.verifySendCMD(['kill ' + appname])
except(DMError):
return None
return data
# external function
# returns:
# success: tmpdir, string
# failure: None
def getTempDir(self):
try:
data = self.verifySendCMD(['tmpd'])
except(DMError):
return None
return self.stripPrompt(data).strip('\n')
# external function
# returns:
# success: filecontents
# failure: None
def catFile(self, remoteFile):
try:
data = self.verifySendCMD(['cat ' + remoteFile])
except(DMError):
return None
return self.stripPrompt(data)
# external function
# returns:
# success: output of pullfile, string
# failure: None
def pullFile(self, remoteFile):
"""Returns contents of remoteFile using the "pull" command.
The "pull" command is different from other commands in that DeviceManager
has to read a certain number of bytes instead of just reading to the
next prompt. This is more robust than the "cat" command, which will be
confused if the prompt string exists within the file being catted.
However it means we can't use the response-handling logic in sendCMD().
"""
def err(error_msg):
err_str = 'error returned from pull: %s' % error_msg
print err_str
self._sock = None
raise FileError(err_str)
# FIXME: We could possibly move these socket-reading functions up to
# the class level if we wanted to refactor sendCMD(). For now they are
# only used to pull files.
def uread(to_recv, error_msg):
""" unbuffered read """
try:
data = self._sock.recv(to_recv)
if not data:
err(error_msg)
return None
return data
except:
err(error_msg)
return None
def read_until_char(c, buffer, error_msg):
""" read until 'c' is found; buffer rest """
while not '\n' in buffer:
data = uread(1024, error_msg)
if data == None:
err(error_msg)
return ('', '', '')
buffer += data
return buffer.partition(c)
def read_exact(total_to_recv, buffer, error_msg):
""" read exact number of 'total_to_recv' bytes """
while len(buffer) < total_to_recv:
to_recv = min(total_to_recv - len(buffer), 1024)
data = uread(to_recv, error_msg)
if data == None:
return None
buffer += data
return buffer
prompt = self.base_prompt + self.prompt_sep
buffer = ''
# expected return value:
# <filename>,<filesize>\n<filedata>
# or, if error,
# <filename>,-1\n<error message>
try:
data = self.verifySendCMD(['pull ' + remoteFile])
except(DMError):
return None
# read metadata; buffer the rest
metadata, sep, buffer = read_until_char('\n', buffer, 'could not find metadata')
if not metadata:
return None
if self.debug >= 3:
print 'metadata: %s' % metadata
filename, sep, filesizestr = metadata.partition(',')
if sep == '':
err('could not find file size in returned metadata')
return None
try:
filesize = int(filesizestr)
except ValueError:
err('invalid file size in returned metadata')
return None
if filesize == -1:
# read error message
error_str, sep, buffer = read_until_char('\n', buffer, 'could not find error message')
if not error_str:
return None
# prompt should follow
read_exact(len(prompt), buffer, 'could not find prompt')
print "DeviceManager: error pulling file '%s': %s" % (remoteFile, error_str)
return None
# read file data
total_to_recv = filesize + len(prompt)
buffer = read_exact(total_to_recv, buffer, 'could not get all file data')
if buffer == None:
return None
if buffer[-len(prompt):] != prompt:
err('no prompt found after file data--DeviceManager may be out of sync with agent')
return buffer
return buffer[:-len(prompt)]
# copy file from device (remoteFile) to host (localFile)
# external function
# returns:
# success: output of pullfile, string
# failure: None
def getFile(self, remoteFile, localFile = ''):
if localFile == '':
localFile = os.path.join(self.tempRoot, "temp.txt")
try:
retVal = self.pullFile(remoteFile)
except:
return None
if (retVal is None):
return None
fhandle = open(localFile, 'wb')
fhandle.write(retVal)
fhandle.close()
if not self.validateFile(remoteFile, localFile):
print 'failed to validate file when downloading %s!' % remoteFile
return None
return retVal
# copy directory structure from device (remoteDir) to host (localDir)
# external function
# checkDir exists so that we don't create local directories if the
# remote directory doesn't exist but also so that we don't call isDir
# twice when recursing.
# returns:
# success: list of files, string
# failure: None
def getDirectory(self, remoteDir, localDir, checkDir=True):
if (self.debug >= 2): print "getting files in '" + remoteDir + "'"
if checkDir:
try:
is_dir = self.isDir(remoteDir)
except FileError:
return None
if not is_dir:
return None
filelist = self.listFiles(remoteDir)
if (self.debug >= 3): print filelist
if not os.path.exists(localDir):
os.makedirs(localDir)
for f in filelist:
if f == '.' or f == '..':
continue
remotePath = remoteDir + '/' + f
localPath = os.path.join(localDir, f)
try:
is_dir = self.isDir(remotePath)
except FileError:
print 'isdir failed on file "%s"; continuing anyway...' % remotePath
continue
if is_dir:
if (self.getDirectory(remotePath, localPath, False) == None):
print 'failed to get directory "%s"' % remotePath
return None
else:
# It's sometimes acceptable to have getFile() return None, such as
# when the agent encounters broken symlinks.
# FIXME: This should be improved so we know when a file transfer really
# failed.
if self.getFile(remotePath, localPath) == None:
print 'failed to get file "%s"; continuing anyway...' % remotePath
return filelist
# external function
# returns:
# success: True
# failure: False
# Throws a FileError exception when null (invalid dir/filename)
def isDir(self, remotePath):
try:
data = self.verifySendCMD(['isdir ' + remotePath])
except(DMError):
# normally there should be no error here; a nonexistent file/directory will
# return the string "<filename>: No such file or directory".
# However, I've seen AGENT-WARNING returned before.
return False
retVal = self.stripPrompt(data).strip()
if not retVal:
raise FileError('isdir returned null')
return retVal == 'TRUE'
# true/false check if the two files have the same md5 sum
# external function
# returns:
# success: True
# failure: False
def validateFile(self, remoteFile, localFile):
remoteHash = self.getRemoteHash(remoteFile)
localHash = self.getLocalHash(localFile)
if (remoteHash == None):
return False
if (remoteHash == localHash):
return True
return False
# return the md5 sum of a remote file
# internal function
# returns:
# success: MD5 hash for given filename
# failure: None
def getRemoteHash(self, filename):
try:
data = self.verifySendCMD(['hash ' + filename])
except(DMError):
return None
retVal = self.stripPrompt(data)
if (retVal != None):
retVal = retVal.strip('\n')
if (self.debug >= 3): print "remote hash returned: '" + retVal + "'"
return retVal
# Gets the device root for the testing area on the device
# For all devices we will use / type slashes and depend on the device-agent
# to sort those out. The agent will return us the device location where we
# should store things, we will then create our /tests structure relative to
# that returned path.
# Structure on the device is as follows:
# /tests
# /<fennec>|<firefox> --> approot
# /profile
# /xpcshell
# /reftest
# /mochitest
#
# external function
# returns:
# success: path for device root
# failure: None
def getDeviceRoot(self):
try:
data = self.verifySendCMD(['testroot'])
except:
return None
deviceRoot = self.stripPrompt(data).strip('\n') + '/tests'
if (not self.dirExists(deviceRoot)):
if (self.mkDir(deviceRoot) == None):
return None
return deviceRoot
# external function
# returns:
# success: output of unzip command
# failure: None
def unpackFile(self, filename):
devroot = self.getDeviceRoot()
if (devroot == None):
return None
dir = ''
parts = filename.split('/')
if (len(parts) > 1):
if self.fileExists(filename):
dir = '/'.join(parts[:-1])
elif self.fileExists('/' + filename):
dir = '/' + filename
elif self.fileExists(devroot + '/' + filename):
dir = devroot + '/' + filename
else:
return None
try:
data = self.verifySendCMD(['cd ' + dir, 'unzp ' + filename])
except(DMError):
return None
return data
# external function
# returns:
# success: status from test agent
# failure: None
def reboot(self, ipAddr=None, port=30000):
cmd = 'rebt'
if (self.debug > 3): print "INFO: sending rebt command"
callbacksvrstatus = None
if (ipAddr is not None):
#create update.info file:
try:
destname = '/data/data/com.mozilla.SUTAgentAndroid/files/update.info'
data = "%s,%s\rrebooting\r" % (ipAddr, port)
self.verifySendCMD(['push ' + destname + ' ' + str(len(data)) + '\r\n', data], newline = False)
except(DMError):
return None
ip, port = self.getCallbackIpAndPort(ipAddr, port)
cmd += " %s %s" % (ip, port)
# Set up our callback server
callbacksvr = callbackServer(ip, port, self.debug)
try:
status = self.verifySendCMD([cmd])
except(DMError):
return None
if (ipAddr is not None):
status = callbacksvr.disconnect()
if (self.debug > 3): print "INFO: rebt- got status back: " + str(status)
return status
# Returns information about the device:
# Directive indicates the information you want to get, your choices are:
# os - name of the os
# id - unique id of the device
# uptime - uptime of the device
# uptimemillis - uptime of device in milliseconds
# systime - system time of the device
# screen - screen resolution
# memory - memory stats
# process - list of running processes (same as ps)
# disk - total, free, available bytes on disk
# power - power status (charge, battery temp)
# all - all of them - or call it with no parameters to get all the information
# returns:
# success: dict of info strings by directive name
# failure: {}
def getInfo(self, directive=None):
data = None
result = {}
collapseSpaces = re.compile(' +')
directives = ['os', 'id','uptime','uptimemillis', 'systime','screen','memory','process', 'disk','power']
if (directive in directives):
directives = [directive]
for d in directives:
data = self.verifySendCMD(['info ' + d])
if (data is None):
continue
data = self.stripPrompt(data)
data = collapseSpaces.sub(' ', data)
result[d] = data.split('\n')
# Get rid of any 0 length members of the arrays
for k, v in result.iteritems():
result[k] = filter(lambda x: x != '', result[k])
# Format the process output
if 'process' in result:
proclist = []
for l in result['process']:
if l:
proclist.append(l.split('\t'))
result['process'] = proclist
if (self.debug >= 3): print "results: " + str(result)
return result
"""
Installs the application onto the device
Application bundle - path to the application bundle on the device
Destination - destination directory of where application should be
installed to (optional)
Returns None for success, or output if known failure
"""
# external function
# returns:
# success: output from agent for inst command
# failure: None
def installApp(self, appBundlePath, destPath=None):
cmd = 'inst ' + appBundlePath
if destPath:
cmd += ' ' + destPath
try:
data = self.verifySendCMD([cmd])
except(DMError):
return None
f = re.compile('Failure')
for line in data.split():
if (f.match(line)):
return data
return None
"""
Uninstalls the named application from device and causes a reboot.
Takes an optional argument of installation path - the path to where the application
was installed.
Returns True, but it doesn't mean anything other than the command was sent,