Write a simple adapter in functest project to run TESTON
[functest.git] / testcases / Controllers / ONOS / Teston / CI / adapters / environment.py
1 """
2 Description:
3     This file is used to setup the running environment
4     Include Download code,setup environment variable
5             Set onos running config
6             Set user name/password
7             Onos-push-keys and so on
8     lanqinglong@huawei.com
9 """
10
11 import os
12 import time
13 import pexpect
14 import re
15 import sys
16 import pxssh
17 from connection import connection
18
19 class environment( connection ):
20
21     def __init__( self ):
22         connection.__init__( self )
23         self.loginfo = connection( )
24         self.masterhandle = ''
25         self.home = ''
26
27     def DownLoadCode( self, handle, codeurl ):
28         """
29         Download Code use 'git clone'
30         parameters:
31         handle:  current working handle
32         codeurl: clone code url
33         """
34         print "Now loading test codes! Please wait in patient..."
35         originalfolder = self.home
36         gitclone = handle
37         gitclone.sendline( "git clone " + codeurl )
38         index = 0
39         while index != 1 or index != 4:
40             index = gitclone.expect ( ['already exists', 'resolving deltas: 100%', \
41                                     'Receiving objects', 'Already up-to-date', \
42                                     pexpect.EOF] )
43
44             filefolder = originalfolder + '/' + codeurl.split('/')[-1].split('.')[0]
45             if index == 0 :
46                 os.chdir( filefolder )
47                 os.system( 'git pull' )
48                 os.chdir( originalfolder )
49                 self.loginfo.log( 'Download code success!' )
50                 break
51             elif index == 1 :
52                 self.loginfo.log( 'Download code success!' )
53                 break
54             elif index == 2 :
55                 increment += 1
56                 if increment == 20:
57                     print '\n'
58                 print '.'
59             else :
60                 self.loginfo.log( 'Download code failed!' )
61                 self.loginfo.log( 'Information before' + gitclone.before )
62                 break
63             time.sleep(5)
64         gitclone.prompt( )
65
66     def InstallDefaultSoftware( self, handle ):
67         """
68         Install default software
69         parameters:
70         handle(input): current working handle
71         """
72         print "Now Cleaning test environment"
73         handle.sendline("sudo apt-get install -y mininet")
74         handle.prompt( )
75         handle.sendline("sudo pip install configobj")
76         handle.prompt( )
77         handle.sendline("sudo apt-get install -y sshpass")
78         handle.prompt( )
79         handle.sendline("OnosSystemTest/TestON/bin/cleanup.sh")
80         handle.prompt( )
81         time.sleep(5)
82         self.loginfo.log( 'Clean environment success!' )
83
84     def OnosPushKeys(self, handle, cmd, password):
85         """
86         Using onos-push-keys to make ssh device without password
87         parameters:
88         handle(input): working handle
89         cmd(input): onos-push-keys xxx(xxx is device)
90         password(input): login in password
91         """
92         print "Now Pushing Onos Keys:"+cmd
93         Pushkeys = handle
94         Pushkeys.sendline( cmd )
95         Result = 0
96         while Result != 2:
97             Result = Pushkeys.expect( ["(yes/no)", "assword:", "PEXPECT]#", \
98                                        pexpect.EOF, pexpect.TIMEOUT])
99             if ( Result == 0 ):
100                 Pushkeys.sendline( "yes" )
101             if ( Result == 1 ):
102                 Pushkeys.sendline( password )
103             if ( Result == 2 ):
104                 self.loginfo.log( "ONOS Push keys Success!" )
105                 break
106             if ( Result == 3 ):
107                 self.loginfo.log( "ONOS Push keys Error!" )
108                 break
109             time.sleep(2)
110         Pushkeys.prompt( )
111         print "Done!"
112
113     def SetOnosEnvVar( self, handle, masterpass, agentpass):
114         """
115         Setup onos pushkeys to all devices(3+2)
116         parameters:
117         handle(input): current working handle
118         masterpass: scripts running server's password
119         agentpass: onos cluster&compute node password
120         """
121         print "Now Setting test environment"
122         self.OnosPushKeys( handle, "onos-push-keys " + self.OCT, masterpass)
123         self.OnosPushKeys( handle, "onos-push-keys " + self.OC1, agentpass)
124         self.OnosPushKeys( handle, "onos-push-keys " + self.OC2, agentpass)
125         self.OnosPushKeys( handle, "onos-push-keys " + self.OC3, agentpass)
126         self.OnosPushKeys( handle, "onos-push-keys " + self.OCN, agentpass)
127         self.OnosPushKeys( handle, "onos-push-keys " + self.OCN2, agentpass)
128
129     def ChangeOnosName( self, user, password):
130         """
131         Change onos name in envDefault file
132         Because some command depend on this
133         parameters:
134         user: onos&compute node user
135         password: onos&compute node password
136         """
137         print "Now Changing ONOS name&password"
138         filepath = self.home + '/onos/tools/build/envDefaults'
139         line = open(filepath, 'r').readlines()
140         lenall = len(line) - 1
141         for i in range(lenall):
142            if "ONOS_USER=" in line[i]:
143                line[i]=line[i].replace("sdn",user)
144            if "ONOS_GROUP" in line[i]:
145                line[i]=line[i].replace("sdn",user)
146            if "ONOS_PWD" in line[i]:
147                line[i]=line[i].replace("rocks",password)
148         NewFile = open(filepath, 'w')
149         NewFile.writelines(line)
150         NewFile.close
151         print "Done!"
152
153     def ChangeTestCasePara(self, testcase, user, password):
154         """
155         When running test script, there's something need \
156         to change in every test folder's *.param & *.topo files
157         user: onos&compute node user
158         password: onos&compute node password
159         """
160         print "Now Changing " + testcase +  " name&password"
161         if self.masterusername is 'root':
162             filepath = '/root/'
163         else :
164             filepath = '/home/' + self.masterusername + '/'
165         filepath = filepath +"OnosSystemTest/TestON/tests/" + testcase + "/" + \
166                    testcase + ".topo"
167         line = open(filepath,'r').readlines()
168         lenall = len(line)-1
169         for i in range(lenall-2):
170            if ("localhost" in line[i]) or ("OCT" in line[i]):
171                line[i+1]=re.sub(">\w+",">"+user,line[i+1])
172                line[i+2]=re.sub(">\w+",">"+password,line[i+2])
173            if "OC1" in line [i] \
174               or "OC2" in line [i] \
175               or "OC3" in line [i] \
176               or "OCN" in line [i] \
177               or "OCN2" in line[i]:
178                line[i+1]=re.sub(">\w+",">root",line[i+1])
179                line[i+2]=re.sub(">\w+",">root",line[i+2])
180         NewFile = open(filepath,'w')
181         NewFile.writelines(line)
182         NewFile.close
183
184     def SSHlogin ( self, ipaddr, username, password ) :
185         """
186         SSH login provide a connection to destination.
187         parameters:
188         ipaddr:   ip address
189         username: login user name
190         password: login password
191         return: handle
192         """
193         login = pxssh.pxssh( )
194         login.login ( ipaddr, username, password, original_prompt='[$#>]')
195         #send command ls -l
196         login.sendline ('ls -l')
197         #match prompt
198         login.prompt()
199         print ("SSH login " + ipaddr + " success!")
200         return login
201
202     def SSHRelease( self, handle ):
203         #Release ssh
204         handle.logout()
205
206     def CopyOnostoTestbin( self ):
207         sourcefile = os.curdir + '/dependencies/onos'
208         destifile = self.home + '/onos/tools/test/bin/'
209         runcommand = 'cp ' + sourcefile + ' ' + destifile
210         os.system( runcommand )
211
212     def OnosEnvSetup( self, handle ):
213         """
214         Onos Environment Setup function
215         """
216         self.Gensshkey( handle )
217         self.home = self.GetEnvValue( handle, 'HOME' )
218         self.AddKnownHost( handle, self.OC1, "karaf", "karaf" )
219         self.AddKnownHost( handle, self.OC2, "karaf", "karaf" )
220         self.AddKnownHost( handle, self.OC3, "karaf", "karaf" )
221         self.DownLoadCode( handle, 'https://github.com/sunyulin/OnosSystemTest.git' )
222         self.DownLoadCode( handle, 'https://gerrit.onosproject.org/onos' )
223         self.CopyOnostoTestbin()
224         self.ChangeOnosName(self.agentusername,self.agentpassword)
225         self.InstallDefaultSoftware( handle )
226         self.SetOnosEnvVar(handle, self.masterpassword,self.agentpassword)