openair.py 10.1 KB
Newer Older
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
#******************************************************************************

#  Eurecom OpenAirInterface
#  Copyright(c) 1999 - 2013 Eurecom

#  This program is free software; you can redistribute it and/or modify it
#  under the terms and conditions of the GNU General Public License,
#  version 2, as published by the Free Software Foundation.

#  This program is distributed in the hope it will be useful, but WITHOUT
#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
#  more details.

#  You should have received a copy of the GNU General Public License along with
#  this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.

#  The full GNU General Public License is included in this distribution in
#  the file called "COPYING".

#  Contact Information
#  Openair Admin: openair_admin@eurecom.fr
#  Openair Tech : openair_tech@eurecom.fr
#  Forums       : http://forums.eurecom.fsr/openairinterface
#  Address      : Eurecom, Compus SophiaTech 450, route des chappes, 06451 Biot, France

#*****************************************************************************

# \file openair.py
# \brief class that define the oaisim class and its attributes
# \author Navid Nikaein
# \date 2013
# \version 0.1
# @ingroup _test

import pexpect
import pxssh
import time
import os
import array
import shutil
import subprocess 
44 45
import sys
import traceback
46
import time
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
# import call

from core import *

SHELL = '/bin/bash'

class openair(core):
    def __init__(self, hostname, address):
        self.error = '% '
        self.hostname = hostname
        self.address = address
        self.localhost = None
        core.__init__(self)
              
    @property        
    def localhost(self):
        if self.localhost :
            return self.localhost 
        elif self.hostname in ['localhost', '127.0.0.7', '::1'] :
            self.localhost = self.hostname
        return self.localhost

    @localhost.setter
    def localhost(self,localhost):
        self.localhost = localhost

    def shcmd(self,cmd,sudo=False):
        
        if sudo:
            cmd = "sudo %s" % command
        
        proc = subprocess.Popen(command, shell=True, 
                             stdout = subprocess.PIPE, 
                             stderr = subprocess.PIPE)
                       
        stdout, stderr = proc.communicate()
        return (stdout, stderr)

    def connect(self, username, password, prompt='PEXPECT_OAI'):
86
     while True:  
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        self.prompt1 = prompt
        self.prompt2 = prompt
        self.password = '' 
        # WE do not store the password when sending commands for secuirity reasons. The password might be accidentally logged in such cases.
        #The password is used only to make ssh connections. In case user wants to run programs with sudo, then he/she needs to add following line in /etc/sudoers
        # your_user_name  ALL=(ALL:ALL) NOPASSWD: ALL
        try:
            if  not username:
                username = root 
            if  not password:
                password = username 
            self.oai = pxssh.pxssh()
            self.oai.login(self.address,username,password)
            self.oai.sendline('PS1='+self.prompt1)
            self.oai.PROMPT='PEXPECT_OAI'
            # need to look for twice the string of the prompt
            self.oai.prompt()
            self.oai.prompt()
            self.oai.sendline('uptime')
            self.oai.prompt()
            print self.oai.before
108
            break
109 110 111 112 113
        except Exception, e:
            error=''
            error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
            error = error + traceback.format_exc()
            print error
114 115 116
            print "Retrying again in 60 seconds"
            time.sleep(60)
            #sys.exit(1)
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
                
    def connect2(self, username, password, prompt='$'):
        self.prompt1 = prompt
        self.prompt2 = prompt
        self.password = password     
        while 1:
            try:
                if  not username:
                    username = root 
                if  not password:
                    password = username 
                    
                self.oai = pexpect.spawn('ssh -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" -o "ConnectionAttempts=1" ' \
                                             + username + '@' + self.address)
                
                index = self.oai.expect([re.escape(self.prompt1), re.escape(self.prompt2), pexpect.TIMEOUT], timeout=40)
                if index == 0 :
                    return 'Ok'
                else :
                    index = self.oai.expect(['password:', pexpect.TIMEOUT], timeout=40)
                    if index == 0 : 
                        self.oai.sendline(password)
                        index = self.oai.expect([re.escape(self.prompt1), re.escape(self.prompt2), pexpect.TIMEOUT], timeout=10)
                        if index != 0:
                            print 'ERROR! could not login with SSH.'
                            print 'Expected ' + self.prompt1 + ', received >>>>' + self.oai.before + '<<<<'
                            sys.exit(1) 
                    return 'Ok'
                        
146 147 148 149 150 151
            except Exception, e:
               error=''
               error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
               error = error + traceback.format_exc()
               print error
               sys.exit(1)
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

    def connect_localshell(self, prompt='$'):
        self.prompt1 = prompt
        self.prompt2 = prompt

        while 1:
            try:
                # start a shell and use the current environment
                self.oai = pexpect.spawn('bash --norc --noprofile')
                
                index = self.oai.expect([re.escape(self.prompt1), re.escape(self.prompt2), pexpect.TIMEOUT], timeout=40)
                if index == 0 :
                    return 'Ok'
                else :
                    sys.exit(1)

168 169 170 171 172 173
            except Exception, e:
               error=''
               error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
               error = error + traceback.format_exc()
               print error
               sys.exit(1)
174 175 176 177 178 179 180 181 182

    def disconnect(self):
        print 'disconnecting the ssh connection to ' + self.address + '\n'
        self.oai.send('exit')
#        self.cancel()

    def kill(self, user, pw):
        try:
            if user == 'root' :
183
                os.system('pkill oaisim oaisim_nos1')
184 185
                os.system('pkill cc1') 
                time.sleep(1)
186
                os.system('pkill oaisim oaisim_nos1')
187
            else :
188
                os.system('echo '+pw+' | sudo -S pkill oaisim oaisim_nos1')
189 190
                os.system('echo '+pw+' | sudo -S pkill cc1') 
                time.sleep(1)
191
                os.system('echo '+pw+' | sudo -S pkill oaisim oaisim_nos1')
192 193 194 195 196
        except Exception, e:
               error=''
               error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
               error = error + traceback.format_exc()
               print error
197
               #sys.exit(1)
198 199 200 201 202 203 204 205 206
            
    def rm_driver(self,oai,user, pw):
        try:
            if user == 'root' : 
                #oai.send_nowait('rmmod nasmesh;')
                os.system('rmmod nasmesh;')
            else :
                oai.send_nowait('echo '+pw+ ' | sudo -S rmmod nasmesh;')
                #os.system('echo '+pw+ ' | sudo -S rmmod nasmesh;')
207 208 209 210 211
        except Exception, e:
               error=''
               error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
               error = error + traceback.format_exc()
               print error
212
               #sys.exit(1)
213 214 215 216 217 218 219 220 221 222 223
   
    def driver(self,oai,user,pw):
        #pwd = oai.send_recv('pwd') 
        oai.send('cd $OPENAIR_TARGETS;')   
        oai.send('cd SIMU/USER;')   
        try:
            if user == 'root' : 
                oai.send_nowait('insmod ./nasmesh.ko;')
            else :
                oai.send('echo '+pw+ ' | sudo -S insmod ./nasmesh.ko;')
                
224 225 226 227 228
        except Exception, e:
               error=''
               error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
               error = error + traceback.format_exc()
               print error
229
               #sys.exit(1)
230 231 232 233 234 235 236 237 238 239
    
    def cleandir (self, logdir,debug) :
        
        for filename in os.listdir(logdir):
            filepath = os.path.join(logdir, filename)
            if debug == 2 :
                print 'logdir is ' + logdir
                print 'filepath is ' + filepath 
            try:
                shutil.rmtree(filepath)
240 241 242 243 244
            except Exception, e:
               error=''
               error = error + ' In function: ' + sys._getframe().f_code.co_name + ': *** Caught exception: '  + str(e.__class__) + " : " + str( e)
               error = error + traceback.format_exc()
               print error
245 246
               #sys.exit(1)
               #print 'Could not remove the filepath'+ filepath + ' with error ' + OSError
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    
    def create_dir(self,dirname,debug) :
        if not os.path.exists(dirname) :
            try:
                os.makedirs(dirname,0755)
            except OSError:
                # There was an error on creation, so make sure we know about it
                raise            
    def cpu_freq(self):
        freq=0
        proc = subprocess.Popen(["cat","/proc/cpuinfo"],
                                stdout=subprocess.PIPE)
        out, err = proc.communicate()
        
        for line in out.split("\n"):
            if "cpu MHz" in line:
                freq = float(line.split(":")[1])
                break 
            
        return freq