code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for device.py.""" __author__ = 'dgentry@google.com (Denton Gentry)' import os import shutil import tempfile import unittest import google3 import tornado.ioloop import tornado.testing import device class MockIoloop(object): def __init__(self): self.timeout = None self.callback = None def add_timeout(self, timeout, callback, monotonic=None): self.timeout = timeout self.callback = callback class DeviceTest(tornado.testing.AsyncTestCase): """Tests for device.py.""" def setUp(self): super(DeviceTest, self).setUp() self.old_ACSCONNECTED = device.ACSCONNECTED self.old_CONFIGDIR = device.CONFIGDIR self.old_GINSTALL = device.GINSTALL self.old_HNVRAM = device.HNVRAM self.old_LEDSTATUS = device.LEDSTATUS self.old_NAND_MB = device.NAND_MB self.old_PROC_CPUINFO = device.PROC_CPUINFO self.old_REBOOT = device.REBOOT self.old_REPOMANIFEST = device.REPOMANIFEST self.old_SET_ACS = device.SET_ACS self.old_VERSIONFILE = device.VERSIONFILE self.install_cb_called = False self.install_cb_faultcode = None self.install_cb_faultstring = None def tearDown(self): super(DeviceTest, self).tearDown() device.ACSCONNECTED = self.old_ACSCONNECTED device.CONFIGDIR = self.old_CONFIGDIR device.GINSTALL = self.old_GINSTALL device.HNVRAM = self.old_HNVRAM device.LEDSTATUS = self.old_LEDSTATUS device.NAND_MB = self.old_NAND_MB device.PROC_CPUINFO = self.old_PROC_CPUINFO device.REBOOT = self.old_REBOOT device.REPOMANIFEST = self.old_REPOMANIFEST device.SET_ACS = self.old_SET_ACS device.VERSIONFILE = self.old_VERSIONFILE def testGetSerialNumber(self): did = device.DeviceId() device.HNVRAM = 'testdata/device/hnvram' self.assertEqual(did.SerialNumber, '123456789') device.HNVRAM = 'testdata/device/hnvramSN_Empty' self.assertEqual(did.SerialNumber, '000000000000') device.HNVRAM = 'testdata/device/hnvramSN_Err' self.assertEqual(did.SerialNumber, '000000000000') def testBadHnvram(self): did = device.DeviceId() device.HNVRAM = '/no_such_binary_at_this_path' self.assertEqual(did.SerialNumber, '000000000000') def testModelName(self): did = device.DeviceId() device.HNVRAM = 'testdata/device/hnvram' self.assertEqual(did.ModelName, 'ModelName') def testSoftwareVersion(self): did = device.DeviceId() device.VERSIONFILE = 'testdata/device/version' self.assertEqual(did.SoftwareVersion, '1.2.3') def testAdditionalSoftwareVersion(self): did = device.DeviceId() device.REPOMANIFEST = 'testdata/device/repomanifest' self.assertEqual(did.AdditionalSoftwareVersion, 'platform 1111111111111111111111111111111111111111') def testGetHardwareVersion(self): device.HNVRAM = 'testdata/device/hnvram' device.PROC_CPUINFO = 'testdata/device/proc_cpuinfo_b0' device.NAND_MB = 'testdata/device/nand_size_mb_rev1' did = device.DeviceId() self.assertEqual(did.HardwareVersion, 'rev') device.HNVRAM = 'testdata/device/hnvramFOO_Empty' self.assertEqual(did.HardwareVersion, '0') device.PROC_CPUINFO = 'testdata/device/proc_cpuinfo_b2' self.assertEqual(did.HardwareVersion, '1') device.NAND_MB = 'testdata/device/nand_size_mb_rev2' self.assertEqual(did.HardwareVersion, '2') device.NAND_MB = 'testdata/device/nand_size_mb_unk' self.assertEqual(did.HardwareVersion, '?') def testFanSpeed(self): fan = device.FanReadGpio(speed_filename='testdata/fanspeed', percent_filename='testdata/fanpercent') fan.ValidateExports() self.assertEqual(fan.RPM, 1800) self.assertEqual(fan.DesiredPercentage, 50) fan = device.FanReadGpio(speed_filename='foo', percent_filename='bar') self.assertEqual(fan.RPM, -1) self.assertEqual(fan.DesiredPercentage, -1) def install_callback(self, faultcode, faultstring, must_reboot): self.install_cb_called = True self.install_cb_faultcode = faultcode self.install_cb_faultstring = faultstring self.install_cb_must_reboot = must_reboot self.stop() def testBadInstaller(self): device.GINSTALL = '/dev/null' inst = device.Installer('/dev/null', ioloop=self.io_loop) inst.install(file_type='1 Firmware Upgrade Image', target_filename='', callback=self.install_callback) self.assertTrue(self.install_cb_called) self.assertEqual(self.install_cb_faultcode, 9002) self.assertTrue(self.install_cb_faultstring) def testInstallerStdout(self): device.GINSTALL = 'testdata/device/installer_128k_stdout' inst = device.Installer('testdata/device/imagefile', ioloop=self.io_loop) inst.install(file_type='1 Firmware Upgrade Image', target_filename='', callback=self.install_callback) self.wait() self.assertTrue(self.install_cb_called) self.assertEqual(self.install_cb_faultcode, 0) self.assertFalse(self.install_cb_faultstring) self.assertTrue(self.install_cb_must_reboot) def testInstallerFailed(self): device.GINSTALL = 'testdata/device/installer_fails' inst = device.Installer('testdata/device/imagefile', ioloop=self.io_loop) inst.install(file_type='1 Firmware Upgrade Image', target_filename='', callback=self.install_callback) self.wait() self.assertTrue(self.install_cb_called) self.assertEqual(self.install_cb_faultcode, 9002) self.assertTrue(self.install_cb_faultstring) def testSetAcs(self): device.SET_ACS = 'testdata/device/set-acs' scriptout = tempfile.NamedTemporaryFile() os.environ['TESTOUTPUT'] = scriptout.name pc = device.PlatformConfig(ioloop=MockIoloop()) self.assertEqual(pc.GetAcsUrl(), 'bar') pc.SetAcsUrl('foo') self.assertEqual(scriptout.read().strip(), 'cwmp foo') def testClearAcs(self): device.SET_ACS = 'testdata/device/set-acs' scriptout = tempfile.NamedTemporaryFile() os.environ['TESTOUTPUT'] = scriptout.name pc = device.PlatformConfig(ioloop=MockIoloop()) pc.SetAcsUrl('') self.assertEqual(scriptout.read().strip(), 'cwmp clear') def testAcsAccess(self): device.SET_ACS = 'testdata/device/set-acs' scriptout = tempfile.NamedTemporaryFile() os.environ['TESTOUTPUT'] = scriptout.name ioloop = MockIoloop() tmpdir = tempfile.mkdtemp() tmpfile = os.path.join(tmpdir, 'acsconnected') self.assertRaises(OSError, os.stat, tmpfile) # File does not exist yet device.ACSCONNECTED = tmpfile pc = device.PlatformConfig(ioloop) acsurl = 'this is the acs url' # Simulate ACS connection pc.AcsAccessAttempt(acsurl) pc.AcsAccessSuccess(acsurl) self.assertTrue(os.stat(tmpfile)) self.assertEqual(open(tmpfile, 'r').read(), acsurl) self.assertTrue(ioloop.timeout) self.assertTrue(ioloop.callback) # Simulate timeout pc.AcsAccessAttempt(acsurl) scriptout.truncate() ioloop.callback() self.assertRaises(OSError, os.stat, tmpfile) self.assertEqual(scriptout.read().strip(), 'timeout ' + acsurl) # cleanup shutil.rmtree(tmpdir) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for gmoca.py.""" __author__ = 'dgentry@google.com (Denton Gentry)' import base64 import bz2 import tempfile import unittest import google3 import gmoca class GMoCATest(unittest.TestCase): """Tests for gmoca.py.""" def testValidateExports(self): gmoca.MOCACTL = 'testdata/device/mocactl' gm = gmoca.GMoCA() gm.ValidateExports() def testDebugOutput(self): gmoca.MOCACTL = 'testdata/device/mocactl' gm = gmoca.GMoCA() out = gm.DebugOutput self.assertTrue(len(out) > 1024) decode = base64.b64decode(out) # will raise TypeError if invalid decomp = bz2.decompress(decode) self.assertTrue(len(decomp) > 1024) self.assertTrue(decomp.find('X_GOOGLE-COM_GMOCA') >= 0) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for tvxmlrpc.py.""" __author__ = 'dgentry@google.com (Denton Gentry)' import os import SimpleXMLRPCServer import tempfile import threading import unittest import xmlrpclib import google3 import gfibertv class TvPropertyRpcs(object): def __init__(self): self.running = True self.properties = { 'Node1': {'Prop1': 'Prop1Value', 'Prop2': 'Prop2Value'}, 'Node2': {'Prop3': 'Prop3Value'}} def Quit(self): self.running = False return True def GetProperty(self, name, node): return self.properties[node][name] def SetProperty(self, name, value, node): self.properties[node][name] = value return '' def ListNodes(self): return self.properties.keys() def Ping(self): return '' class TvXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): allow_reuse_address = 2 srv_port = 0 srv_cv = threading.Condition() class XmlRpcThread(threading.Thread): def run(self): self.tv = TvPropertyRpcs() xmlrpcsrv = TvXMLRPCServer(('localhost', 0)) global srv_port _, srv_port = xmlrpcsrv.server_address xmlrpcsrv.logRequests = False xmlrpcsrv.register_introspection_functions() xmlrpcsrv.register_instance(self.tv) srv_cv.acquire() srv_cv.notify() srv_cv.release() while self.tv.running: xmlrpcsrv.handle_request() xmlrpcsrv.server_close() class GfiberTvTests(unittest.TestCase): """Tests for gfibertv.py and tvxmlrpc.py.""" def setUp(self): srv_cv.acquire() self.server_thread = XmlRpcThread() self.server_thread.start() srv_cv.wait() (nick_file_handle, self.nick_file_name) = tempfile.mkstemp() (tmp_file_handle, self.tmp_file_name) = tempfile.mkstemp() os.close(nick_file_handle) os.close(tmp_file_handle) gfibertv.NICKFILE = self.nick_file_name gfibertv.NICKFILE_TMP = self.tmp_file_name (btdevices_handle, self.btdevices_fname) = tempfile.mkstemp() (btdevices_tmp_handle, self.btdevices_tmp_fname) = tempfile.mkstemp() os.close(btdevices_handle) os.close(btdevices_tmp_handle) gfibertv.BTDEVICES = self.btdevices_fname gfibertv.BTDEVICES_TMP = self.btdevices_tmp_fname (bthhdevices_handle, self.bthhdevices_fname) = tempfile.mkstemp() (bthhdevices_tmp_handle, self.bthhdevices_tmp_fname) = tempfile.mkstemp() os.close(bthhdevices_handle) os.close(bthhdevices_tmp_handle) gfibertv.BTHHDEVICES = self.bthhdevices_fname gfibertv.BTHHDEVICES_TMP = self.bthhdevices_tmp_fname (btconfig_handle, self.btconfig_fname) = tempfile.mkstemp() (btconfig_tmp_handle, self.btconfig_tmp_fname) = tempfile.mkstemp() os.close(btconfig_handle) os.close(btconfig_tmp_handle) gfibertv.BTCONFIG = self.btconfig_fname gfibertv.BTCONFIG_TMP = self.btconfig_tmp_fname (btnopair_handle, self.btnopair_fname) = tempfile.mkstemp() os.close(btnopair_handle) os.unlink(self.btnopair_fname) gfibertv.BTNOPAIRING = self.btnopair_fname def tearDown(self): xmlrpclib.ServerProxy('http://localhost:%d' % srv_port).Quit() self.server_thread.join() os.unlink(gfibertv.NICKFILE) def testValidate(self): tv = gfibertv.GFiberTv('http://localhost:%d' % srv_port) tv.Mailbox.Node = 'Node1' tv.Mailbox.Name = 'Prop1' tv.ValidateExports() def testGetProperties(self): tvrpc = gfibertv.GFiberTvMailbox('http://localhost:%d' % srv_port) tvrpc.Node = 'Node1' tvrpc.Name = 'Prop1' self.assertEqual(tvrpc.Value, 'Prop1Value') tvrpc.Name = 'Prop2' self.assertEqual(tvrpc.Value, 'Prop2Value') tvrpc.Node = 'Node2' tvrpc.Name = 'Prop3' self.assertEqual(tvrpc.Value, 'Prop3Value') tvrpc.Name = 'Prop4' self.assertRaises(IndexError, lambda: tvrpc.Value) tvrpc.Node = 'Node3' self.assertRaises(IndexError, lambda: tvrpc.Value) def testGetPropertiesProtocolError(self): tvrpc = gfibertv.GFiberTvMailbox('http://localhost:2') tvrpc.Node = 'Node1' tvrpc.Name = 'Prop1' self.assertRaises(IndexError, lambda: tvrpc.Value) def testSetProperties(self): tvrpc = gfibertv.GFiberTvMailbox('http://localhost:%d' % srv_port) tvrpc.Node = 'Node1' tvrpc.Name = 'Prop1' tvrpc.Value = 'Prop1NewValue' self.assertEqual(tvrpc.Value, 'Prop1NewValue') tvrpc.Name = 'Prop4' self.assertRaises(IndexError, lambda: tvrpc.Value) tvrpc.Node = 'Node3' self.assertRaises(IndexError, lambda: tvrpc.Value) def testSetPropertiesProtocolError(self): tvrpc = gfibertv.GFiberTvMailbox('http://localhost:2') tvrpc.Node = 'Node1' tvrpc.Name = 'Prop1' self.assertRaises(IndexError, lambda: tvrpc.SetValue(1)) def testNodeList(self): tvrpc = gfibertv.GFiberTvMailbox('http://localhost:%d' % srv_port) self.assertEqual(tvrpc.NodeList, 'Node1, Node2') def testListManipulation(self): gftv = gfibertv.GFiberTv('http://localhost:%d' % srv_port) gftv.ValidateExports() self.assertEqual(0, gftv.DevicePropertiesNumberOfEntries) idx, newobj = gftv.AddExportObject('DeviceProperties', None) idx = int(idx) self.assertEqual(1, gftv.DevicePropertiesNumberOfEntries) self.assertEqual(newobj, gftv.DevicePropertiesList[idx]) gftv.StartTransaction() gftv.DevicePropertiesList[idx].StartTransaction() gftv.DevicePropertiesList[idx].NickName = 'testroom' gftv.DevicePropertiesList[idx].SerialNumber = '12345' gftv.DevicePropertiesList[idx].AbandonTransaction() gftv.AbandonTransaction() self.assertEqual('', gftv.DevicePropertiesList[idx].NickName) gftv.StartTransaction() idx2, newobj = gftv.AddExportObject('DeviceProperties', None) idx2 = int(idx2) gftv.DevicePropertiesList[idx].StartTransaction() gftv.DevicePropertiesList[idx].NickName = 'testroom' gftv.DevicePropertiesList[idx].SerialNumber = '12345' gftv.DevicePropertiesList[idx].CommitTransaction() gftv.DevicePropertiesList[idx2].StartTransaction() uni_name = u'\u212ced\nroom\n\r!'.encode('utf-8') gftv.DevicePropertiesList[idx2].NickName = uni_name gftv.DevicePropertiesList[idx2].SerialNumber = '56789' gftv.DevicePropertiesList[idx2].CommitTransaction() gftv.CommitTransaction() # read the test file back in. f = file(gfibertv.NICKFILE, 'r') lines = set() lines.add(f.readline()) lines.add(f.readline()) last_line = f.readline() last_line = last_line.strip() self.assertTrue('12345/nickname=testroom\n' in lines) self.assertTrue('56789/nickname=\u212cedroom!\n' in lines) self.assertTrue(last_line.startswith('SERIALS=')) split1 = last_line.split('=') self.assertEqual(2, len(split1)) split2 = split1[1].split(',') self.assertTrue('12345' in split2) self.assertTrue('56789' in split2) f.close() def testBtFiles(self): gftv = gfibertv.GFiberTv('http://localhost:%d' % srv_port) gftv.ValidateExports() def CheckNoTrashLeft(): self.assertEqual(None, gftv.config.bt_devices) self.assertEqual(None, gftv.config.bt_hh_devices) self.assertEqual(None, gftv.config.bt_hh_devices) CheckNoTrashLeft() self.assertEqual('', gftv.BtDevices) self.assertEqual('', gftv.BtHHDevices) self.assertEqual('', gftv.BtConfig) devices1 = 'This is a test' devices2 = 'devices test 2' hhdevices = 'hhdevice str\nwith a newline' config = 'btconfig str' gftv.StartTransaction() gftv.BtDevices = devices1 gftv.CommitTransaction() self.assertEqual(devices1, gftv.BtDevices) self.assertEqual('', gftv.BtHHDevices) self.assertEqual('', gftv.BtConfig) CheckNoTrashLeft() gftv.StartTransaction() gftv.BtDevices = devices2 gftv.BtHHDevices = hhdevices gftv.BtConfig = config gftv.CommitTransaction() self.assertEqual(devices2, gftv.BtDevices) self.assertEqual(hhdevices, gftv.BtHHDevices) self.assertEqual(config, gftv.BtConfig) CheckNoTrashLeft() def testNoPairing(self): gftv = gfibertv.GFiberTv('http://localhost:%d' % srv_port) gftv.ValidateExports() self.assertFalse(gftv.BtNoPairing) gftv.BtNoPairing = True self.assertTrue(gftv.BtNoPairing) # Make sure setting to True works if it is already true. gftv.BtNoPairing = True self.assertTrue(gftv.BtNoPairing) gftv.BtNoPairing = False self.assertFalse(gftv.BtNoPairing) gftv.BtNoPairing = False self.assertFalse(gftv.BtNoPairing) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Fix sys.path so it can find our libraries. This file is named google3.py because gpylint specifically ignores it when complaining about the order of import statements - google3 should always come before other non-python-standard imports. """ __author__ = 'apenwarr@google.com (Avery Pennarun)' import os.path import sys mydir = os.path.dirname(__file__) sys.path += [ os.path.join(mydir, '../..'), ] import tr.google3 #pylint: disable-msg=C6204,W0611
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for gvsb.py.""" __author__ = 'dgentry@google.com (Denton Gentry)' import os import shutil import tempfile import unittest import google3 import gvsb class GvsbTest(unittest.TestCase): """Tests for gvsb.py.""" def testValidateExports(self): gv = gvsb.Gvsb() gv.ValidateExports() def testEpgPrimary(self): temp = tempfile.NamedTemporaryFile() gvsb.EPGPRIMARYFILE = temp.name gv = gvsb.Gvsb() gv.StartTransaction() gv.EpgPrimary = 'Booga' gv.CommitTransaction() self.assertEqual(gv.EpgPrimary, 'Booga') temp.seek(0) self.assertEqual(temp.readline(), 'Booga') temp.close() def testEpgSecondary(self): temp = tempfile.NamedTemporaryFile() gvsb.EPGSECONDARYFILE = temp.name gv = gvsb.Gvsb() gv.StartTransaction() gv.EpgSecondary = 'Booga' gv.CommitTransaction() self.assertEqual(gv.EpgSecondary, 'Booga') temp.seek(0) self.assertEqual(temp.readline(), 'Booga') temp.close() def testGvsbServer(self): temp = tempfile.NamedTemporaryFile() gvsb.GVSBSERVERFILE = temp.name gv = gvsb.Gvsb() gv.StartTransaction() gv.GvsbServer = 'Booga' gv.CommitTransaction() self.assertEqual(gv.GvsbServer, 'Booga') temp.seek(0) self.assertEqual(temp.readline(), 'Booga') temp.close() def testGvsbChannelLineup(self): temp = tempfile.NamedTemporaryFile() gvsb.GVSBCHANNELFILE = temp.name gv = gvsb.Gvsb() self.assertEqual(gv.GvsbChannelLineup, 0) gv.StartTransaction() gv.GvsbChannelLineup = 1000 gv.CommitTransaction() self.assertEqual(gv.GvsbChannelLineup, 1000) temp.seek(0) self.assertEqual(temp.readline(), '1000') temp.close() def testGvsbKick(self): temp = tempfile.NamedTemporaryFile() gvsb.GVSBKICKFILE = temp.name gv = gvsb.Gvsb() gv.StartTransaction() gv.GvsbKick = 'kickme' gv.CommitTransaction() self.assertEqual(gv.GvsbKick, 'kickme') temp.seek(0) self.assertEqual(temp.readline(), 'kickme') temp.close() def _FileIsEmpty(self, filename): st = os.stat(filename) return True if st and st.st_size == 0 else False def testInitEmptyFiles(self): tmpdir = tempfile.mkdtemp() gvsb.EPGPRIMARYFILE = os.path.join(tmpdir, 'epgprimaryfile') gvsb.EPGSECONDARYFILE = os.path.join(tmpdir, 'epgsecondaryfile') gvsb.GVSBSERVERFILE = os.path.join(tmpdir, 'gvsbserverfile') gvsb.GVSBCHANNELFILE = os.path.join(tmpdir, 'gvsbchannelfile') gvsb.GVSBKICKFILE = os.path.join(tmpdir, 'gvsbkickfile') gv = gvsb.Gvsb() gv.StartTransaction() gv.CommitTransaction() self.assertTrue(self._FileIsEmpty(gvsb.EPGPRIMARYFILE)) self.assertTrue(self._FileIsEmpty(gvsb.EPGSECONDARYFILE)) self.assertTrue(self._FileIsEmpty(gvsb.GVSBSERVERFILE)) self.assertTrue(self._FileIsEmpty(gvsb.GVSBCHANNELFILE)) self.assertTrue(self._FileIsEmpty(gvsb.GVSBKICKFILE)) shutil.rmtree(tmpdir) def testAbandonTransaction(self): tmpdir = tempfile.mkdtemp() gvsb.EPGPRIMARYFILE = os.path.join(tmpdir, 'epgprimaryfile') gvsb.EPGSECONDARYFILE = os.path.join(tmpdir, 'epgsecondaryfile') gvsb.GVSBSERVERFILE = os.path.join(tmpdir, 'gvsbserverfile') gvsb.GVSBCHANNELFILE = os.path.join(tmpdir, 'gvsbchannelfile') gvsb.GVSBKICKFILE = os.path.join(tmpdir, 'gvsbkickfile') gv = gvsb.Gvsb() gv.StartTransaction() gv.EpgPrimary = 'epgprimary' gv.EpgSecondary = 'epgsecondary' gv.GvsbServer = 'gvsbserver' gv.GvsbChannelLineup = '1001' gv.GvsbKick = 'gvsbkick' gv.AbandonTransaction() self.assertTrue(self._FileIsEmpty(gvsb.EPGPRIMARYFILE)) self.assertTrue(self._FileIsEmpty(gvsb.EPGSECONDARYFILE)) self.assertTrue(self._FileIsEmpty(gvsb.GVSBSERVERFILE)) self.assertTrue(self._FileIsEmpty(gvsb.GVSBCHANNELFILE)) self.assertTrue(self._FileIsEmpty(gvsb.GVSBKICKFILE)) shutil.rmtree(tmpdir) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-135 STBService.""" __author__ = 'dgentry@google.com (Denton Gentry)' import glob import json import os import re import socket import struct import tr.cwmp_session as cwmp_session import tr.cwmpdate import tr.tr135_v1_2 import tr.x_catawampus_videomonitoring_1_0 as vmonitor BASE135STB = tr.tr135_v1_2.STBService_v1_2.STBService BASEPROGMETADATA = vmonitor.X_CATAWAMPUS_ORG_STBVideoMonitoring_v1_0.STBService IGMPREGEX = re.compile('^\s+(\S+)\s+\d\s+\d:[0-9A-Fa-f]+\s+\d') IGMP6REGEX = re.compile(('^\d\s+\S+\s+([0-9A-Fa-f]{32})\s+\d\s+[0-9A-Fa-f]' '+\s+\d')) PROCNETIGMP = '/proc/net/igmp' PROCNETIGMP6 = '/proc/net/igmp6' CONT_MONITOR_FILES = [ '/tmp/cwmp/monitoring/ts/tr_135_total_tsstats*.json', '/tmp/cwmp/monitoring/dejittering/tr_135_total_djstats*.json'] EPG_STATS_FILES = ['/tmp/cwmp/monitoring/epg/tr_135_epg_stats*.json'] HDMI_STATS_FILE = '/tmp/cwmp/monitoring/hdmi/tr_135_hdmi_stats*.json' HDMI_DISPLAY_DEVICE_STATS_FILES = [ '/tmp/cwmp/monitoring/hdmi/tr_135_dispdev_status*.json', '/tmp/cwmp/monitoring/hdmi/tr_135_dispdev_stats*.json'] class STBService(BASE135STB): """STBService.{i}.""" def __init__(self): super(STBService, self).__init__() self.Unexport('Alias') self.Unexport('Enable') self.Unexport(objects='AVPlayers') self.Unexport(objects='AVStreams') self.Unexport(objects='Applications') self.Unexport(objects='Capabilities') self.Export(objects=['X_CATAWAMPUS-ORG_ProgramMetadata']) self.ServiceMonitoring = ServiceMonitoring() self.Components = Components() self.X_CATAWAMPUS_ORG_ProgramMetadata = ProgMetadata() class Components(BASE135STB.Components): """STBService.{i}.Components.""" def __init__(self): super(Components, self).__init__() self.Unexport('AudioDecoderNumberOfEntries') self.Unexport('AudioOutputNumberOfEntries') self.Unexport('CANumberOfEntries') self.Unexport('DRMNumberOfEntries') self.Unexport('SCARTNumberOfEntries') self.Unexport('SPDIFNumberOfEntries') self.Unexport('VideoDecoderNumberOfEntries') self.Unexport('VideoOutputNumberOfEntries') self.Unexport(objects='PVR') self.Unexport(lists='AudioDecoder') self.Unexport(lists='AudioOutput') self.Unexport(lists='CA') self.Unexport(lists='DRM') self.Unexport(lists='SCART') self.Unexport(lists='SPDIF') self.Unexport(lists='VideoDecoder') self.Unexport(lists='VideoOutput') self.FrontEndList = {'1': FrontEnd()} self.HDMIList = {'1': HDMI()} @property def FrontEndNumberOfEntries(self): return len(self.FrontEndList) @property def HDMINumberOfEntries(self): return len(self.HDMIList) class FrontEnd(BASE135STB.Components.FrontEnd): """STBService.{i}.Components.FrontEnd.{i}.""" def __init__(self): super(FrontEnd, self).__init__() self.Unexport('Alias') self.Unexport('Enable') self.Unexport('Name') self.Unexport('Status') self.Unexport(objects='DVBT') self.IP = IP() class IP(BASE135STB.Components.FrontEnd.IP): """STBService.{i}.Components.FrontEnd.{i}.IP.""" def __init__(self): super(IP, self).__init__() self.Unexport('ActiveInboundIPStreams') self.Unexport('ActiveOutboundIPStreams') self.Unexport('InboundNumberOfEntries') self.Unexport('OutboundNumberOfEntries') self.Unexport(objects='Dejittering') self.Unexport(objects='RTCP') self.Unexport(objects='RTPAVPF') self.Unexport(objects='ServiceConnect') self.Unexport(objects='FEC') self.Unexport(objects='ForceMonitor') self.Unexport(lists='Inbound') self.Unexport(lists='Outbound') self.IGMP = IGMP() class IGMP(BASE135STB.Components.FrontEnd.IP.IGMP): """STBService.{i}.Components.FrontEnd.{i}.IP.IGMP.""" def __init__(self): super(IGMP, self).__init__() self.Unexport('ClientGroupStatsNumberOfEntries') self.Unexport('ClientRobustness') self.Unexport('ClientUnsolicitedReportInterval') self.Unexport('ClientVersion') self.Unexport('DSCPMark') self.Unexport('Enable') self.Unexport('EthernetPriorityMark') self.Unexport('LoggingEnable') self.Unexport('MaximumNumberOfConcurrentGroups') self.Unexport('MaximumNumberOfTrackedGroups') self.Unexport('Status') self.Unexport('VLANIDMark') self.Unexport(lists='ClientGroupStats') self.ClientGroupList = tr.core.AutoDict( 'ClientGroupList', iteritems=self.IterClientGroups, getitem=self.GetClientGroupByIndex) @property def ClientGroupNumberOfEntries(self): return len(self.ClientGroupList) def _ParseProcIgmp(self): """Returns a list of current IGMP group memberships. /proc/net/igmp uses an unusual format: Idx Device : Count Querier Group Users Timer Reporter 1 lo : 1 V3 010000E0 1 0:00000000 0 2 eth0 : 1 V3 010000E0 1 0:00000000 0 010000E0 is the IP multicast address as a hex number, and always big endian. """ igmps = set() with open(PROCNETIGMP, 'r') as f: for line in f: result = IGMPREGEX.match(line) if result is not None: igmp = result.group(1).strip() igmps.add(socket.inet_ntop( socket.AF_INET, struct.pack('<L', int(igmp, 16)))) with open(PROCNETIGMP6, 'r') as f: for line in f: result = IGMP6REGEX.match(line) if result is not None: igmp = result.group(1).strip() ip6 = ':'.join([igmp[0:4], igmp[4:8], igmp[8:12], igmp[12:16], igmp[16:20], igmp[20:24], igmp[24:28], igmp[28:]]) igmps.add(socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, ip6))) return list(igmps) def GetClientGroup(self, ipaddr): return ClientGroup(ipaddr) def IterClientGroups(self): """Retrieves a list of IGMP memberships.""" igmps = self._ParseProcIgmp() for idx, ipaddr in enumerate(igmps, start=1): yield str(idx), self.GetClientGroup(ipaddr) def GetClientGroupByIndex(self, index): igmps = self._ParseProcIgmp() i = int(index) - 1 if i > len(igmps): raise IndexError('No such object ClientGroup.{0}'.format(index)) return self.GetClientGroup(igmps[i]) class ClientGroup(BASE135STB.Components.FrontEnd.IP.IGMP.ClientGroup): """STBService.{i}.Components.FrontEnd.{i}.IP.IGMP.ClientGroup.{i}.""" def __init__(self, ipaddr): super(ClientGroup, self).__init__() self.Unexport('UpTime') self.Unexport('Alias') self.ipaddr = ipaddr @property def GroupAddress(self): return self.ipaddr class HDMI(BASE135STB.Components.HDMI): """STBService.{i}.Components.HDMI.""" def __init__(self): super(HDMI, self).__init__() self.Unexport('Alias') self.Unexport('Enable') self.Unexport('Status') self.Unexport('Name') self.DisplayDevice = HDMIDisplayDevice() @property @cwmp_session.cache def _GetStats(self): data = dict() for filename in glob.glob(HDMI_STATS_FILE): try: with open(filename) as f: d = json.load(f) hdmiStats = d['HDMIStats'] if 'ResolutionValue' in hdmiStats.keys(): data['ResolutionValue'] = hdmiStats['ResolutionValue'] # IOError - Failed to open file or failed to read from file # ValueError - JSON file is malformed and cannot be decoded # KeyError - Decoded JSON file doesn't contain the required fields. except (IOError, ValueError, KeyError) as e: print('HDMIStats: Failed to read stats from file {0}, ' 'error = {1}'.format(filename, e)) return data @property def ResolutionMode(self): return 'Auto' @property def ResolutionValue(self): return self._GetStats.get('ResolutionValue', '') class HDMIDisplayDevice(BASE135STB.Components.HDMI.DisplayDevice): """STBService.{i}.Components.HDMI.{i}.DisplayDevice.""" def __init__(self): super(HDMIDisplayDevice, self).__init__() self.Unexport('CECSupport') self.Export(params=['X_GOOGLE-COM_NegotiationCount4']) self.Export(params=['X_GOOGLE-COM_NegotiationCount24']) self.Export(params=['X_GOOGLE-COM_VendorId']) self.Export(params=['X_GOOGLE-COM_ProductId']) self.Export(params=['X_GOOGLE-COM_MfgYear']) self.Export(params=['X_GOOGLE-COM_LastUpdateTimestamp']) self.Export(params=['X_GOOGLE-COM_EDIDExtensions']) @property @cwmp_session.cache def _GetStats(self): data = dict() for wildcard in HDMI_DISPLAY_DEVICE_STATS_FILES: for filename in glob.glob(wildcard): try: with open(filename) as f: d = json.load(f) displayStats = d['HDMIDisplayDevice'] if 'Status' in displayStats.keys(): data['Status'] = displayStats['Status'] if 'Name' in displayStats.keys(): data['Name'] = displayStats['Name'] if 'EEDID' in displayStats.keys(): data['EEDID'] = displayStats['EEDID'] if 'EDIDExtensions' in displayStats.keys(): data['EDIDExtensions'] = ', '.join(displayStats['EDIDExtensions']) # Supported resolutions can have duplicates! Handle it! if 'SupportedResolutions' in displayStats.keys(): sup_res = set() for v in displayStats['SupportedResolutions']: sup_res.add(v) data['SupportedResolutions'] = ', '.join(sorted(sup_res)) if 'PreferredResolution' in displayStats.keys(): data['PreferredResolution'] = displayStats['PreferredResolution'] if 'VideoLatency' in displayStats.keys(): data['VideoLatency'] = displayStats['VideoLatency'] if 'AutoLipSyncSupport' in displayStats.keys(): data['AutoLipSyncSupport'] = displayStats['AutoLipSyncSupport'] if 'HDMI3DPresent' in displayStats.keys(): data['HDMI3DPresent'] = displayStats['HDMI3DPresent'] if 'Negotiations4hr' in displayStats.keys(): data['Negotiations4hr'] = displayStats['Negotiations4hr'] data['LastUpdateTime'] = os.path.getmtime(filename) if 'Negotiations24hr' in displayStats.keys(): data['Negotiations24hr'] = displayStats['Negotiations24hr'] if 'VendorId' in displayStats.keys(): data['VendorId'] = displayStats['VendorId'] if 'ProductId' in displayStats.keys(): data['ProductId'] = displayStats['ProductId'] if 'MfgYear' in displayStats.keys(): data['MfgYear'] = displayStats['MfgYear'] # IOError - Failed to open file or failed to read from file # ValueError - JSON file is malformed and cannot be decoded # KeyError - Decoded JSON file doesn't contain the required fields. # OSError - mtime call failed. except (IOError, ValueError, KeyError, OSError) as e: print('HDMIStats: Failed to read stats from file {0}, ' 'error = {1}'.format(filename, e)) return data @property def Status(self): return self._GetStats.get('Status', 'None') @property def Name(self): return self._GetStats.get('Name', '') @property def SupportedResolutions(self): return self._GetStats.get('SupportedResolutions', '') @property def EEDID(self): return self._GetStats.get('EEDID', '') @property def X_GOOGLE_COM_EDIDExtensions(self): return self._GetStats.get('EDIDExtensions', '') @property def PreferredResolution(self): return self._GetStats.get('PreferredResolution', '') @property def VideoLatency(self): return self._GetStats.get('VideoLatency', 0) @property def AutoLipSyncSupport(self): return self._GetStats.get('AutoLipSyncSupport', False) @property def HDMI3DPresent(self): return self._GetStats.get('HDMI3DPresent', False) @property def X_GOOGLE_COM_NegotiationCount4(self): return self._GetStats.get('Negotiations4hr', 0) @property def X_GOOGLE_COM_NegotiationCount24(self): return self._GetStats.get('Negotiations24hr', 0) @property def X_GOOGLE_COM_VendorId(self): return self._GetStats.get('VendorId', '') @property def X_GOOGLE_COM_ProductId(self): return self._GetStats.get('ProductId', 0) @property def X_GOOGLE_COM_MfgYear(self): return self._GetStats.get('MfgYear', 1990) @property def X_GOOGLE_COM_LastUpdateTimestamp(self): return tr.cwmpdate.format(float(self._GetStats.get('LastUpdateTime', 0))) class ServiceMonitoring(BASE135STB.ServiceMonitoring): """STBService.{i}.ServiceMonitoring.""" def __init__(self): super(ServiceMonitoring, self).__init__() self.Unexport('FetchSamples') self.Unexport('ForceSample') self.Unexport('ReportEndTime') self.Unexport('ReportSamples') self.Unexport('ReportStartTime') self.Unexport('SampleEnable') self.Unexport('SampleInterval') self.Unexport('SampleState') self.Unexport('TimeReference') self.Unexport('EventsPerSampleInterval') self.Unexport(objects='GlobalOperation') self._MainStreamStats = dict() self.MainStreamList = tr.core.AutoDict( 'MainStreamList', iteritems=self.IterMainStreams, getitem=self.GetMainStreamByIndex) @property def MainStreamNumberOfEntries(self): return len(self.MainStreamList) def UpdateSvcMonitorStats(self): """Retrieve and aggregate stats from all related JSON stats files.""" streams = dict() for wildcard in CONT_MONITOR_FILES: for filename in glob.glob(wildcard): self.DeserializeStats(filename, streams) num_streams = len(streams) new_main_stream_stats = dict() old_main_stream_stats = self._MainStreamStats # Existing stream_ids keep their instance number in self._MainStreamStats for instance, old_stream in old_main_stream_stats.items(): stream_id = old_stream.stream_id if stream_id in streams: new_main_stream_stats[instance] = streams[stream_id] del streams[stream_id] # Remaining stream_ids claim an unused instance number in 1..num_streams assigned = set(new_main_stream_stats.keys()) unassigned = set(range(1, num_streams + 1)) - assigned for strm in streams.values(): instance = unassigned.pop() new_main_stream_stats[instance] = strm self._MainStreamStats = new_main_stream_stats def ReadJSONStats(self, fname): """Retrieves statistics from the service monitoring JSON file.""" d = None with open(fname) as f: d = json.load(f) return d def DeserializeStats(self, fname, new_streams): """Generate stats object from the JSON stats.""" try: d = self.ReadJSONStats(fname) streams = d['STBService'][0]['MainStream'] for i in range(len(streams)): stream_id = streams[i]['StreamId'] strm = new_streams.get(stream_id, MainStream(stream_id)) strm.UpdateMainstreamStats(streams[i]) new_streams[stream_id] = strm # IOError - Failed to open file or failed to read from file # ValueError - JSON file is malformed and cannot be decoded # KeyError - Decoded JSON file doesn't contain the required fields. except (IOError, ValueError, KeyError) as e: print('ServiceMonitoring: Failed to read stats from file {0}, ' 'error = {1}'.format(fname, e)) def IterMainStreams(self): """Retrieves an iterable list of stats.""" self.UpdateSvcMonitorStats() return self._MainStreamStats.items() def GetMainStreamByIndex(self, index): """Directly access the value corresponding to a given key.""" self.UpdateSvcMonitorStats() return self._MainStreamStats[index] class MainStream(BASE135STB.ServiceMonitoring.MainStream): """STBService.{i}.ServiceMonitoring.MainStream.""" def __init__(self, stream_id): super(MainStream, self).__init__() self.Unexport('AVStream') self.Unexport('Enable') self.Unexport('Gmin') self.Unexport('ServiceType') self.Unexport('SevereLossMinDistance') self.Unexport('SevereLossMinLength') self.Unexport('Status') self.Unexport('ChannelChangeFailureTimeout') self.Unexport('Alias') self.Unexport(objects='Sample') self.Export(params=['X_GOOGLE-COM_StreamID']) self.Total = Total() self.stream_id = stream_id @property def X_GOOGLE_COM_StreamID(self): return self.stream_id def UpdateMainstreamStats(self, data): self.Total.UpdateTotalStats(data) class Total(BASE135STB.ServiceMonitoring.MainStream.Total): """STBService.{i}.ServiceMonitoring.MainStream.{i}.Total.""" def __init__(self): super(Total, self).__init__() self.Unexport('Reset') self.Unexport('ResetTime') self.Unexport('TotalSeconds') self.Unexport(objects='AudioDecoderStats') self.Unexport(objects='RTPStats') self.Unexport(objects='VideoDecoderStats') self.Unexport(objects='VideoResponseStats') self.DejitteringStats = DejitteringStats() self.MPEG2TSStats = MPEG2TSStats() self.TCPStats = TCPStats() def UpdateTotalStats(self, data): if 'DejitteringStats' in data.keys(): self.DejitteringStats.UpdateDejitteringStats(data['DejitteringStats']) if 'MPEG2TSStats' in data.keys(): self.MPEG2TSStats.UpdateMPEG2TSStats(data['MPEG2TSStats']) if 'TCPStats' in data.keys(): self.TCPStats.UpdateTCPStats(data['TCPStats']) class DejitteringStats(BASE135STB.ServiceMonitoring.MainStream.Total. DejitteringStats): """STBService.{i}.ServiceMonitoring.MainStream.{i}.Total.DejitteringStats.""" def __init__(self): super(DejitteringStats, self).__init__() self.Unexport('TotalSeconds') self.Export(params=['X_GOOGLE-COM_SessionID']) self._empty_buffer_time = 0 self._overruns = 0 self._underruns = 0 self._session_id = 0 @property def EmptyBufferTime(self): return self._empty_buffer_time @property def Overruns(self): return self._overruns @property def Underruns(self): return self._underruns @property def X_GOOGLE_COM_SessionID(self): return self._session_id def UpdateDejitteringStats(self, djstats): if 'EmptyBufferTime' in djstats.keys(): self._empty_buffer_time = djstats['EmptyBufferTime'] if 'Overruns' in djstats.keys(): self._overruns = djstats['Overruns'] if 'Underruns' in djstats.keys(): self._underruns = djstats['Underruns'] if 'SessionId' in djstats.keys(): self._session_id = djstats['SessionId'] class MPEG2TSStats(BASE135STB.ServiceMonitoring.MainStream.Total.MPEG2TSStats): """STBService.{i}.ServiceMonitoring.MainStream.{i}.Total.MPEG2TSStats.""" def __init__(self): super(MPEG2TSStats, self).__init__() self.Unexport('PacketDiscontinuityCounterBeforeCA') self.Unexport('TSSyncByteErrorCount') self.Unexport('TSSyncLossCount') self.Unexport('TotalSeconds') self._packet_discont_counter = 0 self._ts_packets_received = 0 @property def PacketDiscontinuityCounter(self): return self._packet_discont_counter @property def TSPacketsReceived(self): return self._ts_packets_received def UpdateMPEG2TSStats(self, tsstats): if 'PacketsDiscontinuityCounter' in tsstats.keys(): self._packet_discont_counter = tsstats['PacketsDiscontinuityCounter'] if 'TSPacketsReceived' in tsstats.keys(): self._ts_packets_received = tsstats['TSPacketsReceived'] class TCPStats(BASE135STB.ServiceMonitoring.MainStream.Total.TCPStats): """STBService.{i}.ServiceMonitoring.MainStream.{i}.Total.TCPStats.""" def __init__(self): super(TCPStats, self).__init__() self.Unexport('TotalSeconds') self._bytes_received = 0 self._packets_received = 0 self._packets_retransmitted = 0 @property def BytesReceived(self): return self._bytes_received @property def PacketsReceived(self): return self._packets_received @property def PacketsRetransmitted(self): return self._packets_retransmitted def UpdateTCPStats(self, tcpstats): if 'Bytes Received' in tcpstats.keys(): self._bytes_received = tcpstats['Bytes Received'] if 'Packets Received' in tcpstats.keys(): self._packets_received = tcpstats['Packets Received'] if 'Packets Retransmitted' in tcpstats.keys(): self._packets_retransmitted = tcpstats['Packets Retransmitted'] class ProgMetadata(BASEPROGMETADATA.X_CATAWAMPUS_ORG_ProgramMetadata): """STBService.{i}.X_CATAWAMPUS_ORG_ProgramMetadata.""" def __init__(self): super(ProgMetadata, self).__init__() self.EPG = EPG() class EPG(BASEPROGMETADATA.X_CATAWAMPUS_ORG_ProgramMetadata.EPG): """STBService.{i}.X_CATAWAMPUS_ORG_ProgramMetadata.EPG.""" def __init__(self): super(EPG, self).__init__() @property @cwmp_session.cache def _GetStats(self): """Generate stats object from the JSON stats.""" data = dict() for wildcard in EPG_STATS_FILES: for filename in glob.glob(wildcard): try: with open(filename) as f: d = json.load(f) epgStats = d['EPGStats'] if 'MulticastPackets' in epgStats.keys(): data['MulticastPackets'] = epgStats['MulticastPackets'] if 'EPGErrors' in epgStats.keys(): data['EPGErrors'] = epgStats['EPGErrors'] if 'LastReceivedTime' in epgStats.keys(): data['LastReceivedTime'] = epgStats['LastReceivedTime'] if'EPGExpireTime' in epgStats.keys(): data['EPGExpireTime'] = epgStats['EPGExpireTime'] # IOError - Failed to open file or failed to read from file # ValueError - JSON file is malformed and cannot be decoded # KeyError - Decoded JSON file doesn't contain the required fields. except (IOError, ValueError, KeyError) as e: print('EPGStats: Failed to read stats from file {0}, ' 'error = {1}'.format(filename, e)) return data @property def MulticastPackets(self): return self._GetStats.get('MulticastPackets', 0) @property def EPGErrors(self): return self._GetStats.get('EPGErrors', 0) @property def LastReceivedTime(self): return tr.cwmpdate.format(float(self._GetStats.get('LastReceivedTime', 0))) @property def EPGExpireTime(self): return tr.cwmpdate.format(float(self._GetStats.get('EPGExpireTime', 0))) def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 #pylint: disable-msg=W0404 # """Implement handling for the X_GOOGLE-COM_GMOCA vendor data model.""" __author__ = 'dgentry@google.com (Denton Gentry)' import base64 import bz2 import cStringIO import subprocess import google3 import tr.x_gmoca_1_0 # Unit tests can override these. MOCACTL = '/bin/mocactl' class GMoCA(tr.x_gmoca_1_0.X_GOOGLE_COM_GMOCA_v1_0): """Implementation of x-gmoca.xml.""" MOCACMDS = [['show', '--status'], ['show', '--config'], ['show', '--initparms'], ['show', '--stats'], ['showtbl', '--nodestatus'], ['showtbl', '--nodestats'], ['showtbl', '--ucfwd'], ['showtbl', '--mcfwd'], ['showtbl', '--srcaddr']] def __init__(self): super(GMoCA, self).__init__() @property def DebugOutput(self): compr = bz2.BZ2Compressor() cdata = cStringIO.StringIO() for cmd in self.MOCACMDS: cdata.write(compr.compress('X_GOOGLE-COM_GMOCA --------------------\n')) cdata.write(compr.compress(' '.join(cmd) + '\n')) try: mc = subprocess.Popen([MOCACTL] + cmd, stdout=subprocess.PIPE) out, _ = mc.communicate(None) cdata.write(compr.compress(out)) except IOError: continue cdata.write(compr.flush()) return base64.b64encode(cdata.getvalue()) def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 #pylint: disable-msg=W0404 # """Implement handling for the X_GOOGLE-COM_GFIBERTV vendor data model.""" __author__ = 'dgentry@google.com (Denton Gentry)' import copy import errno import os import xmlrpclib import google3 import tr.core import tr.cwmpbool import tr.helpers import tr.x_gfibertv_1_0 BASETV = tr.x_gfibertv_1_0.X_GOOGLE_COM_GFIBERTV_v1_0.X_GOOGLE_COM_GFIBERTV NICKFILE = '/tmp/nicknames' NICKFILE_TMP = '/tmp/nicknames.tmp' BTDEVICES = '/user/bsa/bt_devices.xml' BTDEVICES_TMP = '/user/bsa/bt_devices.xml.tmp' BTHHDEVICES = '/user/bsa/bt_hh_devices.xml' BTHHDEVICES_TMP = '/user/bsa/bt_hh_devices.xml.tmp' BTCONFIG = '/user/bsa/bt_config.xml' BTCONFIG_TMP = '/user/bsa/bt_config.xml.tmp' BTNOPAIRING = '/usr/bsa/nopairing' class GFiberTvConfig(object): """Class to store configuration settings for GFiberTV.""" pass class PropertiesConfig(object): """Class to store configuration settings for DeviceProperties.""" pass class GFiberTv(BASETV): """Implementation of x-gfibertv.xml.""" def __init__(self, mailbox_url): super(GFiberTv, self).__init__() self.Mailbox = GFiberTvMailbox(mailbox_url) self.config = GFiberTvConfig() self.config.nicknames = dict() self.config_old = None self.config.bt_devices = None self.config.bt_hh_devices = None self.config.bt_config = None self.DevicePropertiesList = tr.core.AutoDict( 'X_GOOGLE_COM_GFIBERTV.DevicePropertiesList', iteritems=self.IterProperties, getitem=self.GetProperties, setitem=self.SetProperties, delitem=self.DelProperties) class DeviceProperties(BASETV.DeviceProperties): """Implementation of gfibertv.DeviceProperties.""" def __init__(self): super(GFiberTv.DeviceProperties, self).__init__() self.config = PropertiesConfig() # nick_name is a unicode string. self.config.nick_name = '' self.config.serial_number = '' def StartTransaction(self): # NOTE(jnewlin): If an inner object is added, we need to do deepcopy. self.config_old = copy.copy(self.config) def AbandonTransaction(self): self.config = self.config_old self.config_old = None def CommitTransaction(self): self.config_old = None @property def NickName(self): return self.config.nick_name.decode('utf-8') @NickName.setter def NickName(self, value): # TODO(jnewlin): Need some sanity here so the user can't enter # a value that hoses the file, like a carriage return or newline. tmp_uni = unicode(value, 'utf-8') tmp_uni = tmp_uni.replace(u'\n', u'') tmp_uni = tmp_uni.replace(u'\r', u'') self.config.nick_name = tmp_uni @property def SerialNumber(self): return self.config.serial_number @SerialNumber.setter def SerialNumber(self, value): self.config.serial_number = value def StartTransaction(self): assert self.config_old is None self.config_old = copy.copy(self.config) def AbandonTransaction(self): self.config = self.config_old self.config_old = None def CommitTransaction(self): """Write out the config file for Sage.""" if self.config.nicknames: with file(NICKFILE_TMP, 'w') as f: serials = [] for nn in self.config.nicknames.itervalues(): f.write('%s/nickname=%s\n' % ( nn.SerialNumber, nn.config.nick_name.encode('unicode-escape'))) serials.append(nn.SerialNumber) f.write('SERIALS=%s\n' % ','.join(serials)) os.rename(NICKFILE_TMP, NICKFILE) if self.config.bt_devices != None: tr.helpers.WriteFileAtomic(BTDEVICES_TMP, BTDEVICES, self.config.bt_devices) self.config.bt_devices = None if self.config.bt_hh_devices != None: tr.helpers.WriteFileAtomic(BTHHDEVICES_TMP, BTHHDEVICES, self.config.bt_hh_devices) self.config.bt_hh_devices = None if self.config.bt_config != None: tr.helpers.WriteFileAtomic(BTCONFIG_TMP, BTCONFIG, self.config.bt_config) self.config.bt_config = None self.config_old = None @property def DevicePropertiesNumberOfEntries(self): return len(self.config.nicknames) def IterProperties(self): return self.config.nicknames.iteritems() def GetProperties(self, key): return self.config.nicknames[key] def SetProperties(self, key, value): self.config.nicknames[key] = value def DelProperties(self, key): del self.config.nicknames[key] @property def BtDevices(self): try: with file(BTDEVICES, 'r') as f: return f.read() except IOError as e: # If the file doesn't exist for some reason, just return an empty # string, otherwise throw the exception, which should get propagated # back to the ACS. if e.errno == errno.ENOENT: return '' raise @property def XX(self): return True @property def BtNoPairing(self): return os.access(BTNOPAIRING, os.R_OK) @BtNoPairing.setter def BtNoPairing(self, value): no_pairing = tr.cwmpbool.parse(value) if no_pairing: with open(BTNOPAIRING, 'w') as f: pass else: try: os.unlink(BTNOPAIRING) except OSError as e: if e.errno != errno.ENOENT: raise @BtDevices.setter def BtDevices(self, value): self.config.bt_devices = value @property def BtHHDevices(self): try: with file(BTHHDEVICES, 'r') as f: return f.read() # IOError is thrown if the file doesn't exist. except IOError: return '' @BtHHDevices.setter def BtHHDevices(self, value): self.config.bt_hh_devices = value @property def BtConfig(self): try: with file(BTCONFIG, 'r') as f: return f.read() # IOError is thrown if the file doesn't exist. except IOError: return '' @BtConfig.setter def BtConfig(self, value): self.config.bt_config = value class GFiberTvMailbox(BASETV.Mailbox): """Implementation of x-gfibertv.xml.""" def __init__(self, url): super(GFiberTvMailbox, self).__init__() self.rpcclient = xmlrpclib.ServerProxy(url) self.Name = '' self.Node = '' def GetValue(self): if not self.Name: return None try: return str(self.rpcclient.GetProperty(self.Name, self.Node)) except xmlrpclib.Fault: raise IndexError('No such Property %s:%s' % (self.Node, self.Name)) except (xmlrpclib.ProtocolError, IOError): raise IndexError( 'Unable to access Property %s:%s' % (self.Node, self.Name)) def SetValue(self, value): try: return str(self.rpcclient.SetProperty(self.Name, value, self.Node)) except xmlrpclib.Fault: raise IndexError('No such Property %s:%s' % (self.Node, self.Name)) except (xmlrpclib.ProtocolError, IOError): raise IndexError( 'Unable to access Property %s:%s' % (self.Node, self.Name)) Value = property(GetValue, SetValue, None, 'X_GOOGLE_COM_GFIBERTV_v1_0.Mailbox.Value') @property def NodeList(self): try: return str(', '.join(self.rpcclient.ListNodes())) except (xmlrpclib.Fault, xmlrpclib.ProtocolError, IOError), e: print 'gfibertv.NodeList: %s' % e return {}
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """tr-181 Device implementations for supported platforms.""" __author__ = 'dgentry@google.com (Denton Gentry)' import datetime import fcntl import os import random import subprocess import traceback import google3 import dm.brcmmoca import dm.brcmwifi import dm.device_info import dm.ethernet import dm.igd_time import dm.periodic_statistics import dm.storage import dm.temperature import platform_config import pynetlinux import tornado.ioloop import tr.core import tr.download import tr.tr098_v1_2 import tr.tr181_v2_2 as tr181 import tr.x_catawampus_tr181_2_0 import gfibertv import gvsb import stbservice BASE98IGD = tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice CATA181DI = tr.x_catawampus_tr181_2_0.X_CATAWAMPUS_ORG_Device_v2_0.DeviceInfo PYNETIFCONF = pynetlinux.ifconfig.Interface # tr-69 error codes INTERNAL_ERROR = 9002 # Unit tests can override these with fake data ACSCONNECTED = '/tmp/gpio/ledcontrol/acsconnected' ACSTIMEOUTMIN = 2*60*60 ACSTIMEOUTMAX = 4*60*60 CONFIGDIR = '/config/tr69' DOWNLOADDIR = '/tmp' GINSTALL = '/bin/ginstall.py' HNVRAM = '/usr/bin/hnvram' LEDSTATUS = '/tmp/gpio/ledstate' NAND_MB = '/proc/sys/dev/repartition/nand_size_mb' PROC_CPUINFO = '/proc/cpuinfo' REBOOT = '/bin/tr69_reboot' REPOMANIFEST = '/etc/repo-buildroot-manifest' SET_ACS = 'set-acs' VERSIONFILE = '/etc/version' class PlatformConfig(platform_config.PlatformConfigMeta): """PlatformConfig for GFMedia devices.""" def __init__(self, ioloop=None): platform_config.PlatformConfigMeta.__init__(self) self._ioloop = ioloop or tornado.ioloop.IOLoop.instance() self.acs_timeout = None self.acs_timeout_interval = random.randrange(ACSTIMEOUTMIN, ACSTIMEOUTMAX) self.acs_timeout_url = None def ConfigDir(self): return CONFIGDIR def DownloadDir(self): return DOWNLOADDIR def GetAcsUrl(self): setacs = subprocess.Popen([SET_ACS, 'print'], stdout=subprocess.PIPE) out, _ = setacs.communicate(None) return out if setacs.returncode == 0 else '' def SetAcsUrl(self, url): set_acs_url = url if url else 'clear' rc = subprocess.call(args=[SET_ACS, 'cwmp', set_acs_url.strip()]) if rc != 0: raise AttributeError('set-acs failed') def _AcsAccessClearTimeout(self): if self.acs_timeout: self._ioloop.remove_timeout(self.acs_timeout) self.acs_timeout = None def _AcsAccessTimeout(self): """Timeout for AcsAccess. There has been no successful connection to ACS in self.acs_timeout_interval seconds. """ try: os.remove(ACSCONNECTED) except OSError as e: if e.errno != errno.ENOENT: raise pass # No such file == harmless try: rc = subprocess.call(args=[SET_ACS, 'timeout', self.acs_timeout_url.strip()]) except OSError: rc = -1 if rc != 0: # Log the failure print '%s timeout %s failed %d' % (SET_ACS, self.acs_timeout_url, rc) def AcsAccessAttempt(self, url): """Called when a connection to the ACS is attempted.""" if url != self.acs_timeout_url: self._AcsAccessClearTimeout() # new ACS, restart timer self.acs_timeout_url = url if not self.acs_timeout: self.acs_timeout = self._ioloop.add_timeout( datetime.timedelta(seconds=self.acs_timeout_interval), self._AcsAccessTimeout) def AcsAccessSuccess(self, url): """Called when a session with the ACS successfully concludes.""" self._AcsAccessClearTimeout() # We only *need* to create a 0 byte file, but write URL for debugging with open(ACSCONNECTED, 'w') as f: f.write(url) class DeviceId(dm.device_info.DeviceIdMeta): """Fetch the DeviceInfo parameters from NVRAM.""" def _GetOneLine(self, filename, default): try: with open(filename, 'r') as f: return f.readline().strip() except: return default def _GetNvramParam(self, param, default=''): """Return a parameter from NVRAM, like the serial number. Args: param: string name of the parameter to fetch. This must match the predefined names supported by /bin/hnvram default: value to return if the parameter is not present in NVRAM. Returns: A string value of the contents. """ cmd = [HNVRAM, '-r', param] devnull = open('/dev/null', 'w') try: hnvram = subprocess.Popen(cmd, stdin=devnull, stderr=devnull, stdout=subprocess.PIPE) out, _ = hnvram.communicate() if hnvram.returncode != 0: # Treat failure to run hnvram same as not having the field populated out = '' except OSError: out = '' outlist = out.strip().split('=') # HNVRAM does not distinguish between "value not present" and # "value present, and is empty." Treat empty values as invalid. if len(outlist) > 1 and outlist[1].strip(): return outlist[1].strip() else: return default @property def Manufacturer(self): return 'Google Fiber' @property def ManufacturerOUI(self): return 'F88FCA' @property def ModelName(self): return self._GetNvramParam('PLATFORM_NAME', default='UnknownModel') @property def Description(self): return 'Set top box for Google Fiber network' @property def SerialNumber(self): serial = self._GetNvramParam('1ST_SERIAL_NUMBER', default=None) if serial is None: serial = self._GetNvramParam('SERIAL_NO', default='000000000000') return serial @property def HardwareVersion(self): """Return NVRAM HW_REV, inferring one if not present.""" hw_rev = self._GetNvramParam('HW_REV', default=None) if hw_rev: return hw_rev # initial builds with no HW_REV; infer a rev. cpu = open(PROC_CPUINFO, 'r').read() if cpu.find('BCM7425B0') > 0: return '0' if cpu.find('BCM7425B2') > 0: # B2 chip with 4 Gig MLC flash == rev1. 1 Gig SLC flash == rev2. try: siz = int(open(NAND_MB, 'r').read()) except OSError: return '?' if siz == 4096: return '1' if siz == 1024: return '2' return '?' @property def AdditionalHardwareVersion(self): return self._GetNvramParam('GPN', default='') @property def SoftwareVersion(self): return self._GetOneLine(VERSIONFILE, '0') @property def AdditionalSoftwareVersion(self): return self._GetOneLine(REPOMANIFEST, '') @property def ProductClass(self): return self._GetNvramParam('PLATFORM_NAME', default='UnknownModel') @property def ModemFirmwareVersion(self): return '0' class Installer(tr.download.Installer): """Installer class used by tr/download.py.""" def __init__(self, filename, ioloop=None): tr.download.Installer.__init__(self) self.filename = filename self._install_cb = None self._ioloop = ioloop or tornado.ioloop.IOLoop.instance() def _call_callback(self, faultcode, faultstring): if self._install_cb: self._install_cb(faultcode, faultstring, must_reboot=True) def install(self, file_type, target_filename, callback): """Install self.filename to disk, then call callback.""" print 'Installing: %r %r' % (file_type, target_filename) ftype = file_type.split() if ftype and ftype[0] != '1': self._call_callback(INTERNAL_ERROR, 'Unsupported file_type {0}'.format(ftype[0])) return False self._install_cb = callback if not os.path.exists(self.filename): self._call_callback(INTERNAL_ERROR, 'Installer: file %r does not exist.' % self.filename) return False cmd = [GINSTALL, '--tar={0}'.format(self.filename), '--partition=other'] try: self._ginstall = subprocess.Popen(cmd, stdout=subprocess.PIPE) except OSError: self._call_callback(INTERNAL_ERROR, 'Unable to start installer process') return False fd = self._ginstall.stdout.fileno() fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK) self._ioloop.add_handler(fd, self.on_stdout, self._ioloop.READ) return True def reboot(self): cmd = [REBOOT] subprocess.call(cmd) def on_stdout(self, fd, events): """Called whenever the ginstall process prints to stdout.""" # drain the pipe inp = '' try: inp = os.read(fd, 4096) except OSError: # returns EWOULDBLOCK pass if inp and inp.strip() != '.': print 'ginstall: %s' % inp.strip() if self._ginstall.poll() >= 0: self._ioloop.remove_handler(self._ginstall.stdout.fileno()) if self._ginstall.returncode == 0: self._call_callback(0, '') else: print 'ginstall: exit code %d' % self._ginstall.poll() self._call_callback(INTERNAL_ERROR, 'Unable to install image.') class Services(tr181.Device_v2_2.Device.Services): """Implements tr-181 Device.Services.""" def __init__(self): tr181.Device_v2_2.Device.Services.__init__(self) self.Export(objects=['StorageServices']) self.StorageServices = dm.storage.StorageServiceLinux26() self._AddStorageDevices() self.Export(lists=['STBService']) self.Export(['STBServiceNumberOfEntries']) self.STBServiceList = {'1': stbservice.STBService()} @property def STBServiceNumberOfEntries(self): return len(self.STBServiceList) def _AddStorageDevices(self): num = 0 for drive in ['sda', 'sdb', 'sdc', 'sdd', 'sde', 'sdf']: try: if os.stat('/sys/block/' + drive): phys = dm.storage.PhysicalMediumDiskLinux26(drive, 'SATA/300') self.StorageServices.PhysicalMediumList[str(num)] = phys num += 1 except OSError: pass num = 0 for i in range(32): ubiname = 'ubi' + str(i) try: if os.stat('/sys/class/ubi/' + ubiname): ubi = dm.storage.FlashMediumUbiLinux26(ubiname) self.StorageServices.X_CATAWAMPUS_ORG_FlashMediaList[str(num)] = ubi num += 1 except OSError: pass class Ethernet(tr181.Device_v2_2.Device.Ethernet): """Implementation of tr-181 Device.Ethernet for GFMedia platforms.""" def __init__(self): tr181.Device_v2_2.Device.Ethernet.__init__(self) self.InterfaceList = {'1': dm.ethernet.EthernetInterfaceLinux26('eth0')} self.VLANTerminationList = {} self.LinkList = {} @property def InterfaceNumberOfEntries(self): return len(self.InterfaceList) @property def VLANTerminationNumberOfEntries(self): return len(self.VLANTerminationList) @property def LinkNumberOfEntries(self): return len(self.LinkList) class Moca(tr181.Device_v2_2.Device.MoCA): """Implementation of tr-181 Device.MoCA for GFMedia platforms.""" def __init__(self): tr181.Device_v2_2.Device.MoCA.__init__(self) self.InterfaceList = {'1': dm.brcmmoca.BrcmMocaInterface('eth1')} @property def InterfaceNumberOfEntries(self): return len(self.InterfaceList) class FanReadGpio(CATA181DI.TemperatureStatus.X_CATAWAMPUS_ORG_Fan): """Implementation of Fan object, reading rev/sec from a file.""" def __init__(self, name='Fan', speed_filename='/tmp/gpio/fanspeed', percent_filename='/tmp/gpio/fanpercent'): super(FanReadGpio, self).__init__() self.Unexport(params='DesiredRPM') self._name = name self._speed_filename = speed_filename self._percent_filename = percent_filename @property def Name(self): return self._name @property def RPM(self): try: f = open(self._speed_filename, 'r') except IOError as e: print 'Fan speed file %r: %s' % (self._speed_filename, e) return -1 try: rps2 = int(f.read()) return rps2 * 30 except ValueError as e: print 'FanReadGpio RPM %r: %s' % (self._speed_filename, e) return -1 @property def DesiredPercentage(self): try: f = open(self._percent_filename, 'r') except IOError as e: print 'Fan percent file %r: %s' % (self._percent_filename, e) return -1 try: return int(f.read()) except ValueError as e: print 'FanReadGpio DesiredPercentage %r: %s' % (self._percent_filename, e) return -1 class Device(tr181.Device_v2_2.Device): """tr-181 Device implementation for Google Fiber media platforms.""" def __init__(self, device_id, periodic_stats): super(Device, self).__init__() self.Unexport(objects='ATM') self.Unexport(objects='Bridging') self.Unexport(objects='CaptivePortal') self.Export(objects=['DeviceInfo']) self.Unexport(objects='DHCPv4') self.Unexport(objects='DHCPv6') self.Unexport(objects='DNS') self.Unexport(objects='DSL') self.Unexport(objects='DSLite') self.Unexport(objects='Firewall') self.Unexport(objects='GatewayInfo') self.Unexport(objects='HPNA') self.Unexport(objects='HomePlug') self.Unexport(objects='Hosts') self.Unexport(objects='IEEE8021x') self.Unexport(objects='IP') self.Unexport(objects='IPv6rd') self.Unexport(objects='LANConfigSecurity') self.Unexport(objects='NAT') self.Unexport(objects='NeighborDiscovery') self.Unexport(objects='PPP') self.Unexport(objects='PTM') self.Unexport(objects='QoS') self.Unexport(objects='RouterAdvertisement') self.Unexport(objects='Routing') self.Unexport(objects='SmartCardReaders') self.Unexport(objects='UPA') self.Unexport(objects='USB') self.Unexport(objects='Users') self.Unexport(objects='WiFi') self.DeviceInfo = dm.device_info.DeviceInfo181Linux26(device_id) led = dm.device_info.LedStatusReadFromFile('LED', LEDSTATUS) self.DeviceInfo.AddLedStatus(led) self.Ethernet = Ethernet() self.ManagementServer = tr.core.TODO() # higher level code splices this in self.MoCA = Moca() self.Services = Services() self.InterfaceStackList = {} self.InterfaceStackNumberOfEntries = 0 self.Export(objects=['PeriodicStatistics']) self.PeriodicStatistics = periodic_stats # GFHD100 & GFMS100 both monitor CPU temperature. # GFMS100 also monitors hard drive temperature. ts = self.DeviceInfo.TemperatureStatus ts.AddSensor(name='CPU temperature', sensor=dm.temperature.SensorReadFromFile( '/tmp/gpio/cpu_temperature')) for drive in ['sda', 'sdb', 'sdc', 'sdd', 'sde', 'sdf']: try: if os.stat('/sys/block/' + drive): ts.AddSensor(name='Hard drive temperature ' + drive, sensor=dm.temperature.SensorHdparm(drive)) except OSError: pass ts.AddFan(FanReadGpio()) class LANDevice(BASE98IGD.LANDevice): """tr-98 InternetGatewayDevice for Google Fiber media platforms.""" def __init__(self): super(LANDevice, self).__init__() self.Unexport('Alias') self.Unexport(objects='Hosts') self.Unexport(lists='LANEthernetInterfaceConfig') self.Unexport(objects='LANHostConfigManagement') self.Unexport(lists='LANUSBInterfaceConfig') self.LANEthernetInterfaceNumberOfEntries = 0 self.LANUSBInterfaceNumberOfEntries = 0 self.WLANConfigurationList = {} if self._has_wifi(): wifi = dm.brcmwifi.BrcmWifiWlanConfiguration('eth2') self.WLANConfigurationList = {'1': wifi} def _has_wifi(self): try: PYNETIFCONF('eth2').get_index() return True except IOError: return False @property def LANWLANConfigurationNumberOfEntries(self): return len(self.WLANConfigurationList) class InternetGatewayDevice(BASE98IGD): """Implements tr-98 InternetGatewayDevice.""" def __init__(self, device_id, periodic_stats): super(InternetGatewayDevice, self).__init__() self.Unexport(objects='CaptivePortal') self.Unexport(objects='DeviceConfig') self.Unexport(params='DeviceSummary') self.Unexport(objects='DownloadDiagnostics') self.Unexport(objects='IPPingDiagnostics') self.Unexport(objects='LANConfigSecurity') self.LANDeviceList = {'1': LANDevice()} self.Unexport(objects='LANInterfaces') self.Unexport(objects='Layer2Bridging') self.Unexport(objects='Layer3Forwarding') self.ManagementServer = tr.core.TODO() # higher level code splices this in self.Unexport(objects='QueueManagement') self.Unexport(objects='Services') self.Unexport(objects='TraceRouteDiagnostics') self.Unexport(objects='UploadDiagnostics') self.Unexport(objects='UserInterface') self.Unexport(lists='WANDevice') self.DeviceInfo = dm.device_info.DeviceInfo98Linux26(device_id) self.Time = dm.igd_time.TimeTZ() self.Export(objects=['PeriodicStatistics']) self.PeriodicStatistics = periodic_stats @property def LANDeviceNumberOfEntries(self): return len(self.LANDeviceList) @property def WANDeviceNumberOfEntries(self): return 0 def PlatformInit(name, device_model_root): """Create platform-specific device models and initialize platform.""" tr.download.INSTALLER = Installer params = [] objects = [] dev_id = DeviceId() periodic_stats = dm.periodic_statistics.PeriodicStatistics() device_model_root.Device = Device(dev_id, periodic_stats) device_model_root.InternetGatewayDevice = InternetGatewayDevice( dev_id, periodic_stats) device_model_root.X_GOOGLE_COM_GVSB = gvsb.Gvsb() tvrpc = gfibertv.GFiberTv('http://localhost:51834/xmlrpc') device_model_root.X_GOOGLE_COM_GFIBERTV = tvrpc objects.append('Device') objects.append('InternetGatewayDevice') objects.append('X_GOOGLE-COM_GVSB') objects.append('X_GOOGLE-COM_GFIBERTV') return (params, objects) def main(): dev_id = DeviceId() periodic_stats = dm.periodic_statistics.PeriodicStatistics() root = Device(dev_id, periodic_stats) root.ValidateExports() tr.core.Dump(root) if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for stbservice.py implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import unittest import google3 import stbservice class STBServiceTest(unittest.TestCase): def setUp(self): self.CONT_MONITOR_FILES_ALT = ['testdata/stbservice/stats_small.json'] self.CONT_MONITOR_FILES_P = ['testdata/stbservice/stats_small.json', 'testdata/stbservice/stats_p2.json', 'testdata/stbservice/stats_p1.json', 'testdata/stbservice/notexist.json'] self.CONT_MONITOR_FILES_P1 = ['testdata/stbservice/stats_p1.json'] self.STATS_FILES_NOEXST = ['testdata/stbservice/notexist.json'] self.old_CONT_MONITOR_FILES = stbservice.CONT_MONITOR_FILES self.old_EPG_STATS_FILES = stbservice.EPG_STATS_FILES self.old_HDMI_DISP_DEVICE_STATS = stbservice.HDMI_DISPLAY_DEVICE_STATS_FILES self.old_HDMI_STATS_FILE = stbservice.HDMI_STATS_FILE self.old_PROCNETIGMP = stbservice.PROCNETIGMP self.old_PROCNETIGMP6 = stbservice.PROCNETIGMP6 stbservice.CONT_MONITOR_FILES = ['testdata/stbservice/stats_full.json'] stbservice.EPG_STATS_FILES = ['testdata/stbservice/epgstats.json'] stbservice.HDMI_DISPLAY_DEVICE_STATS_FILES = [ 'testdata/stbservice/hdmi_dispdev_stats*.json', 'testdata/stbservice/hdmi_dispdev_status*.json'] stbservice.HDMI_STATS_FILE = 'testdata/stbservice/hdmi_stats.json' stbservice.PROCNETIGMP = 'testdata/stbservice/igmp' stbservice.PROCNETIGMP6 = 'testdata/stbservice/igmp6' def tearDown(self): stbservice.CONT_MONITOR_FILES = self.old_CONT_MONITOR_FILES stbservice.EPG_STATS_FILES = self.old_EPG_STATS_FILES stbservice.HDMI_DISPLAY_DEVICE_STATS_FILES = self.old_HDMI_DISP_DEVICE_STATS stbservice.HDMI_STATS_FILE = self.old_HDMI_STATS_FILE stbservice.PROCNETIGMP = self.old_PROCNETIGMP stbservice.PROCNETIGMP6 = self.old_PROCNETIGMP6 def testValidateExports(self): stb = stbservice.STBService() stb.ValidateExports() def testClientGroups(self): stb = stbservice.STBService() igmp = stb.Components.FrontEndList['1'].IP.IGMP self.assertEqual(len(igmp.ClientGroupList), 12) expected = set(['224.0.0.1', '225.0.1.3', '225.0.1.6', '225.0.1.10', '225.0.1.13', '225.0.1.18', '225.0.1.20', '225.0.1.153', '225.0.1.158', 'ff02::1', 'ff02::1:ff30:66af', 'ff02::1:ff30:64af']) actual = set() for i in range(1, 13): actual.add(igmp.ClientGroupList[i].GroupAddress) self.assertEqual(expected, actual) def testNonexistentStatsFile(self): """Test whether the absence of stats file is handled gracefully.""" stbservice.CONT_MONITOR_FILES = self.STATS_FILES_NOEXST stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 0) def testIncorrectStatsFileFormat(self): """Test whether a malformed stats file is handled gracefully.""" # stbservice.PROCNETIGMP is not a JSON file. stbservice.CONT_MONITOR_FILES = [stbservice.PROCNETIGMP] stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 0) def testIncorrectObjectListIndex(self): """Test whether incorrect indexing of the stream object is handled.""" stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 8) self.assertRaises(KeyError, lambda: stb.ServiceMonitoring.MainStreamList[9]) def testDynamicUpdate(self): """Test whether the object stays consistent when the file is updated.""" savedfnames = stbservice.CONT_MONITOR_FILES stbservice.CONT_MONITOR_FILES = self.CONT_MONITOR_FILES_ALT stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 4) for stream in stb.ServiceMonitoring.MainStreamList.values(): if stream.X_GOOGLE_COM_StreamID == 3: self.assertEqual(stream.Total.MPEG2TSStats.TSPacketsReceived, 600) self.assertRaises(KeyError, lambda: stb.ServiceMonitoring.MainStreamList[6]) # Change the underlying json file; The new one has more entries stbservice.CONT_MONITOR_FILES = savedfnames self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 8) self.assertEqual(stream.Total.MPEG2TSStats.TSPacketsReceived, 600) for stream in stb.ServiceMonitoring.MainStreamList.values(): if stream.X_GOOGLE_COM_StreamID == 3: self.assertEqual(stream.Total.MPEG2TSStats.TSPacketsReceived, 600) if stream.X_GOOGLE_COM_StreamID == 6: self.assertEqual(stream.Total.MPEG2TSStats.TSPacketsReceived, 300) def testPartialUpdate(self): """Test whether a stats file with a subset of objects are deserialized.""" stbservice.CONT_MONITOR_FILES = self.CONT_MONITOR_FILES_P1 stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 8) # Dejittering stats not present in file. Check whether the object is init'ed expected_emptybuftime = set([0, 0, 0, 0, 0, 0, 0, 0]) expected_discont = set([10, 20, 30, 40, 50, 60, 70, 80]) actual_emptybuftime = set() actual_discont = set() for v in stb.ServiceMonitoring.MainStreamList.values(): actual_emptybuftime.add(v.Total.DejitteringStats.EmptyBufferTime) actual_discont.add(v.Total.MPEG2TSStats.PacketDiscontinuityCounter) self.assertEqual(expected_emptybuftime, actual_emptybuftime) self.assertEqual(expected_discont, actual_discont) def testAggregateUpdate(self): """Test deserialization from multiple source files.""" stbservice.CONT_MONITOR_FILES = self.CONT_MONITOR_FILES_P self.testTSStats() self.testDejitteringStats() self.testTCPStats() def testTSStats(self): """Test whether transport stream stats are deserialized.""" stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 8) expected_discont = set([10, 20, 30, 40, 50, 60, 70, 80]) expected_pkts = set([100, 200, 300, 400, 500, 600, 700, 800]) actual_discont = set() actual_pkts = set() #using iterators to read the stream data. This should reduce the file reads. for v in stb.ServiceMonitoring.MainStreamList.values(): tsstats = v.Total.MPEG2TSStats actual_discont.add(tsstats.PacketDiscontinuityCounter) actual_pkts.add(tsstats.TSPacketsReceived) self.assertEqual(expected_discont, actual_discont) self.assertEqual(expected_pkts, actual_pkts) def testDejitteringStats(self): """Test whether Dejittering stats are deserialized.""" stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 8) expected_emptybuftime = set([1, 5, 11, 17, 23, 31, 41, 47]) expected_overruns = set([1, 2, 3, 4, 5, 6, 7, 8]) expected_underruns = set([18, 17, 16, 15, 14, 13, 12, 11]) actual_emptybuftime = set() actual_underruns = set() actual_overruns = set() for v in stb.ServiceMonitoring.MainStreamList.values(): djstats = v.Total.DejitteringStats actual_emptybuftime.add(djstats.EmptyBufferTime) actual_overruns.add(djstats.Overruns) actual_underruns.add(djstats.Underruns) self.assertEqual(expected_emptybuftime, actual_emptybuftime) self.assertEqual(expected_underruns, actual_underruns) self.assertEqual(expected_overruns, actual_overruns) def testTCPStats(self): """Test whether TCP stats are deserialized.""" stb = stbservice.STBService() self.assertEqual(stb.ServiceMonitoring.MainStreamNumberOfEntries, 8) expected_pktsrcvd = set([1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000]) expected_bytesrcvd = set([256000, 512000, 768000, 1024000, 1280000, 1536000, 1792000, 2048000]) expected_pktsretran = set([1, 3, 2, 5, 4, 7, 6, 9]) actual_pktsrcvd = set() actual_bytesrcvd = set() actual_pktsretran = set() for v in stb.ServiceMonitoring.MainStreamList.values(): tcpstats = v.Total.TCPStats actual_pktsrcvd.add(tcpstats.PacketsReceived) actual_bytesrcvd.add(tcpstats.BytesReceived) actual_pktsretran.add(tcpstats.PacketsRetransmitted) self.assertEqual(expected_pktsrcvd, actual_pktsrcvd) self.assertEqual(expected_bytesrcvd, actual_bytesrcvd) self.assertEqual(expected_pktsretran, actual_pktsretran) def testInstancePersistance(self): """Test whether MainStream instance numbers are persistent.""" stbservice.CONT_MONITOR_FILES = ['testdata/stbservice/stats_strm1.json'] stb = stbservice.STBService() m = stb.ServiceMonitoring self.assertEqual(m.MainStreamNumberOfEntries, 1) self.assertEqual(m.MainStreamList[1].X_GOOGLE_COM_StreamID, 1) stbservice.CONT_MONITOR_FILES = ['testdata/stbservice/stats_strm12.json'] self.assertEqual(m.MainStreamNumberOfEntries, 2) self.assertEqual(m.MainStreamList[1].X_GOOGLE_COM_StreamID, 1) self.assertEqual(m.MainStreamList[2].X_GOOGLE_COM_StreamID, 2) stbservice.CONT_MONITOR_FILES = ['testdata/stbservice/stats_strm123.json'] self.assertEqual(m.MainStreamNumberOfEntries, 3) self.assertEqual(m.MainStreamList[1].X_GOOGLE_COM_StreamID, 1) self.assertEqual(m.MainStreamList[2].X_GOOGLE_COM_StreamID, 2) self.assertEqual(m.MainStreamList[3].X_GOOGLE_COM_StreamID, 3) stbservice.CONT_MONITOR_FILES = ['testdata/stbservice/stats_strm2.json'] self.assertEqual(m.MainStreamNumberOfEntries, 1) self.assertEqual(m.MainStreamList[2].X_GOOGLE_COM_StreamID, 2) stbservice.CONT_MONITOR_FILES = ['testdata/stbservice/stats_strm23.json'] self.assertEqual(m.MainStreamNumberOfEntries, 2) self.assertEqual(m.MainStreamList[1].X_GOOGLE_COM_StreamID, 3) self.assertEqual(m.MainStreamList[2].X_GOOGLE_COM_StreamID, 2) stb.ValidateExports() def testNonexistentHDMIStatsFile(self): """Test whether the absence of HDMI stats file is handled gracefully.""" stbservice.HDMI_STATS_FILE = self.STATS_FILES_NOEXST[0] stbservice.HDMI_DISPLAY_DEVICE_STATS_FILES = self.STATS_FILES_NOEXST stb = stbservice.STBService() self.assertEqual(stb.Components.HDMINumberOfEntries, 1) for v in stb.Components.HDMIList.values(): self.assertEqual(v.ResolutionMode, 'Auto') self.assertEqual(v.ResolutionValue, '') self.assertEqual(v.DisplayDevice.Status, 'None') self.assertEqual(v.DisplayDevice.Name, '') self.assertEqual(v.DisplayDevice.EEDID, '') self.assertEqual(len(v.DisplayDevice.SupportedResolutions), 0) self.assertEqual(v.DisplayDevice.PreferredResolution, '') self.assertEqual(v.DisplayDevice.VideoLatency, 0) self.assertEqual(v.DisplayDevice.AutoLipSyncSupport, False) self.assertEqual(v.DisplayDevice.HDMI3DPresent, False) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_NegotiationCount4, 0) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_NegotiationCount24, 0) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_VendorId, '') self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_ProductId, 0) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_MfgYear, 1990) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_LastUpdateTimestamp, '0001-01-01T00:00:00Z') def testHDMIStatsAll(self): """Test deserialization of all HDMI stats parameters.""" stb = stbservice.STBService() self.assertEqual(stb.Components.HDMINumberOfEntries, 1) for v in stb.Components.HDMIList.values(): self.assertEqual(v.ResolutionMode, 'Auto') self.assertEqual(v.ResolutionValue, '640x480 @ 51Hz') self.assertEqual(v.DisplayDevice.Status, 'Present') self.assertEqual(v.DisplayDevice.Name, 'X213W') self.assertEqual(v.DisplayDevice.EEDID, ('00ffffffffffff000472330088b4808' '008120103802f1e78eade95a3544c99' '260f5054bfef90a940714f814001019' '500950f9040010121399030621a2740' '68b03600da2811000019000000fd003' '84d1f5411000a202020202020000000' 'ff004c43473043303233343031300a0' '00000fc0058323133570a2020202020' '202000d9')) self.assertEqual(v.DisplayDevice.SupportedResolutions, ('640x480 @ 51Hz, ' '640x480 @ 52Hz, ' '640x480 @ 55Hz')) self.assertEqual(v.DisplayDevice.PreferredResolution, '640x480 @ 51Hz') self.assertEqual(v.DisplayDevice.VideoLatency, 0) self.assertEqual(v.DisplayDevice.AutoLipSyncSupport, False) self.assertEqual(v.DisplayDevice.HDMI3DPresent, False) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_EDIDExtensions, v.DisplayDevice.EEDID + ', ' + v.DisplayDevice.EEDID) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_NegotiationCount4, 3) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_NegotiationCount24, 9) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_VendorId, 'ACR') self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_ProductId, 51) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_MfgYear, 2008) def testIncorrectHDMIStatsFile(self): """Test deserialization when a subset of stats files are invalid.""" stbservice.HDMI_STATS_FILE = stbservice.PROCNETIGMP stb = stbservice.STBService() self.assertEqual(stb.Components.HDMINumberOfEntries, 1) for v in stb.Components.HDMIList.values(): self.assertEqual(v.ResolutionMode, 'Auto') self.assertEqual(v.ResolutionValue, '') self.assertEqual(v.DisplayDevice.Name, 'X213W') def testPartialHDMIStatsFiles(self): """Test deserialization when a subset of files are not present.""" stbservice.HDMI_DISPLAY_DEVICE_STATS_FILES = [ 'testdata/stbservice/hdmi_dispdev_status.json'] stb = stbservice.STBService() self.assertEqual(stb.Components.HDMINumberOfEntries, 1) for v in stb.Components.HDMIList.values(): self.assertEqual(v.ResolutionMode, 'Auto') self.assertEqual(v.ResolutionValue, '640x480 @ 51Hz') self.assertEqual(v.DisplayDevice.Status, 'Present') self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_NegotiationCount4, 3) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_NegotiationCount24, 9) self.assertEqual(v.DisplayDevice.Name, '') self.assertEqual(v.DisplayDevice.EEDID, '') self.assertEqual(len(v.DisplayDevice.SupportedResolutions), 0) self.assertEqual(v.DisplayDevice.PreferredResolution, '') self.assertEqual(v.DisplayDevice.VideoLatency, 0) self.assertEqual(v.DisplayDevice.AutoLipSyncSupport, False) self.assertEqual(v.DisplayDevice.HDMI3DPresent, False) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_VendorId, '') self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_ProductId, 0) self.assertEqual(v.DisplayDevice.X_GOOGLE_COM_MfgYear, 1990) def testEPGStatsNoFile(self): """Test whether EPG stats are deserialized properly when not file backed.""" stbservice.EPG_STATS_FILES = self.STATS_FILES_NOEXST stb = stbservice.STBService() stb.X_CATAWAMPUS_ORG_ProgramMetadata.ValidateExports() epgStats = stb.X_CATAWAMPUS_ORG_ProgramMetadata.EPG self.assertEqual(epgStats.MulticastPackets, 0) self.assertEqual(epgStats.EPGErrors, 0) self.assertEqual(epgStats.LastReceivedTime, '0001-01-01T00:00:00Z') self.assertEqual(epgStats.EPGExpireTime, '0001-01-01T00:00:00Z') def testEPGStatsIncorrectFileFormat(self): """Test whether EPG stats are handled properly for a bad file.""" stbservice.EPG_STATS_FILES = [stbservice.PROCNETIGMP] stb = stbservice.STBService() stb.X_CATAWAMPUS_ORG_ProgramMetadata.ValidateExports() epgStats = stb.X_CATAWAMPUS_ORG_ProgramMetadata.EPG self.assertEqual(epgStats.MulticastPackets, 0) self.assertEqual(epgStats.EPGErrors, 0) self.assertEqual(epgStats.LastReceivedTime, '0001-01-01T00:00:00Z') self.assertEqual(epgStats.EPGExpireTime, '0001-01-01T00:00:00Z') def testEPGStatsAll(self): """Test whether EPG stats are deserialized properly.""" stb = stbservice.STBService() stb.X_CATAWAMPUS_ORG_ProgramMetadata.ValidateExports() epgStats = stb.X_CATAWAMPUS_ORG_ProgramMetadata.EPG self.assertEqual(epgStats.MulticastPackets, 1002) self.assertEqual(epgStats.EPGErrors, 2) self.assertEqual(epgStats.LastReceivedTime, '2012-07-25T01:50:37Z') self.assertEqual(epgStats.EPGExpireTime, '2012-07-30T01:50:37Z') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 #pylint: disable-msg=W0404 # """Implement the X_GOOGLE-COM_GVSB vendor data model.""" __author__ = 'dgentry@google.com (Denton Gentry)' import copy import google3 import tr.x_gvsb_1_0 # Unit tests can override these. EPGPRIMARYFILE = '/tmp/epgprimary' EPGSECONDARYFILE = '/tmp/epgsecondary' GVSBCHANNELFILE = '/tmp/gvsbchannel' GVSBKICKFILE = '/tmp/gvsbkick' GVSBSERVERFILE = '/tmp/gvsbhost' class GvsbConfig(object): """A dumb data object to store config settings.""" pass class Gvsb(tr.x_gvsb_1_0.X_GOOGLE_COM_GVSB_v1_1): """Implementation of x-gvsb.xml.""" def __init__(self): super(Gvsb, self).__init__() self.config = self.DefaultConfig() self.WriteFile(EPGPRIMARYFILE, '') self.WriteFile(EPGSECONDARYFILE, '') self.WriteFile(GVSBCHANNELFILE, '') self.WriteFile(GVSBKICKFILE, '') self.WriteFile(GVSBSERVERFILE, '') def DefaultConfig(self): obj = GvsbConfig() obj.epgprimary = None obj.epgsecondary = None obj.gvsbserver = None obj.gvsb_channel_lineup = 0 obj.gvsb_kick = None return obj def StartTransaction(self): config = self.config self.config = copy.copy(config) self.old_config = config def AbandonTransaction(self): self.config = self.old_config self.old_config = None def CommitTransaction(self): self._ConfigureGvsb() self.old_config = None def GetEpgPrimary(self): return self.config.epgprimary def SetEpgPrimary(self, value): self.config.epgprimary = value EpgPrimary = property(GetEpgPrimary, SetEpgPrimary, None, 'X_GVSB.EpgPrimary') def GetEpgSecondary(self): return self.config.epgsecondary def SetEpgSecondary(self, value): self.config.epgsecondary = value EpgSecondary = property(GetEpgSecondary, SetEpgSecondary, None, 'X_GVSB.EpgSecondary') def GetGvsbServer(self): return self.config.gvsbserver def SetGvsbServer(self, value): self.config.gvsbserver = value GvsbServer = property(GetGvsbServer, SetGvsbServer, None, 'X_GVSB.GvsbServer') def GetGvsbChannelLineup(self): return self.config.gvsb_channel_lineup def SetGvsbChannelLineup(self, value): self.config.gvsb_channel_lineup = int(value) GvsbChannelLineup = property(GetGvsbChannelLineup, SetGvsbChannelLineup, None, 'X_GVSB.GvsbChannelLineup') def GetGvsbKick(self): return self.config.gvsb_kick def SetGvsbKick(self, value): self.config.gvsb_kick = value GvsbKick = property(GetGvsbKick, SetGvsbKick, None, 'X_GVSB.GvsbKick') def WriteFile(self, filename, content): try: with open(filename, 'w') as f: f.write(content) return True except IOError: return False def _ConfigureGvsb(self): if self.config.epgprimary != self.old_config.epgprimary: if self.WriteFile(EPGPRIMARYFILE, str(self.config.epgprimary)): self.old_config.epgprimary = self.config.epgprimary if self.config.epgsecondary != self.old_config.epgsecondary: if self.WriteFile(EPGSECONDARYFILE, str(self.config.epgsecondary)): self.old_config.epgsecondary = self.config.epgsecondary if self.config.gvsbserver != self.old_config.gvsbserver: if self.WriteFile(GVSBSERVERFILE, str(self.config.gvsbserver)): self.old_config.gvsbserver = self.config.gvsbserver if self.config.gvsb_channel_lineup != self.old_config.gvsb_channel_lineup: if self.WriteFile(GVSBCHANNELFILE, str(self.config.gvsb_channel_lineup)): self.old_config.gvsb_channel_lineup = self.config.gvsb_channel_lineup if self.config.gvsb_kick != self.old_config.gvsb_kick: if self.WriteFile(GVSBKICKFILE, self.config.gvsb_kick): self.old_config.gvsb_kick = self.config.gvsb_kick def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Fix sys.path so it can find our libraries. This file is named google3.py because gpylint specifically ignores it when complaining about the order of import statements - google3 should always come before other non-python-standard imports. """ __author__ = 'apenwarr@google.com (Avery Pennarun)' import tr.google3 #pylint: disable-msg=C6204,W0611
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for TraceRoute implementation.""" __author__ = 'apenwarr@google.com (Avery Pennarun)' import unittest import google3 import tr.mainloop import traceroute class TraceRouteTest(unittest.TestCase): """Tests for traceroute.py.""" def _DoTrace(self, loop, trace, hostname, maxhops): trace.Host = hostname trace.MaxHopCount = maxhops trace.DiagnosticsState = 'Requested' while trace.DiagnosticsState == 'Requested': loop.RunOnce(timeout=5) def testTraceRoute(self): loop = tr.mainloop.MainLoop() trace = traceroute.TraceRoute(loop) self._DoTrace(loop, trace, '127.0.0.1', 1) self.assertEqual(len(trace.RouteHopsList), 1) self.assertEqual(trace.RouteHopsList[1].Host, 'localhost') self.assertEqual(trace.RouteHopsList[1].HostAddress, '127.0.0.1') self.assertEqual(trace.DiagnosticsState, 'Error_MaxHopCountExceeded') self._DoTrace(loop, trace, '::1', 2) self.assertEqual(len(trace.RouteHopsList), 1) self.assertTrue(trace.RouteHopsList[1].Host == 'localhost' or trace.RouteHopsList[1].Host == 'ip6-localhost') self.assertEqual(trace.RouteHopsList[1].HostAddress, '::1') self.assertEqual(trace.DiagnosticsState, 'Complete') self._DoTrace(loop, trace, 'this-name-does-not-exist', 30) self.assertEqual(len(trace.RouteHopsList), 0) self.assertEqual(trace.DiagnosticsState, 'Error_CannotResolveHostName') self._DoTrace(loop, trace, 'google.com', 30) self.assertTrue(len(trace.RouteHopsList) > 1) self.assertEqual(trace.DiagnosticsState, 'Complete') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for dm_root.py.""" __author__ = 'dgentry@google.com (Denton Gentry)' import unittest import google3 import dm_root import tr.tr098_v1_4 import tr.tr181_v2_2 BASE181 = tr.tr181_v2_2.Device_v2_2.Device BASE98 = tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice class MockTr181(BASE181): pass class MockTr98(BASE98): pass class MockManagement(object): def __init__(self): self.EnableCWMP = False class DeviceModelRootTest(unittest.TestCase): def testAddManagementServer(self): root = dm_root.DeviceModelRoot(loop=None, platform=None) mgmt = MockManagement() root.add_management_server(mgmt) # should do nothing. root.Device = MockTr181() root.InternetGatewayDevice = MockTr98() root.Export(objects=['Device', 'InternetGatewayDevice']) self.assertFalse(isinstance(root.InternetGatewayDevice.ManagementServer, BASE98.ManagementServer)) self.assertFalse(isinstance(root.Device.ManagementServer, BASE181.ManagementServer)) root.add_management_server(mgmt) # should do nothing. self.assertTrue(isinstance(root.InternetGatewayDevice.ManagementServer, BASE98.ManagementServer)) self.assertTrue(isinstance(root.Device.ManagementServer, BASE181.ManagementServer)) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for cwmpd.""" __author__ = 'apenwarr@google.com (Avery Pennarun)' import errno import os import select import subprocess import unittest import google3 import tr.helpers class RunserverTest(unittest.TestCase): """Tests for cwmpd and cwmp.""" sockname = '/tmp/cwmpd_test.sock.%d' % os.getpid() def _StartClient(self, stdout=None): client = subprocess.Popen(['./cwmp', '--unix-path', self.sockname], stdin=subprocess.PIPE, stdout=stdout) client.stdin.close() return client def _DoTest(self, args): print print 'Testing with args=%r' % args tr.helpers.Unlink(self.sockname) server = subprocess.Popen(['./cwmpd', '--rcmd-port', '0', '--unix-path', self.sockname, '--close-stdio'] + args, stdout=subprocess.PIPE, stdin=subprocess.PIPE) try: print 'waiting for server to start...' while server.stdout.read(): pass client = self._StartClient() self.assertEqual(client.wait(), 0) server.stdin.close() self.assertEqual(server.wait(), 0) finally: try: server.kill() except OSError: pass tr.helpers.Unlink(self.sockname) def testExitOnError(self): print 'testing client exit when server not running' client = self._StartClient(stdout=subprocess.PIPE) r, _, _ = select.select([client.stdout], [], [], 5) try: self.assertNotEqual(r, []) self.assertNotEqual(client.wait(), 0) finally: if client.poll() is None: client.kill() def testRunserver(self): self._DoTest(['--no-cpe']) self._DoTest(['--no-cpe', '--platform', 'fakecpe']) self._DoTest(['--fake-acs', '--platform', 'fakecpe']) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-181 Device.Ethernet hierarchy of objects. Handles the Device.Ethernet portion of TR-181, as described in http://www.broadband-forum.org/cwmp/tr-181-2-2-0.html """ __author__ = 'dgentry@google.com (Denton Gentry)' import pynetlinux import tr.core import tr.cwmpdate import tr.tr181_v2_4 import tr.x_catawampus_tr181_2_0 import netdev BASEETHERNET = tr.tr181_v2_4.Device_v2_4.Device.Ethernet CATAWAMPUSETHERNET = tr.x_catawampus_tr181_2_0.X_CATAWAMPUS_ORG_Device_v2_0.Device.Ethernet PYNETIFCONF = pynetlinux.ifconfig.Interface class EthernetInterfaceStatsLinux26(netdev.NetdevStatsLinux26, BASEETHERNET.Interface.Stats): """tr181 Ethernet.Interface.{i}.Stats implementation for Linux eth#.""" def __init__(self, ifname): netdev.NetdevStatsLinux26.__init__(self, ifname) BASEETHERNET.Interface.Stats.__init__(self) class EthernetInterfaceLinux26(CATAWAMPUSETHERNET.Interface): """Handling for a Linux 2.6-style device like eth0/eth1/etc. Constructor arguments: ifname: netdev name, like 'eth0' """ def __init__(self, ifname, upstream=False): super(EthernetInterfaceLinux26, self).__init__() self._pynet = PYNETIFCONF(ifname) self._ifname = ifname self.Unexport('Alias') self.Name = ifname self.Upstream = upstream @property def DuplexMode(self): return 'Auto' @property def Enable(self): return True @property def LastChange(self): return tr.cwmpdate.format(0) @property def LowerLayers(self): return '' @property def MACAddress(self): return self._pynet.get_mac() @property def MaxBitRate(self): return -1 @property def Status(self): if not self._pynet.is_up(): return 'Down' (speed, duplex, auto, link_up) = self._pynet.get_link_info() if link_up: return 'Up' else: return 'Dormant' @property def Stats(self): return EthernetInterfaceStatsLinux26(self._ifname) @property def X_CATAWAMPUS_ORG_ActualBitRate(self): (speed, duplex, auto, link_up) = self._pynet.get_link_info() return speed @property def X_CATAWAMPUS_ORG_ActualDuplexMode(self): (speed, duplex, auto, link_up) = self._pynet.get_link_info() return 'Full' if duplex else 'Half' def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-181 Device.DeviceInfo.TemperatureStatus object. Handles the Device.DeviceInfo.TemperatureStatus portion of TR-181, as described by http://www.broadband-forum.org/cwmp/tr-181-2-2-0.html """ __author__ = 'dgentry@google.com (Denton Gentry)' import copy import datetime import re import subprocess import tornado.ioloop import tr.core import tr.cwmpbool import tr.cwmpdate import tr.tr181_v2_2 import tr.x_catawampus_tr181_2_0 BASE181TEMPERATURE = tr.tr181_v2_2.Device_v2_2.DeviceInfo.TemperatureStatus CATA181DI = tr.x_catawampus_tr181_2_0.X_CATAWAMPUS_ORG_Device_v2_0.DeviceInfo NUMBER = re.compile(r'(\d+(?:\.\d+)?)') # tr-181 defines a temperature below 0 Kelvin as "Invalid temperature" BADCELSIUS = -274 # Unit tests can override these with fake data HDPARM = 'hdparm' PERIODICCALL = tornado.ioloop.PeriodicCallback TIMENOW = datetime.datetime.now def GetNumberFromFile(filename): """Extract a number from a file. The number can be an integer or float. If float, it will be rounded. Returns: an integer. """ with open(filename, 'r') as f: result = NUMBER.search(f.readline()) if result is not None: return int(round(float(result.group(0)))) raise ValueError('No number found in %s' % filename) class TemperatureSensorConfig(object): pass class TemperatureSensor(BASE181TEMPERATURE.TemperatureSensor): """Implements tr-181 TemperatureStatus.TemperatureSensor. Args: name: a descriptive name for this sensor. sensor: an object with a GetTemperature() method. This class implements the hardware and platform-independant portions of a TemperatureSensor. It periodically calls sensor.GetTemperature() to obtain a sample from the hardware. """ DEFAULTPOLL = 300 def __init__(self, name, sensor, ioloop=None): super(TemperatureSensor, self).__init__() self._name = name self._sensor = sensor self.ioloop = ioloop or tornado.ioloop.IOLoop.instance() self.scheduler = None self.config = self._GetDefaultSettings() self.old_config = None self._ResetReadings() self._Configure() def _ResetReadings(self): unknown_time = tr.cwmpdate.format(0) self._high_alarm_time = unknown_time self._do_reset_high_alarm_time = False self._low_alarm_time = unknown_time self._do_reset_low_alarm_time = False self._last_update = unknown_time self._min_value = None self._min_time = unknown_time self._max_value = None self._max_time = unknown_time self._reset_time = unknown_time self._value = BADCELSIUS def _GetDefaultSettings(self): obj = TemperatureSensorConfig() obj.p_enable = True obj.p_polling_interval = self.DEFAULTPOLL obj.p_low_alarm_value = None obj.p_high_alarm_value = None return obj def StartTransaction(self): self.old_config = self.config self.config = copy.deepcopy(self.old_config) def AbandonTransaction(self): self.config = self.old_config self.old_config = None def CommitTransaction(self): self.old_config = None self._Configure() def GetEnable(self): return self.config.p_enable def SetEnable(self, value): self.config.p_enable = tr.cwmpbool.parse(value) Enable = property(GetEnable, SetEnable, None, 'TemperatureSensor.Enable') def GetHighAlarmValue(self): if self.config.p_high_alarm_value is None: return BADCELSIUS else: return self.config.p_high_alarm_value def SetHighAlarmValue(self, value): self.config.p_high_alarm_value = int(value) self._do_reset_high_alarm_time = True HighAlarmValue = property(GetHighAlarmValue, SetHighAlarmValue, None, 'TemperatureSensor.HighAlarmValue') @property def HighAlarmTime(self): return self._high_alarm_time @property def LastUpdate(self): return self._last_update def GetLowAlarmValue(self): if self.config.p_low_alarm_value is None: return BADCELSIUS else: return self.config.p_low_alarm_value def SetLowAlarmValue(self, value): self.config.p_low_alarm_value = int(value) self._do_reset_low_alarm_time = True LowAlarmValue = property(GetLowAlarmValue, SetLowAlarmValue, None, 'TemperatureSensor.LowAlarmValue') @property def LowAlarmTime(self): return self._low_alarm_time @property def MinTime(self): return self._min_time @property def MinValue(self): return BADCELSIUS if self._min_value is None else self._min_value @property def MaxTime(self): return self._max_time @property def MaxValue(self): return BADCELSIUS if self._max_value is None else self._max_value @property def Name(self): return self._name def GetPollingInterval(self): return self.config.p_polling_interval def SetPollingInterval(self, value): v = int(value) if v < 0: raise ValueError('Invalid PollingInterval %d' % v) if v == 0: v = self.DEFAULTPOLL self.config.p_polling_interval = v PollingInterval = property(GetPollingInterval, SetPollingInterval) def GetReset(self): return False def SetReset(self, value): if tr.cwmpbool.parse(value): self._ResetReadings() self._reset_time = tr.cwmpdate.format(TIMENOW()) Reset = property(GetReset, SetReset, None, 'TemperatureSensor.Reset') @property def ResetTime(self): return self._reset_time @property def Status(self): return 'Enabled' if self.config.p_enable else 'Disabled' @property def Value(self): return self._value def SampleTemperature(self): t = self._sensor.GetTemperature() self._value = t now = tr.cwmpdate.format(TIMENOW()) self._last_update = now if self._min_value is None or t < self._min_value: self._min_value = t self._min_time = now if self._max_value is None or t > self._max_value: self._max_value = t self._max_time = now high = self.config.p_high_alarm_value if high is not None and t > high: self._high_alarm_time = now low = self.config.p_low_alarm_value if low is not None and t < low: self._low_alarm_time = now def _Configure(self): if self._do_reset_high_alarm_time: self._high_alarm_time = tr.cwmpdate.format(0) self._do_reset_high_alarm_time = False if self._do_reset_low_alarm_time: self._low_alarm_time = tr.cwmpdate.format(0) self._do_reset_low_alarm_time = False if self.scheduler is not None: self.scheduler.stop() self.scheduler = None if self.config.p_enable: self.scheduler = PERIODICCALL(self.SampleTemperature, self.config.p_polling_interval * 1000, io_loop=self.ioloop) self.scheduler.start() # Let new alarm thresholds take effect self.SampleTemperature() class SensorHdparm(object): """Hard drive temperature sensor implementation. This object can be passed as the sensor argument to a TemperatureSensor object, to monitor hard drive temperature. """ DRIVETEMP = re.compile(r'drive temperature \(celsius\) is:\s*(\d+(?:\.\d+)?)') def __init__(self, dev): self._dev = dev if dev[0] == '/' else '/dev/' + dev def GetTemperature(self): hd = subprocess.Popen([HDPARM, '-H', self._dev], stdout=subprocess.PIPE) out, _ = hd.communicate(None) for line in out.splitlines(): result = self.DRIVETEMP.search(line) if result is not None: return int(round(float(result.group(1)))) return BADCELSIUS class SensorReadFromFile(object): """Read a temperature from an arbitrary file. Opens a file looks for a number in the first line. This is treated as a temperature in degrees Celsius. This object can be passed as the sensor argument to a TemperatureSensor object, to monitor an arbitrary temperature written to a file. """ def __init__(self, filename): self._filename = filename def GetTemperature(self): try: return GetNumberFromFile(self._filename) except (IOError, ValueError): print 'TempFromFile %s: bad value' % self._filename return BADCELSIUS class TemperatureStatus(CATA181DI.TemperatureStatus): """Implementation of tr-181 DeviceInfo.TemperatureStatus.""" def __init__(self): super(TemperatureStatus, self).__init__() self.TemperatureSensorList = dict() self._next_sensor_number = 1 self.X_CATAWAMPUS_ORG_FanList = dict() self._next_fan_number = 1 @property def TemperatureSensorNumberOfEntries(self): return len(self.TemperatureSensorList) @property def X_CATAWAMPUS_ORG_FanNumberOfEntries(self): return len(self.X_CATAWAMPUS_ORG_FanList) def AddSensor(self, name, sensor): ts = TemperatureSensor(name=name, sensor=sensor) ts.SampleTemperature() self.TemperatureSensorList[self._next_sensor_number] = ts self._next_sensor_number += 1 def AddFan(self, fan): self.X_CATAWAMPUS_ORG_FanList[self._next_fan_number] = fan self._next_fan_number += 1 class FanReadFileRPS(CATA181DI.TemperatureStatus.X_CATAWAMPUS_ORG_Fan): """Implementation of Fan object, reading rev/sec from a file.""" def __init__(self, name, filename): super(FanReadFileRPS, self).__init__() self._name = name self._filename = filename @property def Name(self): return self._name @property def RPM(self): try: rps = GetNumberFromFile(self._filename) return rps * 60 except ValueError as e: print 'FanReadFileRPS bad value %s' % self._filename return -1 @property def DesiredRPM(self): return -1 @property def DesiredPercentage(self): return -1 def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-157 collection of periodic statistics.""" __author__ = 'jnewlin@google.com (John Newlin)' import datetime import time import tr.cwmpbool import tr.tr157_v1_3 # TODO(jnewlin): Denton has suggested that we might need to import a newer # version of the schema. BASE157PS = tr.tr157_v1_3.InternetGatewayDevice_v1_7.PeriodicStatistics CALC_MODES = frozenset( ['Latest', 'Minimum', 'Maximum', 'Average']) SAMPLE_MODES = frozenset(['Current', 'Change']) def _MakeSampleSeconds(sample_times): """Helper to convert an array of time values to a tr157 string.""" deltas = [str(int(round(end - start))) for start, end in sample_times] return ','.join(deltas) class PeriodicStatistics(BASE157PS): """An implementation of tr157 PeriodicStatistics sampling.""" def __init__(self): BASE157PS.__init__(self) self._root = None self._cpe = None self.sample_sets = dict() self.SampleSetList = tr.core.AutoDict( 'PeriodicStatistics.SampleSetList', iteritems=self.IterSampleSets, getitem=self.GetSampleSet, setitem=self.SetSampleSet, delitem=self.DelSampleSet) def SetRoot(self, root): """Sets the root object. Args: root: The root of the tr hierarchy. This is needed to lookup objects that are being tracked. """ self._root = root def SetCpe(self, cpe): """Sets the cpe to use for scheduling polling events.""" self._cpe = cpe def StartTransaction(self): # TODO(jnewlin): Implement the transaction model for SetParameterValues pass def AbandonTransaction(self): pass def CommitTransaction(self): pass def IterSampleSets(self): return self.sample_sets.iteritems() def GetSampleSet(self, key): return self.sample_sets[key] def SetSampleSet(self, key, value): value.SetCpeAndRoot(self._cpe, self._root) self.sample_sets[key] = value def DelSampleSet(self, key): del self.sample_sets[key] @property def SampleSetNumberOfEntries(self): return len(self.sample_sets) @property def MaxReportSamples(self): """Maximum samples that can be collected in a report. Returns: A value of 0 in this case, indicates no specific maximum. """ return 0 @property def MinSampleInterval(self): """Minimum sampling interval, a value of 0 indicates no minimum.""" return 0 class SampleSet(BASE157PS.SampleSet): """Implementation of PeriodicStatistics.SampleSet.""" def __init__(self): BASE157PS.SampleSet.__init__(self) self.ParameterList = tr.core.AutoDict( 'ParameterList', iteritems=self.IterParameters, getitem=self.GetParameter, setitem=self.SetParameter, delitem=self.DelParameter) self.Unexport('ForceSample') self.Name = '' self.ParameterNumberOfEntries = 0 self._parameter_list = dict() self._sample_times = [] self._samples_collected = 0 self._sample_start_time = None self._attributes = dict() self._cpe = None self._root = None self._enable = False self._pending_timeout = None self._fetch_samples = 0 self._report_samples = 0 self._sample_interval = 0 self._time_reference = None def IterParameters(self): return self._parameter_list.iteritems() def GetParameter(self, key): return self._parameter_list[key] def SetParameter(self, key, value): self._parameter_list[key] = value value.SetParent(self) value.SetRoot(self._root) def DelParameter(self, key): del self._parameter_list[key] @property def TimeReference(self): # if _time_reference is None, this returns a CWMP # Unknown time. return tr.cwmpdate.format(self._time_reference) @TimeReference.setter def TimeReference(self, value): self.ClearSamplingData() if value == '0001-01-01T00:00:00Z': # CWMP Unknown time. self._time_reference = None else: self._time_reference = tr.cwmpdate.parse(value) @property def ReportStartTime(self): start_time = self._sample_times[0][0] if self._sample_times else None return tr.cwmpdate.format(start_time) @property def ReportEndTime(self): end_time = self._sample_times[-1][1] if self._sample_times else None return tr.cwmpdate.format(end_time) @property def Status(self): return 'Enabled' if self._enable else 'Disabled' @property def FetchSamples(self): return self._fetch_samples @FetchSamples.setter def FetchSamples(self, value): self._fetch_samples = int(value) @property def ReportSamples(self): return self._report_samples @ReportSamples.setter def ReportSamples(self, value): v = int(value) if v < 1: raise ValueError('ReportSamples must be >= 1') self._report_samples = v # Trim down samples self._sample_times = self._sample_times[-v:] for param in self._parameter_list.itervalues(): param.TrimSamples(v) self.UpdateSampling() @property def SampleInterval(self): return self._sample_interval @SampleInterval.setter def SampleInterval(self, value): v = int(value) if v < 1: raise ValueError('SampleInterval must be >= 1') self._sample_interval = v self.ClearSamplingData() self.UpdateSampling() def RemoveTimeout(self): """If there is a pending timeout, removes it.""" if self._pending_timeout: self._cpe.ioloop.remove_timeout(self._pending_timeout) self._pending_timeout = None def SetSampleTrigger(self, current_time=None): """Sets the timeout to collect the next sample.""" current_time = current_time if current_time else time.time() self.RemoveTimeout() self._sample_start_time = current_time time_to_sample = self.CalcTimeToNextSample(current_time) delta = datetime.timedelta(0, time_to_sample) self._pending_timeout = self._cpe.ioloop.add_timeout( delta, self.CollectSample) def StopSampling(self): """Disables the sampling, and if a sample is pending, cancels it.""" self.RemoveTimeout() def ClearSamplingData(self): """Clears out any old sampling data. Clears any old sampled data, so that a new sampling run can begin. Also clears all Parameter objects. """ self._sample_times = [] self._samples_collected = 0 for param in self._parameter_list.itervalues(): param.ClearSamplingData() def UpdateSampling(self): """This is called whenever some member is changed. Whenever a member, e.g. Enable is changed, call this to start the sampling process. """ if (self._enable and self._report_samples > 0 and self._sample_interval > 0): self.SetSampleTrigger() else: self.StopSampling() def CalcTimeToNextSample(self, current_time): """Return time until the next sample should be collected.""" # The simple case, if TimeReference is not set, the time till next # sample is simply the SampleInterval. if not self._time_reference: return max(1, self._sample_interval) # self._time_reference is a datetime object. time_ref = time.mktime(self._time_reference.timetuple()) delta_seconds = (current_time - time_ref) % self._sample_interval tts = int(round(self._sample_interval - delta_seconds)) return max(1, tts) def CollectSample(self, current_time=None): """Collects a sample for each of the Parameters. Iterate over all of the Parameter objects and collect samples for each of those. If this is the last sample, optionally signal back to the ACS that the sampling is finished. If another sample is required, setup a trigger to collect the next sample. TODO(jnewlin): Add code to trigger the ACS. Args: current_time: The current time, usually from time.time() """ self.RemoveTimeout() if not self._root or not self._cpe: return current_time = current_time if current_time else time.time() sample_start_time = self._sample_start_time if not sample_start_time: sample_start_time = current_time self._sample_start_time = None sample_end_time = current_time self._samples_collected += 1 self._sample_times.append((sample_start_time, sample_end_time)) # This will keep just the last ReportSamples worth of samples. self._sample_times = self._sample_times[-self._report_samples:] for key in self._parameter_list: self._parameter_list[key].CollectSample( start_time=sample_start_time, current_time=current_time) if self._enable: self.SetSampleTrigger(current_time) if self.FetchSamplesTriggered(): if self.PassiveNotification() or self.ActiveNotification(): param_name = self._root.GetCanonicalName(self) param_name += '.Status' self._cpe.SetNotificationParameters( [(param_name, 'Trigger')]) if self.ActiveNotification(): self._cpe.NewValueChangeSession() def FetchSamplesTriggered(self): """Check if FetchSamples would have triggered on this sample.""" if self._fetch_samples <= 0: return False samples_this_period = self._samples_collected % self._report_samples # I'm sure there's a better way to do this, I just can't think # of it. Want the repeating set of [1..N] not [0..N-1] if samples_this_period == 0: samples_this_period = self._report_samples return samples_this_period == self._fetch_samples def PassiveNotification(self): """Check if passive notification is enabled.""" if 'Notification' in self._attributes: val = self._attributes['Notification'] == 1 return val return False def ActiveNotification(self): """Check if active notification is enabled.""" if 'Notification' in self._attributes: val = self._attributes['Notification'] == 2 return val return False def SetCpeAndRoot(self, cpe, root): self._cpe = cpe self._root = root @property def Enable(self): return self._enable @Enable.setter def Enable(self, value): self._enable = tr.cwmpbool.parse(value) if self._enable: self.ClearSamplingData() self.UpdateSampling() @property def SampleSeconds(self): """A comma separarted string of unsigned integers.""" return _MakeSampleSeconds(self._sample_times) def SetAttribute(self, attr, value): """Sets an attribute on this object. Currently can be anything. NOTE(jnewlin): This should probably throw an exception for unsupported attributes and the list of attributes should come for the tr xml spec files somewhere, but it's not clear to me how to do this. Args: attr: the name of the attribute to set. value: the value of the attribute """ if attr == 'Notification': # Technically should not overwrite this unless we all see a # 'NotificationChange' with a value of true. Seems a bit retarded # though, why send a SetParametersAttribute with a new value but # NotificationChange set to False... self._attributes[attr] = int(value) elif attr == 'AccessList': self._attributes[attr] = value class Parameter(BASE157PS.SampleSet.Parameter): """Implementation of PeriodicStatistics.SampleSet.Parameter.""" def __init__(self): BASE157PS.SampleSet.Parameter.__init__(self) self._parent = None self._root = None self.Enable = False self.HighThreshold = 0 self.LowThreshold = 0 self.Reference = None self._calculation_mode = 'Latest' self._failures = 0 self._sample_mode = 'Current' self._sample_times = [] self._suspect_data = [] self._values = [] @property def CalculationMode(self): return self._calculation_mode @CalculationMode.setter def CalculationMode(self, value): if not value in CALC_MODES: raise ValueError('Bad value sent for CalculationMode.') self._calculation_mode = value @property def Failures(self): return self._failures @property def SampleMode(self): return self._sample_mode @SampleMode.setter def SampleMode(self, value): if value not in SAMPLE_MODES: raise ValueError('Bad value set for SampleMode: ' + str(value)) self._sample_mode = value @property def SampleSeconds(self): """Convert the stored time values to a SampleSeconds string.""" return _MakeSampleSeconds(self._sample_times) @property def SuspectData(self): return ','.join(self._suspect_data) @property def Values(self): return ','.join(self._values) def SetParent(self, parent): """Set the parent object (should be a SampleSet).""" self._parent = parent def SetRoot(self, root): """Sets the root of the hierarchy, needed for GetExport.""" self._root = root def CollectSample(self, start_time=None, current_time=None): """Collects one new sample point.""" current_time = current_time if current_time else time.time() start_time = start_time if start_time else current_time if not self.Enable: return try: # TODO(jnewlin): Update _suspect_data. current_value = self._root.GetExport(self.Reference) self._values.append(str(current_value)) self._sample_times.append((start_time, current_time)) except (KeyError, AttributeError, IndexError): pass finally: # This will keep just the last ReportSamples worth of samples. self.TrimSamples(self._parent.ReportSamples) def ClearSamplingData(self): """Throw away any sampled data.""" self._values = [] self._sample_times = [] def TrimSamples(self, length): """Trim any sampling data arrays to only keep the last N values.""" # Make sure some bogus value of length can't be passed in. if length <= 0: length = 1 self._sample_times = self._sample_times[-length:] self._values = self._values[-length:] def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of network device support used in a number of data models.""" __author__ = 'dgentry@google.com (Denton Gentry)' # Unit tests can override this. PROC_NET_DEV = '/proc/net/dev' class NetdevStatsLinux26(object): """Parses /proc/net/dev to populate Stats objects in several TRs.""" # Fields in /proc/net/dev _RX_BYTES = 0 _RX_PKTS = 1 _RX_ERRS = 2 _RX_DROP = 3 _RX_FIFO = 4 _RX_FRAME = 5 _RX_COMPRESSED = 6 _RX_MCAST = 7 _TX_BYTES = 8 _TX_PKTS = 9 _TX_DROP = 10 _TX_FIFO = 11 _TX_COLLISIONS = 12 _TX_CARRIER = 13 _TX_COMPRESSED = 14 def __init__(self, ifname): """Parse fields from a /proc/net/dev line. Args: ifname: string name of the interface, like "eth0" """ ifstats = self._ReadProcNetDev(ifname) if ifstats: self.BroadcastPacketsReceived = None self.BroadcastPacketsSent = None self.BytesReceived = ifstats[self._RX_BYTES] self.BytesSent = ifstats[self._TX_BYTES] self.DiscardPacketsReceived = ifstats[self._RX_DROP] self.DiscardPacketsSent = ifstats[self._TX_DROP] err = int(ifstats[self._RX_ERRS]) + int(ifstats[self._RX_FRAME]) self.ErrorsReceived = str(err) self.ErrorsSent = ifstats[self._TX_FIFO] self.MulticastPacketsReceived = ifstats[self._RX_MCAST] self.MulticastPacketsSent = None self.PacketsReceived = ifstats[self._RX_PKTS] self.PacketsSent = ifstats[self._TX_PKTS] rx = int(ifstats[self._RX_PKTS]) - int(ifstats[self._RX_MCAST]) self.UnicastPacketsReceived = str(rx) # Linux doesn't break out transmit uni/multi/broadcast, but we don't # want to return None for all of them. So we return all transmitted # packets as unicast, though some were surely multicast or broadcast. self.UnicastPacketsSent = ifstats[self._TX_PKTS] self.UnknownProtoPacketsReceived = None def _ReadProcNetDev(self, ifname): """Return the /proc/net/dev entry for ifname. Args: ifname: string name of the interface, ecx: "eth0" Returns: The /proc/net/dev entry for ifname as a list. """ f = open(PROC_NET_DEV) for line in f: fields = line.split(':') if (len(fields) == 2) and (fields[0].strip() == ifname): return fields[1].split() return None def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for igd_time.py implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import os import tempfile import unittest import google3 import igd_time def TimeNow(): return 1234567890.987654 class IgdTimeTest(unittest.TestCase): def setUp(self): self.old_TIMENOW = igd_time.TIMENOW igd_time.TIMENOW = TimeNow self.files_to_remove = list() def tearDown(self): igd_time.TIMENOW = self.old_TIMENOW for f in self.files_to_remove: os.remove(f) def MakeTestScript(self): """Create a unique file in /tmp.""" outfile = tempfile.NamedTemporaryFile(delete=False) self.files_to_remove.append(outfile.name) return outfile def testValidateExports(self): t = igd_time.TimeTZ() t.ValidateExports() def testCurrentLocalTime(self): t = igd_time.TimeTZ() self.assertEqual(t.CurrentLocalTime, '2009-02-13T23:31:30.987654Z') def testGetLocalTimeZoneName(self): t = igd_time.TimeTZ(tzfile='testdata/igd_time/TZ') self.assertEqual(t.LocalTimeZoneName, 'POSIX') def testSetLocalTimeZoneName(self): outfile = self.MakeTestScript() t = igd_time.TimeTZ(tzfile=outfile.name) expected = 'PST8PDT,M3.2.0/2,M11.1.0/2' t.StartTransaction() t.LocalTimeZoneName = expected t.CommitTransaction() self.assertEqual(outfile.read().strip(), expected) def testUCLibcIsReallyReallyReallyPickyAboutWhitespace(self): # uClibC will only accept a TZ file with exactly one newline at the end. tzwrite = 'PST8PDT,M3.2.0/2,M11.1.0/2' outfile = self.MakeTestScript() t = igd_time.TimeTZ(tzfile=outfile.name) t.StartTransaction() t.LocalTimeZoneName = tzwrite + '\n\n\n\n\n' t.CommitTransaction() self.assertEqual(outfile.read(), tzwrite + '\n') outfile = self.MakeTestScript() t = igd_time.TimeTZ(tzfile=outfile.name) t.StartTransaction() t.LocalTimeZoneName = tzwrite t.CommitTransaction() self.assertEqual(outfile.read(), tzwrite + '\n') def testAbandonTransaction(self): outfile = self.MakeTestScript() t = igd_time.TimeTZ(tzfile=outfile.name) t.StartTransaction() t.LocalTimeZoneName = 'This should not be written.' t.AbandonTransaction() self.assertEqual(outfile.read().strip(), '') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-140 Storage Services objects.""" __author__ = 'dgentry@google.com (Denton Gentry)' import ctypes import fcntl import os import os.path import re import subprocess import tr.core import tr.tr140_v1_1 import tr.x_catawampus_storage_1_0 BASESTORAGE = tr.x_catawampus_storage_1_0.X_CATAWAMPUS_ORG_Storage_v1_0.StorageService class MtdEccStats(ctypes.Structure): """<mtd/mtd-abi.h> struct mtd_ecc_stats.""" _fields_ = [('corrected', ctypes.c_uint32), ('failed', ctypes.c_uint32), ('badblocks', ctypes.c_uint32), ('bbtblocks', ctypes.c_uint32)] def _GetMtdStats(mtddev): """Return the MtdEccStats for the given mtd device. Arguments: mtddev: the string path to the device, ex: '/dev/mtd14' Raises: IOError: if the ioctl fails. Returns: an MtdEccStats. """ ECCGETSTATS = 0x40104d12 # ECCGETSTATS _IOR('M', 18, struct mtd_ecc_stats) with open(mtddev, 'r') as f: ecc = MtdEccStats() if fcntl.ioctl(f, ECCGETSTATS, ctypes.addressof(ecc)) != 0: raise IOError('ECCGETSTATS failed') return ecc # Unit tests can override these GETMTDSTATS = _GetMtdStats PROC_FILESYSTEMS = '/proc/filesystems' PROC_MOUNTS = '/proc/mounts' SLASHDEV = '/dev/' SMARTCTL = '/usr/sbin/smartctl' STATVFS = os.statvfs SYS_BLOCK = '/sys/block/' SYS_UBI = '/sys/class/ubi/' def _FsType(fstype): supported = {'vfat': 'FAT32', 'ext2': 'ext2', 'ext3': 'ext3', 'ext4': 'ext4', 'msdos': 'FAT32', 'xfs': 'xfs', 'reiserfs': 'REISER'} if fstype in supported: return supported[fstype] else: return 'X_CATAWAMPUS-ORG_' + fstype def _IsSillyFilesystem(fstype): """Filesystems which are not interesting to export to the ACS.""" SILLY = frozenset(['devtmpfs', 'proc', 'sysfs', 'usbfs', 'devpts', 'rpc_pipefs', 'autofs', 'nfsd', 'binfmt_misc', 'fuseblk']) return fstype in SILLY def _GetFieldFromOutput(prefix, output, default=''): """Search output for line of the form 'Foo: Bar', return 'Bar'.""" field_re = re.compile(prefix + '\s*(\S+)') for line in output.splitlines(): result = field_re.search(line) if result is not None: return result.group(1).strip() return default def _ReadOneLine(filename, default): """Read one line from a file. Return default if anything fails.""" try: f = open(filename, 'r') return f.readline().strip() except IOError: return default def IntFromFile(filename): """Read one line from a file and return an int, or zero if an error occurs.""" try: buf = _ReadOneLine(filename, '0') return int(buf) except ValueError: return 0 class LogicalVolumeLinux26(BASESTORAGE.LogicalVolume): """Implementation of tr-140 StorageService.LogicalVolume for Linux FS.""" def __init__(self, rootpath, fstype): BASESTORAGE.LogicalVolume.__init__(self) self.rootpath = rootpath self.fstype = fstype self.Unexport('Alias') self.Unexport('Encrypted') self.Unexport('ThresholdReached') self.Unexport('PhysicalReference') self.FolderList = {} self.ThresholdLimit = 0 @property def Name(self): return self.rootpath @property def Status(self): return 'Online' @property def Enable(self): return True @property def FileSystem(self): return self.fstype # TODO(dgentry) need @sessioncache decorator def _GetStatVfs(self): return STATVFS(self.rootpath) @property def Capacity(self): vfs = self._GetStatVfs() return int(vfs.f_blocks * vfs.f_bsize / 1024 / 1024) @property def ThresholdReached(self): vfs = self._GetStatVfs() require = self.ThresholdLimit * 1024 * 1024 avail = vfs.f_bavail * vfs.f_bsize return True if avail < require else False @property def UsedSpace(self): vfs = self._GetStatVfs() b_used = vfs.f_blocks - vfs.f_bavail return int(b_used * vfs.f_bsize / 1024 / 1024) @property def X_CATAWAMPUS_ORG_ReadOnly(self): ST_RDONLY = 0x0001 vfs = self._GetStatVfs() return True if vfs.f_flag & ST_RDONLY else False @property def FolderNumberOfEntries(self): return len(self.FolderList) class PhysicalMediumDiskLinux26(BASESTORAGE.PhysicalMedium): """tr-140 PhysicalMedium implementation for non-removable disks.""" CONNECTION_TYPES = frozenset( ['USB 1.1', 'USB 2.0', 'IEEE1394', 'IEEE1394b', 'IDE', 'EIDE', 'ATA/33', 'ATA/66', 'ATA/100', 'ATA/133', 'SATA/150', 'SATA/300', 'SCSI-1', 'Fast SCSI', 'Fast-Wide SCSI', 'Ultra SCSI', 'Ultra Wide SCSI', 'Ultra2 SCSI', 'Ultra2 Wide SCSI', 'Ultra3 SCSI', 'Ultra-320 SCSI', 'Ultra-640 SCSI', 'SSA', 'SSA-40', 'Fibre Channel']) def __init__(self, dev, conn_type=None): BASESTORAGE.PhysicalMedium.__init__(self) self.dev = dev self.name = dev self.Unexport('Alias') # TODO(dgentry) read SMART attribute for PowerOnHours self.Unexport('Uptime') # TODO(dgentry) What does 'Standby' or 'Offline' mean? self.Unexport('Status') if conn_type is None: # transport is really, really hard to infer programatically. # If platform code doesn't provide it, don't try to guess. self.Unexport('ConnectionType') else: # Provide a hint to the platform code: use a valid enumerated string, # or define a vendor extension. Don't just make something up. assert conn_type[0:1] == 'X_' or conn_type in self.CONNECTION_TYPES self.conn_type = conn_type # TODO(dgentry) need @sessioncache decorator def _GetSmartctlOutput(self): """Return smartctl info and health output.""" dev = SLASHDEV + self.dev smart = subprocess.Popen([SMARTCTL, '--info', '--health', dev], stdout=subprocess.PIPE) out, _ = smart.communicate(None) return out def GetName(self): return self.name def SetName(self, value): self.name = value Name = property(GetName, SetName, None, 'PhysicalMedium.Name') @property def Vendor(self): filename = SYS_BLOCK + '/' + self.dev + '/device/vendor' vendor = _ReadOneLine(filename=filename, default='') # /sys/block/?da/device/vendor is often 'ATA'. Not useful. return '' if vendor == 'ATA' else vendor @property def Model(self): filename = SYS_BLOCK + '/' + self.dev + '/device/model' return _ReadOneLine(filename=filename, default='') @property def SerialNumber(self): return _GetFieldFromOutput(prefix='Serial Number:', output=self._GetSmartctlOutput(), default='') @property def FirmwareVersion(self): return _GetFieldFromOutput(prefix='Firmware Version:', output=self._GetSmartctlOutput(), default='') @property def ConnectionType(self): return self.conn_type @property def Removable(self): return False @property def Capacity(self): """Return capacity in Megabytes.""" filename = SYS_BLOCK + '/' + self.dev + '/size' size = _ReadOneLine(filename=filename, default='0') try: # TODO(dgentry) Do 4k sector drives populate size in 512 byte blocks? return int(size) * 512 / 1048576 except ValueError: return 0 @property def SMARTCapable(self): capable = _GetFieldFromOutput(prefix='SMART support is: Enab', output=self._GetSmartctlOutput(), default=None) return True if capable else False @property def Health(self): health = _GetFieldFromOutput( prefix='SMART overall-health self-assessment test result:', output=self._GetSmartctlOutput(), default='') if health == 'PASSED': return 'OK' elif health.find('FAIL') >= 0: return 'Failing' else: return 'Error' @property def HotSwappable(self): filename = SYS_BLOCK + '/' + self.dev + '/removable' removable = _ReadOneLine(filename=filename, default='0').strip() return False if removable == '0' else True class FlashSubVolUbiLinux26(BASESTORAGE.X_CATAWAMPUS_ORG_FlashMedia.SubVolume): """Catawampus Storage Flash SubVolume implementation for UBI volumes.""" def __init__(self, ubivol): BASESTORAGE.X_CATAWAMPUS_ORG_FlashMedia.SubVolume.__init__(self) self.ubivol = ubivol @property def DataMBytes(self): bytesiz = IntFromFile(os.path.join(SYS_UBI, self.ubivol, 'data_bytes')) return int(bytesiz / 1024 / 1024) @property def Name(self): return _ReadOneLine(os.path.join(SYS_UBI, self.ubivol, 'name'), self.ubivol) @property def Status(self): corr = IntFromFile(os.path.join(SYS_UBI, self.ubivol, 'corrupted')) return 'OK' if corr == 0 else 'Corrupted' class FlashMediumUbiLinux26(BASESTORAGE.X_CATAWAMPUS_ORG_FlashMedia): """Catawampus Storage FlashMedium implementation for UBI volumes.""" def __init__(self, ubiname): BASESTORAGE.X_CATAWAMPUS_ORG_FlashMedia.__init__(self) self.ubiname = ubiname self.SubVolumeList = {} num = 0 for i in range(128): subvolname = ubiname + '_' + str(i) try: if os.stat(os.path.join(SYS_UBI, self.ubiname, subvolname)): self.SubVolumeList[str(num)] = FlashSubVolUbiLinux26(subvolname) num += 1 except OSError: pass @property def BadEraseBlocks(self): return IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'bad_peb_count')) @property def CorrectedErrors(self): mtdnum = IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'mtd_num')) ecc = GETMTDSTATS(os.path.join(SLASHDEV, 'mtd' + str(mtdnum))) return ecc.corrected @property def EraseBlockSize(self): return IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'eraseblock_size')) @property def IOSize(self): return IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'min_io_size')) @property def MaxEraseCount(self): return IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'max_ec')) @property def SubVolumeNumberOfEntries(self): return len(self.SubVolumeList) @property def Name(self): return self.ubiname @property def ReservedEraseBlocks(self): return IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'reserved_for_bad')) @property def TotalEraseBlocks(self): return IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'total_eraseblocks')) @property def UncorrectedErrors(self): mtdnum = IntFromFile(os.path.join(SYS_UBI, self.ubiname, 'mtd_num')) ecc = GETMTDSTATS(os.path.join(SLASHDEV, 'mtd' + str(mtdnum))) return ecc.failed class CapabilitiesNoneLinux26(BASESTORAGE.Capabilities): """Trivial tr-140 StorageService.Capabilities, all False.""" def __init__(self): BASESTORAGE.Capabilities.__init__(self) @property def FTPCapable(self): return False @property def HTTPCapable(self): return False @property def HTTPSCapable(self): return False @property def HTTPWritable(self): return False @property def SFTPCapable(self): return False @property def SupportedFileSystemTypes(self): """Returns possible filesystems. Parses /proc/filesystems, omit any defined as uninteresting in _IsSillyFileSystem(), and return the rest. Returns: a string of comma-separated filesystem types. """ fslist = set() f = open(PROC_FILESYSTEMS) for line in f: if line.find('nodev') >= 0: # rule of thumb to skip internal, non-interesting filesystems continue fstype = line.strip() if _IsSillyFilesystem(fstype): continue fslist.add(_FsType(fstype)) return ','.join(sorted(fslist, key=str.lower)) @property def SupportedNetworkProtocols(self): return '' @property def SupportedRaidTypes(self): return '' @property def VolumeEncryptionCapable(self): return False class StorageServiceLinux26(BASESTORAGE): """Implements a basic tr-140 for Linux 2.6-ish systems. This class implements no network file services, it only exports the LogicalVolume information. """ def __init__(self): BASESTORAGE.__init__(self) self.Capabilities = CapabilitiesNoneLinux26() self.Unexport('Alias') self.Unexport(objects='NetInfo') self.Unexport(objects='NetworkServer') self.Unexport(objects='FTPServer') self.Unexport(objects='SFTPServer') self.Unexport(objects='HTTPServer') self.Unexport(objects='HTTPSServer') self.PhysicalMediumList = {} self.StorageArrayList = {} self.LogicalVolumeList = tr.core.AutoDict( 'LogicalVolumeList', iteritems=self.IterLogicalVolumes, getitem=self.GetLogicalVolumeByIndex) self.UserAccountList = {} self.UserGroupList = {} self.X_CATAWAMPUS_ORG_FlashMediaList = {} @property def Enable(self): # TODO(dgentry): tr-140 says this is supposed to be writable return True @property def PhysicalMediumNumberOfEntries(self): return len(self.PhysicalMediumList) @property def StorageArrayNumberOfEntries(self): return len(self.StorageArrayList) @property def LogicalVolumeNumberOfEntries(self): return len(self.LogicalVolumeList) @property def UserAccountNumberOfEntries(self): return len(self.UserAccountList) @property def UserGroupNumberOfEntries(self): return len(self.UserGroupList) @property def X_CATAWAMPUS_ORG_FlashMediaNumberOfEntries(self): return len(self.X_CATAWAMPUS_ORG_FlashMediaList) def _ParseProcMounts(self): """Return list of (mount point, filesystem type) tuples.""" mounts = dict() try: f = open(PROC_MOUNTS) except IOError: return [] for line in f: fields = line.split() # ex: /dev/mtdblock9 / squashfs ro,relatime 0 0 if len(fields) < 6: continue fsname = fields[0] mountpoint = fields[1] fstype = fields[2] if fsname == 'none' or _IsSillyFilesystem(fstype): continue mounts[mountpoint] = _FsType(fstype) return sorted(mounts.items()) def GetLogicalVolume(self, fstuple): """Get an LogicalVolume object for a mounted filesystem.""" (mountpoint, fstype) = fstuple return LogicalVolumeLinux26(mountpoint, fstype) def IterLogicalVolumes(self): """Retrieves a list of all mounted filesystems.""" fstuples = self._ParseProcMounts() for idx, fstuple in enumerate(fstuples): yield idx, self.GetLogicalVolume(fstuple) def GetLogicalVolumeByIndex(self, index): fstuples = self._ParseProcMounts() if index >= len(fstuples): raise IndexError('No such object LogicalVolume.{0}'.format(index)) return self.GetLogicalVolume(fstuples[index]) def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for wifi.py implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import unittest import google3 import wifi class WifiTest(unittest.TestCase): def testContiguousRanges(self): self.assertEqual(wifi.ContiguousRanges([1, 2, 3, 4, 5]), '1-5') self.assertEqual(wifi.ContiguousRanges([1, 2, 3, 5]), '1-3,5') self.assertEqual(wifi.ContiguousRanges([1, 2, 3, 5, 6, 7]), '1-3,5-7') self.assertEqual(wifi.ContiguousRanges([1, 2, 3, 5, 7, 8, 9]), '1-3,5,7-9') self.assertEqual(wifi.ContiguousRanges([1, 3, 5, 7, 9]), '1,3,5,7,9') def testPreSharedKeyValidate(self): psk = wifi.PreSharedKey98() psk.ValidateExports() def testPBKDF2(self): psk = wifi.PreSharedKey98() # http://connect.microsoft.com/VisualStudio/feedback/details/95506/ psk.KeyPassphrase = 'ThisIsAPassword' key = psk.GetKey('ThisIsASSID') self.assertEqual( key, '0dc0d6eb90555ed6419756b9a15ec3e3209b63df707dd508d14581f8982721af') def testWEPKeyValidate(self): wk = wifi.WEPKey98() wk.ValidateExports() if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of the x-catawampus-org vendor data model.""" __author__ = 'dgentry@google.com (Denton Gentry)' import json import sys import google3 import tr.core import tr.x_catawampus_1_0 BASEDM = tr.x_catawampus_1_0.X_CATAWAMPUS_ORG_CATAWAMPUS_v1_0 #pylint: disable-msg=W0231 class CatawampusDm(BASEDM): """Implementation of x-catawampus-1.0. See tr/schema/x-catawampus.xml.""" def __init__(self): BASEDM.__init__(self) @property def RuntimeEnvInfo(self): """Return string of interesting settings from Python environment.""" python = dict() python['exec_prefix'] = sys.exec_prefix python['executable'] = sys.executable python['path'] = str(sys.path) python['platform'] = sys.platform python['prefix'] = sys.prefix python['version'] = sys.version env = dict() env['python'] = python return json.dumps(env) if __name__ == '__main__': sys.path.append('../') cm = CatawampusDm() print tr.core.Dump(cm)
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for tr-181 DeviceInfo implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import os import unittest import google3 import tr.core import device_info import tornado.testing class TestDeviceId(device_info.DeviceIdMeta): def Manufacturer(self): return 'Manufacturer' def ManufacturerOUI(self): return '000000' def ModelName(self): return 'ModelName' def Description(self): return 'Description' def SerialNumber(self): return '00000000' def HardwareVersion(self): return '0' def AdditionalHardwareVersion(self): return '0' def SoftwareVersion(self): return '0' def AdditionalSoftwareVersion(self): return '0' def ProductClass(self): return 'ProductClass' def ModemFirmwareVersion(self): return 'ModemFirmwareVersion' fake_periodics = [] class FakePeriodicCallback(object): def __init__(self, callback, callback_time, io_loop=None): self.callback = callback self.callback_time = callback_time self.io_loop = io_loop self.start_called = False self.stop_called = False fake_periodics.append(self) def start(self): self.start_called = True def stop(self): self.stop_called = True def FakeLedStatus(): return 'LEDSTATUS' class DeviceInfoTest(tornado.testing.AsyncTestCase): """Tests for device_info.py.""" def setUp(self): super(DeviceInfoTest, self).setUp() self.old_PERIODICCALL = device_info.PERIODICCALL self.old_PROC_MEMINFO = device_info.PROC_MEMINFO self.old_PROC_NET_DEV = device_info.PROC_NET_DEV self.old_PROC_UPTIME = device_info.PROC_UPTIME self.old_SLASH_PROC = device_info.SLASH_PROC device_info.PERIODICCALL = FakePeriodicCallback device_info.PROC_MEMINFO = 'testdata/device_info/meminfo' device_info.PROC_UPTIME = 'testdata/device_info/uptime' device_info.SLASH_PROC = 'testdata/device_info/processes' def tearDown(self): super(DeviceInfoTest, self).tearDown() device_info.PERIODICCALL = self.old_PERIODICCALL device_info.PROC_MEMINFO = self.old_PROC_MEMINFO device_info.PROC_NET_DEV = self.old_PROC_NET_DEV device_info.PROC_UPTIME = self.old_PROC_UPTIME device_info.SLASH_PROC = self.old_SLASH_PROC def testValidate181(self): di = device_info.DeviceInfo181Linux26(TestDeviceId()) di.ValidateExports() def testValidate98(self): di = device_info.DeviceInfo98Linux26(TestDeviceId()) di.ValidateExports() def testUptimeSuccess(self): device_info.PROC_UPTIME = 'testdata/device_info/uptime' di = device_info.DeviceInfo181Linux26(TestDeviceId()) self.assertEqual(di.UpTime, '123') def testDeviceId(self): did = TestDeviceId() di = device_info.DeviceInfo181Linux26(did) self.assertEqual(did.Manufacturer, di.Manufacturer) self.assertEqual(did.ManufacturerOUI, di.ManufacturerOUI) self.assertEqual(did.ModelName, di.ModelName) self.assertEqual(did.Description, di.Description) self.assertEqual(did.SerialNumber, di.SerialNumber) self.assertEqual(did.HardwareVersion, di.HardwareVersion) self.assertEqual(did.AdditionalHardwareVersion, di.AdditionalHardwareVersion) self.assertEqual(did.SoftwareVersion, di.SoftwareVersion) self.assertEqual(did.AdditionalSoftwareVersion, di.AdditionalSoftwareVersion) self.assertEqual(did.ProductClass, di.ProductClass) def testMemoryStatusSuccess(self): device_info.PROC_MEMINFO = 'testdata/device_info/meminfo' mi = device_info.MemoryStatusLinux26() self.assertEqual(mi.Total, 123456) self.assertEqual(mi.Free, 654321) def testMemoryStatusTotal(self): device_info.PROC_MEMINFO = 'testdata/device_info/meminfo_total' mi = device_info.MemoryStatusLinux26() self.assertEqual(mi.Total, 123456) self.assertEqual(mi.Free, 0) def testMemoryStatusFree(self): device_info.PROC_MEMINFO = 'testdata/device_info/meminfo_free' mi = device_info.MemoryStatusLinux26() self.assertEqual(mi.Total, 0) self.assertEqual(mi.Free, 654321) def testCPUUsage(self): ps = device_info.ProcessStatusLinux26(self.io_loop) self.assertEqual(len(fake_periodics), 1) self.assertTrue(fake_periodics[0].start_called) device_info.PROC_STAT = 'testdata/device_info/cpu/stat0' self.assertEqual(ps.CPUUsage, 0) fake_periodics[0].callback() # simulate periodic timer self.assertEqual(ps.CPUUsage, 0) device_info.PROC_STAT = 'testdata/device_info/cpu/stat' fake_periodics[0].callback() # simulate periodic timer self.assertEqual(ps.CPUUsage, 10) del fake_periodics[0] def testProcessStatusReal(self): ps = device_info.ProcessStatusLinux26(self.io_loop) # This fetches the processes running on the unit test machine. We can't # make many assertions about this, just that there should be some processes # running. processes = ps.ProcessList if os.path.exists('/proc/status'): # otherwise not a Linux machine self.assertTrue(processes) def testProcessStatusFakeData(self): Process = device_info.BASE181DEVICE.DeviceInfo.ProcessStatus.Process fake_processes = { 1: Process(PID=1, Command='init', Size=551, Priority=20, CPUTime=81970, State='Sleeping'), 3: Process(PID=3, Command='migration/0', Size=0, Priority=-100, CPUTime=591510, State='Stopped'), 5: Process(PID=5, Command='foobar', Size=0, Priority=-100, CPUTime=591510, State='Zombie'), 17: Process(PID=17, Command='bar', Size=0, Priority=-100, CPUTime=591510, State='Uninterruptible'), 164: Process(PID=164, Command='udevd', Size=288, Priority=16, CPUTime=300, State='Running'), 770: Process(PID=770, Command='automount', Size=6081, Priority=20, CPUTime=5515790, State='Uninterruptible') } device_info.SLASH_PROC = 'testdata/device_info/processes' ps = device_info.ProcessStatusLinux26(self.io_loop) processes = ps.ProcessList self.assertEqual(len(processes), 6) for p in processes.values(): fake_p = fake_processes[p.PID] self.assertEqual(tr.core.Dump(fake_p), tr.core.Dump(p)) def testProcessExited(self): device_info.SLASH_PROC = 'testdata/device_info/processes' ps = device_info.ProcessStatusLinux26(self.io_loop) proc = ps.GetProcess(1000) self.assertEqual(proc.PID, 1000); self.assertEqual(proc.Command, '<exited>'); self.assertEqual(proc.Size, 0); self.assertEqual(proc.Priority, 0); self.assertEqual(proc.CPUTime, 0); self.assertEqual(proc.State, 'X_CATAWAMPUS-ORG_Exited'); def testLedStatus(self): led = device_info.LedStatusReadFromFile( 'LED', 'testdata/device_info/ledstatus') led.ValidateExports() self.assertEqual(led.Name, 'LED') self.assertEqual(led.Status, 'LED_ON') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Fix sys.path so it can find our libraries. This file is named google3.py because gpylint specifically ignores it when complaining about the order of import statements - google3 should always come before other non-python-standard imports. """ __author__ = 'apenwarr@google.com (Avery Pennarun)' import os.path import sys mydir = os.path.dirname(__file__) sys.path += [ os.path.join(mydir, '..'), ] import tr.google3 #pylint: disable-msg=C6204,W0611
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-98/181 WLAN objects for Broadcom Wifi chipsets. The platform code is expected to set the BSSID (which is really a MAC address). The Wifi module should be populated with a MAC address. For example if it appears as eth2, then "ifconfig eth2" will show the MAC address from the Wifi card. The platform should execute: wl bssid xx:xx:xx:xx:xx:xx To set the bssid to the desired MAC address, either the one from the wifi card or your own. """ __author__ = 'dgentry@google.com (Denton Gentry)' import collections import copy import re import subprocess import time import tr.core import tr.cwmpbool import tr.tr098_v1_4 import netdev import wifi BASE98IGD = tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice BASE98WIFI = BASE98IGD.LANDevice.WLANConfiguration # Supported Encryption Modes EM_NONE = 0 EM_WEP = 1 EM_TKIP = 2 EM_AES = 4 EM_WSEC = 8 # Not enumerated in tr-98 EM_FIPS = 0x80 # Not enumerated in tr-98 EM_WAPI = 0x100 # Not enumerated in tr-98 # Unit tests can override these. WL_EXE = '/usr/bin/wl' WL_SLEEP = 3 # Broadcom recommendation for 3 second sleep before final join. # Broadcom recommendation for delay while scanning for a channel WL_AUTOCHAN_SLEEP = 2 # Parameter enumerations BEACONS = frozenset(['None', 'Basic', 'WPA', '11i', 'BasicandWPA', 'Basicand11i', 'WPAand11i', 'BasicandWPAand11i']) BASICENCRYPTIONS = frozenset(['None', 'WEPEncryption']) # We do not support EAPAuthentication BASICAUTHMODES = frozenset(['None', 'SharedAuthentication']) WPAAUTHMODES = frozenset(['PSKAuthentication']) def IsInteger(value): try: int(value) except: #pylint: disable-msg=W0702 return False return True class WifiConfig(object): """A dumb data object to store config settings.""" pass class Wl(object): """Class wrapping Broadcom's wl utility. This class implements low-level wifi handling, the stuff which tr-98 and tr-181 can both take advantage of. This object cannot retain any state about the Wifi configuration, as both tr-98 and tr-181 can have instances of this object. It has to consult the wl utility for all state information.""" def __init__(self, interface): self._if = interface def _SubprocessCall(self, cmd): subprocess.check_call([WL_EXE, '-i', self._if] + cmd) def _SubprocessWithOutput(self, cmd): wl = subprocess.Popen([WL_EXE, '-i', self._if] + cmd, stdout=subprocess.PIPE) out, _ = wl.communicate(None) return out def GetWlCounters(self): out = self._SubprocessWithOutput(['counters']) # match three different types of stat output: # rxuflo: 1 2 3 4 5 6 # rxfilter 1 # d11_txretrie st = re.compile('(\w+:?(?: \d+)*)') stats = st.findall(out) r1 = re.compile('(\w+): (.+)') r2 = re.compile('(\w+) (\d+)') r3 = re.compile('(\w+)') sdict = dict() for stat in stats: p1 = r1.match(stat) p2 = r2.match(stat) p3 = r3.match(stat) if p1 is not None: sdict[p1.group(1).lower()] = p1.group(2).split() elif p2 is not None: sdict[p2.group(1).lower()] = p2.group(2) elif p3 is not None: sdict[p3.group(1).lower()] = '0' return sdict def DoAutoChannelSelect(self): """Run the AP through an auto channel selection.""" # Make sure the interface is up, and ssid is the empty string. self._SubprocessCall(['down']) self._SubprocessCall(['spect', '0']) self._SubprocessCall(['mpc', '0']) self._SubprocessCall(['up']) self._SubprocessCall(['ssid', '']) time.sleep(WL_SLEEP) # This starts a scan, and we give it some time to complete. # TODO(jnewlin): Chat with broadcom about how long we need/should # wait before setting the autoscanned channel. self._SubprocessCall(['autochannel', '1']) time.sleep(WL_AUTOCHAN_SLEEP) # This programs the channel with the best channel found during the # scan. self._SubprocessCall(['autochannel', '2']) # Bring the interface back down and reset spect and mpc settings. # spect can't be changed for 0 -> 1 unless the interface is down. self._SubprocessCall(['down']) self._SubprocessCall(['spect', '1']) self._SubprocessCall(['mpc', '1']) def SetApMode(self): """Put device into AP mode.""" self._SubprocessCall(['ap', '1']) def GetAssociatedDevices(self): """Return a list of MAC addresses of associated STAs.""" out = self._SubprocessWithOutput(['assoclist']) stamac_re = re.compile('((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})') stations = list() for line in out.splitlines(): sta = stamac_re.search(line) if sta is not None: stations.append(sta.group(1)) return stations def GetAssociatedDevice(self, mac): """Return information about as associated STA. Args: mac: MAC address of the requested STA as a string, xx:xx:xx:xx:xx:xx Returns: An AssociatedDevice namedtuple. """ ad = collections.namedtuple( 'AssociatedDevice', ('AssociatedDeviceMACAddress ' 'AssociatedDeviceAuthenticationState ' 'LastDataTransmitRate')) ad.AssociatedDeviceMACAddress = mac ad.AssociatedDeviceAuthenticationState = False ad.LastDataTransmitRate = '0' out = self._SubprocessWithOutput(['sta_info', mac.upper()]) tx_re = re.compile('rate of last tx pkt: (\d+) kbps') for line in out.splitlines(): if line.find('AUTHENTICATED') >= 0: ad.AssociatedDeviceAuthenticationState = True tx_rate = tx_re.search(line) if tx_rate is not None: try: mbps = int(tx_rate.group(1)) / 1000 except ValueError: mbps = 0 ad.LastDataTransmitRate = str(mbps) return ad def GetAutoRateFallBackEnabled(self): """Return WLANConfiguration.AutoRateFallBackEnabled as a boolean.""" out = self._SubprocessWithOutput(['interference']) mode_re = re.compile('\(mode (\d)\)') result = mode_re.search(out) mode = -1 if result is not None: mode = int(result.group(1)) return True if mode == 3 or mode == 4 else False def SetAutoRateFallBackEnabled(self, value): """Set WLANConfiguration.AutoRateFallBackEnabled, expects a boolean.""" interference = 4 if value else 3 self._SubprocessCall(['interference', str(interference)]) def GetBasicDataTransmitRates(self): out = self._SubprocessWithOutput(['rateset']) basic_re = re.compile('([0123456789]+(?:\.[0123456789]+)?)\(b\)') return ','.join(basic_re.findall(out)) def GetBSSID(self): out = self._SubprocessWithOutput(['bssid']) bssid_re = re.compile('((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})') for line in out.splitlines(): bssid = bssid_re.match(line) if bssid is not None: return bssid.group(1) return '00:00:00:00:00:00' def SetBSSID(self, value): self._SubprocessCall(['bssid', value]) def ValidateBSSID(self, value): lower = value.lower() if lower == '00:00:00:00:00:00' or lower == 'ff:ff:ff:ff:ff:ff': return False bssid_re = re.compile('((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})') if bssid_re.search(value) is None: return False return True def GetBssStatus(self): out = self._SubprocessWithOutput(['bss']) lower = out.strip().lower() if lower == 'up': return 'Up' elif lower == 'down': return 'Disabled' else: return 'Error' def SetBssStatus(self, enable): status = 'up' if enable else 'down' self._SubprocessCall(['bss', status]) def GetChannel(self): out = self._SubprocessWithOutput(['channel']) chan_re = re.compile('current mac channel(?:\s+)(\d+)') for line in out.splitlines(): mr = chan_re.match(line) if mr is not None: return int(mr.group(1)) return 0 def SetChannel(self, value): self._SubprocessCall(['channel', value]) def ValidateChannel(self, value): if not IsInteger(value): return False iv = int(value) if iv in range(1, 14): return True # 2.4 GHz. US allows 1-11, Japan allows 1-13. if iv in range(36, 144, 4): return True # 5 GHz lower bands if iv in range(149, 169, 4): return True # 5 GHz upper bands return False def EM_StringToBitmap(self, enum): wsec = {'X_CATAWAMPUS-ORG_None': EM_NONE, 'None': EM_NONE, 'WEPEncryption': EM_WEP, 'TKIPEncryption': EM_TKIP, 'WEPandTKIPEncryption': EM_WEP | EM_TKIP, 'AESEncryption': EM_AES, 'WEPandAESEncryption': EM_WEP | EM_AES, 'TKIPandAESEncryption': EM_TKIP | EM_AES, 'WEPandTKIPandAESEncryption': EM_WEP | EM_TKIP | EM_AES} return wsec.get(enum, EM_NONE) def EM_BitmapToString(self, bitmap): bmap = {EM_NONE: 'X_CATAWAMPUS-ORG_None', EM_WEP: 'WEPEncryption', EM_TKIP: 'TKIPEncryption', EM_WEP | EM_TKIP: 'WEPandTKIPEncryption', EM_AES: 'AESEncryption', EM_WEP | EM_AES: 'WEPandAESEncryption', EM_TKIP | EM_AES: 'TKIPandAESEncryption', EM_WEP | EM_TKIP | EM_AES: 'WEPandTKIPandAESEncryption'} return bmap.get(bitmap) def GetEncryptionModes(self): out = self._SubprocessWithOutput(['wsec']) try: w = int(out.strip()) & 0x7 return self.EM_BitmapToString(w) except ValueError: return 'X_CATAWAMPUS-ORG_None' def SetEncryptionModes(self, value): self._SubprocessCall(['wsec', str(value)]) def ValidateEncryptionModes(self, value): ENCRYPTTYPES = frozenset(['X_CATAWAMPUS-ORG_None', 'None', 'WEPEncryption', 'TKIPEncryption', 'WEPandTKIPEncryption', 'AESEncryption', 'WEPandAESEncryption', 'TKIPandAESEncryption', 'WEPandTKIPandAESEncryption']) return True if value in ENCRYPTTYPES else False def SetJoin(self, ssid, amode): self._SubprocessCall(['join', str(ssid), 'imode', 'bss', 'amode', str(amode)]) def GetOperationalDataTransmitRates(self): out = self._SubprocessWithOutput(['rateset']) oper_re = re.compile('([0123456789]+(?:\.[0123456789]+)?)') if out: line1 = out.splitlines()[0] else: line1 = '' return ','.join(oper_re.findall(line1)) def SetPMK(self, value): self._SubprocessCall(['set_pmk', value]) def GetPossibleChannels(self): out = self._SubprocessWithOutput(['channels']) if out: channels = [int(x) for x in out.split()] return wifi.ContiguousRanges(channels) else: return '' def GetRadioEnabled(self): out = self._SubprocessWithOutput(['radio']) # This may look backwards, but I assure you it is correct. If the # radio is off, 'wl radio' returns 0x0001. try: return False if int(out.strip(), 0) == 1 else True except ValueError: return False def SetRadioEnabled(self, value): radio = 'on' if value else 'off' self._SubprocessCall(['radio', radio]) def GetRegulatoryDomain(self): out = self._SubprocessWithOutput(['country']) fields = out.split() if fields: return fields[0] else: return '' def SetRegulatoryDomain(self, value): self._SubprocessCall(['country', value]) def ValidateRegulatoryDomain(self, value): out = self._SubprocessWithOutput(['country', 'list']) countries = set() for line in out.splitlines(): fields = line.split(' ') if len(fields) and len(fields[0]) == 2: countries.add(fields[0]) return True if value in countries else False def SetReset(self, do_reset): status = 'down' if do_reset else 'up' self._SubprocessCall([status]) def GetSSID(self): """Return current Wifi SSID.""" out = self._SubprocessWithOutput(['ssid']) ssid_re = re.compile('Current SSID: "(.*)"') for line in out.splitlines(): ssid = ssid_re.match(line) if ssid is not None: return ssid.group(1) return '' def SetSSID(self, value, cfgnum=None): self._SubprocessCall(['up']) if cfgnum is not None: self._SubprocessCall(['ssid', '-C', str(cfgnum), value]) else: self._SubprocessCall(['ssid', value]) def ValidateSSID(self, value): if len(value) > 32: return False return True def GetSSIDAdvertisementEnabled(self): out = self._SubprocessWithOutput(['closed']) return True if out.strip() == '0' else False def SetSSIDAdvertisementEnabled(self, value): closed = '0' if value else '1' self._SubprocessCall(['closed', closed]) def SetSupWpa(self, value): sup_wpa = '1' if value else '0' self._SubprocessCall(['sup_wpa', sup_wpa]) def GetTransmitPower(self): out = self._SubprocessWithOutput(['pwr_percent']) return out.strip() def SetTransmitPower(self, value): self._SubprocessCall(['pwr_percent', value]) def ValidateTransmitPower(self, value): if not IsInteger(value): return False percent = int(value) if percent < 0 or percent > 100: return False return True def GetTransmitPowerSupported(self): # tr-98 describes this as a comma separated list, limited to string(64) # clearly it is expected to be a small number of discrete steps. # This chipset appears to have no such restriction. Hope a range is ok. return '1-100' def SetWepKey(self, index, key, mac=None): wl_cmd = ['addwep', str(index), key] if mac is not None: wl_cmd.append(str(mac)) self._SubprocessCall(wl_cmd) def ClrWepKey(self, index): self._SubprocessCall(['rmwep', str(index)]) def SetWepKeyIndex(self, index): # We do not use check_call here because primary_key fails if no WEP # keys have been configured, but we keep the code simple to always set it. subprocess.call([WL_EXE, '-i', self._if, 'primary_key', str(index)]) def SetWepStatus(self, enable): status = 'on' if enable else 'off' self._SubprocessCall(['wepstatus', status]) def GetWpaAuth(self): return self._SubprocessWithOutput(['wpa_auth']) def SetWpaAuth(self, value): self._SubprocessCall(['wpa_auth', str(value)]) class BrcmWifiWlanConfiguration(BASE98WIFI): """An implementation of tr98 WLANConfiguration for Broadcom Wifi chipsets.""" def __init__(self, ifname): BASE98WIFI.__init__(self) self._ifname = ifname self.wl = Wl(ifname) # Unimplemented, but not yet evaluated self.Unexport('Alias') self.Unexport('BeaconAdvertisementEnabled') self.Unexport('ChannelsInUse') self.Unexport('MaxBitRate') self.Unexport('PossibleDataTransmitRates') self.Unexport('TotalIntegrityFailures') self.Unexport('TotalPSKFailures') self.AssociatedDeviceList = tr.core.AutoDict( 'AssociatedDeviceList', iteritems=self.IterAssociations, getitem=self.GetAssociationByIndex) self.PreSharedKeyList = {} for i in range(1, 2): # tr-98 spec deviation: spec says 10 PreSharedKeys objects, # BRCM only supports one. self.PreSharedKeyList[i] = wifi.PreSharedKey98() self.WEPKeyList = {} for i in range(1, 5): self.WEPKeyList[i] = wifi.WEPKey98() self.LocationDescription = '' # No RADIUS support, could be added later. self.Unexport('AuthenticationServiceMode') # Local settings, currently unimplemented. Will require more # coordination with the underlying platform support. self.Unexport('InsecureOOBAccessEnabled') # MAC Access controls, currently unimplemented but could be supported. self.Unexport('MACAddressControlEnabled') # Wifi Protected Setup, currently unimplemented and not recommended. self.Unexport(objects='WPS') # Wifi MultiMedia, currently unimplemented but could be supported. # "wl wme_*" commands self.Unexport(lists='APWMMParameter') self.Unexport(lists='STAWMMParameter') self.Unexport('UAPSDEnable') self.Unexport('WMMEnable') # WDS, currently unimplemented but could be supported at some point. self.Unexport('PeerBSSID') self.Unexport('DistanceFromRoot') self.config = self._GetDefaultSettings() self.old_config = None def _GetDefaultSettings(self): obj = WifiConfig() obj.p_auto_channel_enable = True obj.p_auto_rate_fallback_enabled = None obj.p_basic_authentication_mode = 'None' obj.p_basic_encryption_modes = 'WEPEncryption' obj.p_beacon_type = 'WPAand11i' obj.p_bssid = None obj.p_channel = None obj.p_enable = False obj.p_ieee11i_authentication_mode = 'PSKAuthentication' obj.p_ieee11i_encryption_modes = 'X_CATAWAMPUS-ORG_None' obj.p_radio_enabled = True obj.p_regulatory_domain = None obj.p_ssid = None obj.p_ssid_advertisement_enabled = None obj.p_transmit_power = None obj.p_wepkeyindex = 1 obj.p_wpa_authentication_mode = 'PSKAuthentication' obj.p_wpa_encryption_modes = 'X_CATAWAMPUS-ORG_None' return obj def StartTransaction(self): config = self.config self.config = copy.copy(config) self.old_config = config def AbandonTransaction(self): self.config = self.old_config self.old_config = None def CommitTransaction(self): self.old_config = None self._ConfigureBrcmWifi() @property def Name(self): return self._ifname @property # TODO(dgentry) need @sessioncache decorator. def Stats(self): return BrcmWlanConfigurationStats(self._ifname) @property def Standard(self): return 'n' @property def DeviceOperationMode(self): return 'InfrastructureAccessPoint' @property def UAPSDSupported(self): return False @property def WEPEncryptionLevel(self): return 'Disabled,40-bit,104-bit' @property def WMMSupported(self): return False @property def TotalAssociations(self): return len(self.AssociatedDeviceList) def GetAutoRateFallBackEnabled(self): return self.wl.GetAutoRateFallBackEnabled() def SetAutoRateFallBackEnabled(self, value): self.config.p_auto_rate_fallback_enabled = tr.cwmpbool.parse(value) AutoRateFallBackEnabled = property( GetAutoRateFallBackEnabled, SetAutoRateFallBackEnabled, None, 'WLANConfiguration.AutoRateFallBackEnabled') def GetBasicAuthenticationMode(self): return self.config.p_basic_authentication_mode def SetBasicAuthenticationMode(self, value): if not value in BASICAUTHMODES: raise ValueError('Unsupported BasicAuthenticationMode %s' % value) self.config.p_basic_authentication_mode = value BasicAuthenticationMode = property( GetBasicAuthenticationMode, SetBasicAuthenticationMode, None, 'WLANConfiguration.BasicAuthenticationMode') def GetBasicDataTransmitRates(self): return self.wl.GetBasicDataTransmitRates() # TODO(dgentry) implement SetBasicDataTransmitRates BasicDataTransmitRates = property( GetBasicDataTransmitRates, None, None, 'WLANConfiguration.BasicDataTransmitRates') def GetBasicEncryptionModes(self): return self.config.p_basic_encryption_modes def SetBasicEncryptionModes(self, value): if value not in BASICENCRYPTIONS: raise ValueError('Unsupported BasicEncryptionMode: %s' % value) self.config.p_basic_encryption_modes = value BasicEncryptionModes = property(GetBasicEncryptionModes, SetBasicEncryptionModes, None, 'WLANConfiguration.BasicEncryptionModes') def GetBeaconType(self): return self.config.p_beacon_type def SetBeaconType(self, value): if value not in BEACONS: raise ValueError('Unsupported BeaconType: %s' % value) self.config.p_beacon_type = value BeaconType = property(GetBeaconType, SetBeaconType, None, 'WLANConfiguration.BeaconType') def GetBSSID(self): return self.wl.GetBSSID() def SetBSSID(self, value): if not self.wl.ValidateBSSID(value): raise ValueError('Invalid BSSID: %s' % value) self.config.p_bssid = value BSSID = property(GetBSSID, SetBSSID, None, 'WLANConfiguration.BSSID') def GetChannel(self): return self.wl.GetChannel() def SetChannel(self, value): if not self.wl.ValidateChannel(value): raise ValueError('Invalid Channel: %s' % value) self.config.p_channel = value self.config.p_auto_channel_enable = False Channel = property(GetChannel, SetChannel, None, 'WLANConfiguration.Channel') def GetEnable(self): return self.config.p_enable def SetEnable(self, value): self.config.p_enable = tr.cwmpbool.parse(value) Enable = property(GetEnable, SetEnable, None, 'WLANConfiguration.Enable') def GetIEEE11iAuthenticationMode(self): auth = self.wl.GetWpaAuth().split() eap = True if 'WPA2-802.1x' in auth else False psk = True if 'WPA2-PSK' in auth else False if eap and psk: return 'EAPandPSKAuthentication' elif eap: return 'EAPAuthentication' else: return 'PSKAuthentication' def SetIEEE11iAuthenticationMode(self, value): if not value in WPAAUTHMODES: raise ValueError('Unsupported IEEE11iAuthenticationMode %s' % value) self.config.p_ieee11i_authentication_mode = value IEEE11iAuthenticationMode = property( GetIEEE11iAuthenticationMode, SetIEEE11iAuthenticationMode, None, 'WLANConfiguration.IEEE11iAuthenticationMode') def GetIEEE11iEncryptionModes(self): return self.wl.GetEncryptionModes() def SetIEEE11iEncryptionModes(self, value): if not self.wl.ValidateEncryptionModes(value): raise ValueError('Invalid IEEE11iEncryptionMode: %s' % value) self.config.p_ieee11i_encryption_modes = value IEEE11iEncryptionModes = property( GetIEEE11iEncryptionModes, SetIEEE11iEncryptionModes, None, 'WLANConfiguration.IEEE11iEncryptionModes') def GetKeyPassphrase(self): psk = self.PreSharedKeyList[1] return psk.KeyPassphrase def SetKeyPassphrase(self, value): psk = self.PreSharedKeyList[1] psk.KeyPassphrase = value # TODO(dgentry) need to set WEPKeys, but this is fraught with peril. # If KeyPassphrase is not exactly 5 or 13 bytes it must be padded. # Apple uses different padding than Windows (and others). # http://support.apple.com/kb/HT1344 KeyPassphrase = property(GetKeyPassphrase, SetKeyPassphrase, None, 'WLANConfiguration.KeyPassphrase') def GetOperationalDataTransmitRates(self): return self.wl.GetOperationalDataTransmitRates() # TODO(dgentry) - need to implement SetOperationalDataTransmitRates OperationalDataTransmitRates = property( GetOperationalDataTransmitRates, None, None, 'WLANConfiguration.OperationalDataTransmitRates') def GetPossibleChannels(self): return self.wl.GetPossibleChannels() PossibleChannels = property(GetPossibleChannels, None, None, 'WLANConfiguration.PossibleChannels') def GetRadioEnabled(self): return self.wl.GetRadioEnabled() def SetRadioEnabled(self, value): self.config.p_radio_enabled = tr.cwmpbool.parse(value) RadioEnabled = property(GetRadioEnabled, SetRadioEnabled, None, 'WLANConfiguration.RadioEnabled') def GetRegulatoryDomain(self): return self.wl.GetRegulatoryDomain() def SetRegulatoryDomain(self, value): if not self.wl.ValidateRegulatoryDomain(value): raise ValueError('Unknown RegulatoryDomain: %s' % value) self.config.p_regulatory_domain = value RegulatoryDomain = property(GetRegulatoryDomain, SetRegulatoryDomain, None, 'WLANConfiguration.RegulatoryDomain') def GetAutoChannelEnable(self): return self.config.p_auto_channel_enable def SetAutoChannelEnable(self, value): self.config.p_auto_channel_enable = tr.cwmpbool.parse(value) AutoChannelEnable = property(GetAutoChannelEnable, SetAutoChannelEnable, None, 'WLANConfiguration.AutoChannelEnable') def GetSSID(self): return self.wl.GetSSID() def SetSSID(self, value): if not self.wl.ValidateSSID(value): raise ValueError('Invalid SSID: %s' % value) self.config.p_ssid = value SSID = property(GetSSID, SetSSID, None, 'WLANConfiguration.SSID') def GetSSIDAdvertisementEnabled(self): return self.wl.GetSSIDAdvertisementEnabled() def SetSSIDAdvertisementEnabled(self, value): self.config.p_ssid_advertisement_enabled = tr.cwmpbool.parse(value) SSIDAdvertisementEnabled = property( GetSSIDAdvertisementEnabled, SetSSIDAdvertisementEnabled, None, 'WLANConfiguration.SSIDAdvertisementEnabled') def GetBssStatus(self): return self.wl.GetBssStatus() Status = property(GetBssStatus, None, None, 'WLANConfiguration.Status') def GetTransmitPower(self): return self.wl.GetTransmitPower() def SetTransmitPower(self, value): if not self.wl.ValidateTransmitPower(value): raise ValueError('Invalid TransmitPower: %s' % value) self.config.p_transmit_power = value TransmitPower = property(GetTransmitPower, SetTransmitPower, None, 'WLANConfiguration.TransmitPower') def GetTransmitPowerSupported(self): return self.wl.GetTransmitPowerSupported() TransmitPowerSupported = property(GetTransmitPowerSupported, None, None, 'WLANConfiguration.TransmitPowerSupported') def GetWEPKeyIndex(self): return self.config.p_wepkeyindex def SetWEPKeyIndex(self, value): self.config.p_wepkeyindex = int(value) WEPKeyIndex = property(GetWEPKeyIndex, SetWEPKeyIndex, None, 'WLANConfiguration.WEPKeyIndex') def GetWPAAuthenticationMode(self): auth = self.wl.GetWpaAuth().split() psk = True if 'WPA-PSK' in auth else False eap = True if 'WPA-802.1x' in auth else False if eap: return 'EAPAuthentication' else: return 'PSKAuthentication' def SetWPAAuthenticationMode(self, value): if not value in WPAAUTHMODES: raise ValueError('Unsupported WPAAuthenticationMode %s' % value) self.config.p_wpa_authentication_mode = value WPAAuthenticationMode = property( GetWPAAuthenticationMode, SetWPAAuthenticationMode, None, 'WLANConfiguration.WPAAuthenticationMode') def GetEncryptionModes(self): return self.wl.GetEncryptionModes() def SetWPAEncryptionModes(self, value): if not self.wl.ValidateEncryptionModes(value): raise ValueError('Invalid WPAEncryptionMode: %s' % value) self.config.p_wpa_encryption_modes = value WPAEncryptionModes = property(GetEncryptionModes, SetWPAEncryptionModes, None, 'WLANConfiguration.WPAEncryptionModes') def _ConfigureBrcmWifi(self): """Issue commands to the wifi device to configure it. The Wifi driver is somewhat picky about the order of the commands. For example, some settings can only be changed while the radio is on. Make sure any changes made in this routine work in a real system, unit tests do not (and realistically, cannot) model all behaviors of the real wl utility. """ if not self.config.p_enable or not self.config.p_radio_enabled: self.wl.SetRadioEnabled(False) return self.wl.SetRadioEnabled(True) self.wl.SetApMode() if self.config.p_auto_channel_enable: self.wl.DoAutoChannelSelect() self.wl.SetBssStatus(False) if self.config.p_auto_rate_fallback_enabled is not None: self.wl.SetAutoRateFallBackEnabled( self.config.p_auto_rate_fallback_enabled) if self.config.p_bssid is not None: self.wl.SetBSSID(self.config.p_bssid) if self.config.p_channel is not None: self.wl.SetChannel(self.config.p_channel) if self.config.p_regulatory_domain is not None: self.wl.SetRegulatoryDomain(self.config.p_regulatory_domain) if self.config.p_ssid_advertisement_enabled is not None: self.wl.SetSSIDAdvertisementEnabled( self.config.p_ssid_advertisement_enabled) if self.config.p_transmit_power is not None: self.wl.SetTransmitPower(self.config.p_transmit_power) # sup_wpa should only be set WPA/WPA2 modes, not for Basic. sup_wpa = False amode = 0 if self.config.p_beacon_type.find('11i') >= 0: crypto = self.wl.EM_StringToBitmap(self.config.p_ieee11i_encryption_modes) if crypto != EM_NONE: amode = 128 sup_wpa = True elif self.config.p_beacon_type.find('WPA') >= 0: crypto = self.wl.EM_StringToBitmap(self.config.p_wpa_encryption_modes) if crypto != EM_NONE: amode = 4 sup_wpa = True elif self.config.p_beacon_type.find('Basic') >= 0: crypto = self.wl.EM_StringToBitmap(self.config.p_basic_encryption_modes) else: crypto = EM_NONE self.wl.SetEncryptionModes(crypto) self.wl.SetSupWpa(sup_wpa) self.wl.SetWpaAuth(amode) for idx, psk in self.PreSharedKeyList.items(): key = psk.GetKey(self.config.p_ssid) if key: self.wl.SetPMK(key) if self.config.p_ssid is not None: time.sleep(WL_SLEEP) self.wl.SetSSID(self.config.p_ssid) # Setting WEP key has to come after setting SSID. (Doesn't make sense # to me, it just doesn't work if you do it before setting SSID.) for idx, wep in self.WEPKeyList.items(): key = wep.WEPKey if key is None: self.wl.ClrWepKey(idx-1) else: self.wl.SetWepKey(idx-1, key) self.wl.SetWepKeyIndex(self.config.p_wepkeyindex) def GetTotalBytesReceived(self): # TODO(dgentry) cache for lifetime of session counters = self.wl.GetWlCounters() return int(counters.get('rxbyte', 0)) TotalBytesReceived = property(GetTotalBytesReceived, None, None, 'WLANConfiguration.TotalBytesReceived') def GetTotalBytesSent(self): counters = self.wl.GetWlCounters() return int(counters.get('txbyte', 0)) TotalBytesSent = property(GetTotalBytesSent, None, None, 'WLANConfiguration.TotalBytesSent') def GetTotalPacketsReceived(self): counters = self.wl.GetWlCounters() return int(counters.get('rxframe', 0)) TotalPacketsReceived = property(GetTotalPacketsReceived, None, None, 'WLANConfiguration.TotalPacketsReceived') def GetTotalPacketsSent(self): counters = self.wl.GetWlCounters() return int(counters.get('txframe', 0)) TotalPacketsSent = property(GetTotalPacketsSent, None, None, 'WLANConfiguration.TotalPacketsSent') def GetAssociation(self, mac): """Get an AssociatedDevice object for the given STA.""" ad = BrcmWlanAssociatedDevice(self.wl.GetAssociatedDevice(mac)) if ad: ad.ValidateExports() return ad def IterAssociations(self): """Retrieves a list of all associated STAs.""" stations = self.wl.GetAssociatedDevices() for idx, mac in enumerate(stations): yield idx, self.GetAssociation(mac) def GetAssociationByIndex(self, index): stations = self.wl.GetAssociatedDevices() return self.GetAssociation(stations[index]) class BrcmWlanConfigurationStats(netdev.NetdevStatsLinux26, BASE98WIFI.Stats): """tr98 InternetGatewayDevice.LANDevice.WLANConfiguration.Stats.""" def __init__(self, ifname): netdev.NetdevStatsLinux26.__init__(self, ifname) BASE98WIFI.Stats.__init__(self) class BrcmWlanAssociatedDevice(BASE98WIFI.AssociatedDevice): """Implementation of tr98 AssociatedDevice for Broadcom Wifi chipsets.""" def __init__(self, device): BASE98WIFI.AssociatedDevice.__init__(self) self._device = device self.Unexport('AssociatedDeviceIPAddress') self.Unexport('LastPMKId') self.Unexport('LastRequestedUnicastCipher') self.Unexport('LastRequestedMulticastCipher') def __getattr__(self, name): if hasattr(self._device, name): return getattr(self._device, name) else: raise AttributeError def main(): print tr.core.DumpSchema(BrcmWifiWlanConfiguration) if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-181 Device.DeviceInfo object. Handles the Device.DeviceInfo portion of TR-181, as described by http://www.broadband-forum.org/cwmp/tr-181-2-2-0.html """ __author__ = 'dgentry@google.com (Denton Gentry)' import abc import glob import os import tornado.ioloop import temperature import tr.core import tr.tr098_v1_4 import tr.tr181_v2_2 BASE98IGD = tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice BASE181DEVICE = tr.tr181_v2_2.Device_v2_2 CATA181DEVICE = tr.x_catawampus_tr181_2_0.X_CATAWAMPUS_ORG_Device_v2_0 # Unit tests can override these with fake data PERIODICCALL = tornado.ioloop.PeriodicCallback PROC_MEMINFO = '/proc/meminfo' PROC_NET_DEV = '/proc/net/dev' PROC_UPTIME = '/proc/uptime' PROC_STAT = '/proc/stat' SLASH_PROC = '/proc' class DeviceIdMeta(object): """Class to provide platform-specific fields for DeviceInfo. Each platform is expected to subclass DeviceIdMeta and supply concrete implementations of all methods. We use a Python Abstract Base Class to protect against future versions. If we add fields to this class, any existing platform implementations will be prompted to add implementations (because they will fail to startup when their DeviceId fails to instantiate. """ __metaclass__ = abc.ABCMeta @abc.abstractproperty def Manufacturer(self): return None @abc.abstractproperty def ManufacturerOUI(self): return None @abc.abstractproperty def ModelName(self): return None @abc.abstractproperty def Description(self): return None @abc.abstractproperty def SerialNumber(self): return None @abc.abstractproperty def HardwareVersion(self): return None @abc.abstractproperty def AdditionalHardwareVersion(self): return None @abc.abstractproperty def SoftwareVersion(self): return None @abc.abstractproperty def AdditionalSoftwareVersion(self): return None @abc.abstractproperty def ProductClass(self): return None @abc.abstractproperty def ModemFirmwareVersion(self): return None def _GetUptime(): """Return a string of the number of integer seconds since boot.""" uptime = float(open(PROC_UPTIME).read().split()[0]) return str(int(uptime)) #pylint: disable-msg=W0231 class DeviceInfo181Linux26(CATA181DEVICE.DeviceInfo): """Implements tr-181 DeviceInfo for Linux 2.6 and similar systems.""" def __init__(self, device_id, ioloop=None): super(DeviceInfo181Linux26, self).__init__() assert isinstance(device_id, DeviceIdMeta) self.ioloop = ioloop or tornado.ioloop.IOLoop.instance() self._device_id = device_id self.MemoryStatus = MemoryStatusLinux26() self.ProcessStatus = ProcessStatusLinux26(ioloop=ioloop) self.Unexport('FirstUseDate') self.Unexport(lists='Location') self.Unexport(objects='NetworkProperties') self.Unexport('ProvisioningCode') self.Unexport(objects='ProxierInfo') self.TemperatureStatus = temperature.TemperatureStatus() self.VendorLogFileList = {} self.VendorConfigFileList = {} self.SupportedDataModelList = {} self.ProcessorList = {} self.X_CATAWAMPUS_ORG_LedStatusList = {} self._next_led_number = 1 def __getattr__(self, name): """Allows passthrough of parameters to the platform-supplied device_id.""" if hasattr(self._device_id, name): return getattr(self._device_id, name) else: raise AttributeError('No such attribute %s' % name) @property def UpTime(self): return _GetUptime() @property def VendorLogFileNumberOfEntries(self): return len(self.VendorLogFileList) @property def VendorConfigFileNumberOfEntries(self): return len(self.VendorConfigFileList) @property def LocationNumberOfEntries(self): return 0 @property def ProcessorNumberOfEntries(self): return len(self.ProcessorList) @property def SupportedDataModelNumberOfEntries(self): return len(self.SupportedDataModelList) @property def X_CATAWAMPUS_ORG_LedStatusNumberOfEntries(self): return len(self.X_CATAWAMPUS_ORG_LedStatusList) def AddLedStatus(self, led): self.X_CATAWAMPUS_ORG_LedStatusList[self._next_led_number] = led self._next_led_number += 1 class MemoryStatusLinux26(BASE181DEVICE.DeviceInfo.MemoryStatus): """Abstraction to get memory information from the underlying platform. Reads /proc/meminfo to find TotalMem and FreeMem. """ def __init__(self): super(MemoryStatusLinux26, self).__init__() (self._totalmem, self._freemem) = self._GetMemInfo() @property def Total(self): return self._totalmem @property def Free(self): return self._freemem def _GetMemInfo(self): """Fetch TotalMem and FreeMem from the underlying platform. Returns: a list of two integers, (totalmem, freemem) """ totalmem = 0 freemem = 0 with open(PROC_MEMINFO) as pfile: for line in pfile: fields = line.split() name = fields[0] value = fields[1] if name == 'MemTotal:': totalmem = int(value) elif name == 'MemFree:': freemem = int(value) return (totalmem, freemem) class ProcessStatusLinux26(BASE181DEVICE.DeviceInfo.ProcessStatus): """Get information about running processes on Linux 2.6. Reads /proc/<pid> to get information about processes. """ # Field ordering in /proc/<pid>/stat _PID = 0 _COMM = 1 _STATE = 2 _UTIME = 13 _STIME = 14 _PRIO = 17 _RSS = 23 def __init__(self, ioloop=None): super(ProcessStatusLinux26, self).__init__() tick = os.sysconf(os.sysconf_names['SC_CLK_TCK']) self._msec_per_jiffy = 1000.0 / tick self.ioloop = ioloop or tornado.ioloop.IOLoop.instance() self.scheduler = PERIODICCALL(self.CpuUsageTimer, 300 * 1000, io_loop=self.ioloop) self.scheduler.start() self.cpu_usage = 0.0 self.cpu_used = 0 self.cpu_total = 0 self.ProcessList = tr.core.AutoDict('ProcessList', iteritems=self.IterProcesses, getitem=self.GetProcess) def _LinuxStateToTr181(self, linux_state): """Maps Linux process states to TR-181 process state names. Args: linux_state: One letter describing the state of the linux process, as described in proc(5). One of "RSDZTW" Returns: the tr-181 string describing the process state. """ mapping = { 'R': 'Running', 'S': 'Sleeping', 'D': 'Uninterruptible', 'Z': 'Zombie', 'T': 'Stopped', 'W': 'Uninterruptible'} return mapping.get(linux_state, 'Sleeping') def _JiffiesToMsec(self, utime, stime): ticks = int(utime) + int(stime) msecs = ticks * self._msec_per_jiffy return int(msecs) def _RemoveParens(self, command): return command[1:-1] def _ProcFileName(self, pid): return '%s/%s/stat' % (SLASH_PROC, pid) def _ParseProcStat(self): """Compute CPU utilization using /proc/stat. Returns: (used, total) used: number of jiffies where CPU was active total: total number of jiffies including idle """ with open(PROC_STAT) as f: for line in f: fields = line.split() if fields[0] == 'cpu': user = float(fields[1]) nice = float(fields[2]) syst = float(fields[3]) idle = float(fields[4]) iowt = float(fields[5]) irq = float(fields[6]) sirq = float(fields[7]) total = user + nice + syst + idle + iowt + irq + sirq used = total - idle return (used, total) return (0, 0) def CpuUsageTimer(self): """Called periodically to compute CPU utilization since last call.""" (new_used, new_total) = self._ParseProcStat() total = new_total - self.cpu_total used = new_used - self.cpu_used if total == 0: self.cpu_usage = 0.0 else: self.cpu_usage = (used / total) * 100.0 self.cpu_total = new_total self.cpu_used = new_used @property def CPUUsage(self): return int(self.cpu_usage) @property def ProcessNumberOfEntries(self): return len(self.ProcessList) def GetProcess(self, pid): """Get a self.Process() object for the given pid.""" try: with open(self._ProcFileName(pid)) as f: fields = f.read().split() p = self.Process(PID=int(fields[self._PID]), Command=self._RemoveParens(fields[self._COMM]), Size=int(fields[self._RSS]), Priority=int(fields[self._PRIO]), CPUTime=self._JiffiesToMsec(fields[self._UTIME], fields[self._STIME]), State=self._LinuxStateToTr181(fields[self._STATE])) except IOError: # This isn't an error. We have a list of files which existed the # moment the glob.glob was run. If a process exits before we get # around to reading it, its /proc files will go away. p = self.Process(PID=pid, Command='<exited>', Size=0, Priority=0, CPUTime=0, State='X_CATAWAMPUS-ORG_Exited') return p def IterProcesses(self): """Walks through /proc/<pid>/stat to return a list of all processes.""" for filename in glob.glob(self._ProcFileName('[0123456789]*')): pid = int(filename.split('/')[-2]) proc = self.GetProcess(pid) yield pid, proc class LedStatusReadFromFile(CATA181DEVICE.DeviceInfo.X_CATAWAMPUS_ORG_LedStatus): """X_CATAWAMPUS-ORG_LedStatus implementation which reads a line from a file.""" def __init__(self, name, filename): super(LedStatusReadFromFile, self).__init__() self._name = name self._filename = filename @property def Name(self): return self._name @property def Status(self): return open(self._filename).readline().strip() class DeviceInfo98Linux26(BASE98IGD.DeviceInfo): """Implementation of tr-98 DeviceInfo for Linux.""" def __init__(self, device_id): super(DeviceInfo98Linux26, self).__init__() assert isinstance(device_id, DeviceIdMeta) self._device_id = device_id self.Unexport(params='DeviceLog') self.Unexport(params='EnabledOptions') self.Unexport(params='FirstUseDate') self.Unexport(params='ProvisioningCode') self.Unexport(lists='VendorConfigFile') self.VendorConfigFileNumberOfEntries = 0 @property def SpecVersion(self): return '1.0' @property def UpTime(self): return _GetUptime() def __getattr__(self, name): if hasattr(self._device_id, name): return getattr(self._device_id, name) else: raise AttributeError('No such attribute %s' % name) def main(): dp = DeviceInfo181Linux26() #print tr.core.DumpSchema(dp) print tr.core.Dump(dp) if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-98 InternetGatewayDevice.Time """ __author__ = 'dgentry@google.com (Denton Gentry)' import copy import datetime import tr.core import tr.cwmpdate import tr.tr098_v1_4 BASE98IGD = tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice TIMENOW = datetime.datetime.now class TimeConfig(object): """A dumb data object to store config settings.""" def __init__(self): self.TZ = None class TimeTZ(BASE98IGD.Time): """An implementation of tr98 InternetGatewayDevice.Time. This object does not handle NTPd configuration, only CurrentLocalTime and LocalTimeZoneName. It writes the timezone information to /etc/TZ, which is generally the right thing to do for Linux uClibc systems. If the system is running glibc, you should not use this class. """ def __init__(self, tzfile='/etc/TZ'): BASE98IGD.Time.__init__(self) self.Unexport('DaylightSavingsEnd') self.Unexport('DaylightSavingsStart') self.Unexport('DaylightSavingsUsed') self.Unexport('LocalTimeZone') self.Unexport('NTPServer1') self.Unexport('NTPServer2') self.Unexport('NTPServer3') self.Unexport('NTPServer4') self.Unexport('NTPServer5') self.Unexport('Status') self.config = TimeConfig() self.old_config = None self.tzfile = tzfile def StartTransaction(self): config = self.config self.config = copy.copy(config) self.old_config = config def AbandonTransaction(self): self.config = self.old_config self.old_config = None def CommitTransaction(self): self.old_config = None if self.config.TZ is not None: f = open(self.tzfile, 'w') # uClibc is picky about whitespace: exactly one newline, no more, no less. tz = str(self.config.TZ).strip() + '\n' f.write(tz) f.close() def GetEnable(self): return True Enable = property(GetEnable, None, None, 'InternetGatewayDevice.Time.Enable') def GetCurrentLocalTime(self): return tr.cwmpdate.format(TIMENOW()) CurrentLocalTime = property(GetCurrentLocalTime, None, None, 'InternetGatewayDevice.Time.CurrentLocalTime') def GetLocalTimeZoneName(self): try: return open(self.tzfile, 'r').readline().strip() except IOError: return'' def SetLocalTimeZoneName(self, value): self.config.TZ = value LocalTimeZoneName = property(GetLocalTimeZoneName, SetLocalTimeZoneName, None, 'InternetGatewayDevice.Time.LocalTimeZoneName') def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-181 MoCA objects for Broadcom chipsets.""" __author__ = 'dgentry@google.com (Denton Gentry)' import re import subprocess import pynetlinux import tr.core import tr.tr181_v2_2 import netdev BASE181MOCA = tr.tr181_v2_2.Device_v2_2.Device.MoCA MOCACTL = '/bin/mocactl' PYNETIFCONF = pynetlinux.ifconfig.Interface def IntOrZero(arg): try: return int(arg) except ValueError: return 0 def FloatOrZero(arg): try: return float(arg) except ValueError: return 0.0 class BrcmMocaInterface(BASE181MOCA.Interface): """An implementation of tr181 Device.MoCA.Interface for Broadcom chipsets.""" def __init__(self, ifname, upstream=False): BASE181MOCA.Interface.__init__(self) self._ifname = ifname self.upstream = upstream self._pynet = PYNETIFCONF(ifname) self.Unexport('Alias') self.Unexport('MaxBitRate') self.Unexport('MaxIngressBW') self.Unexport('MaxEgressBW') self.Unexport('MaxNodes') self.Unexport('PreferredNC') self.Unexport('PrivacyEnabledSetting') self.Unexport('FreqCapabilityMask') self.Unexport('FreqCurrentMaskSetting') self.Unexport('FreqCurrentMask') self.Unexport('KeyPassphrase') self.Unexport('TxPowerLimit') self.Unexport('PowerCntlPhyTarget') self.Unexport('BeaconPowerLimit') self.Unexport('NetworkTabooMask') self.Unexport('NodeTabooMask') self.Unexport('TxBcastRate') self.Unexport('TxBcastPowerReduction') self.Unexport(objects='QoS') self.AssociatedDeviceList = tr.core.AutoDict( 'AssociatedDeviceList', iteritems=self.IterAssociatedDevices, getitem=self.GetAssociatedDeviceByIndex) @property # TODO(dgentry) need @sessioncache decorator. def Stats(self): return BrcmMocaInterfaceStatsLinux26(self._ifname) # TODO(dgentry) need @sessioncache decorator def _MocaCtlShowStatus(self): """Return output of mocactl show --status.""" mc = subprocess.Popen([MOCACTL, 'show', '--status'], stdout=subprocess.PIPE) out, _ = mc.communicate(None) return out.splitlines() # TODO(dgentry) need @sessioncache decorator def _MocaCtlShowInitParms(self): """Return output of mocactl show --initparms.""" mc = subprocess.Popen([MOCACTL, 'show', '--initparms'], stdout=subprocess.PIPE) out, _ = mc.communicate(None) return out.splitlines() # TODO(dgentry) need @sessioncache decorator def _MocaCtlShowConfig(self): """Return output of mocactl show --config.""" mc = subprocess.Popen([MOCACTL, 'show', '--config'], stdout=subprocess.PIPE) out, _ = mc.communicate(None) return out.splitlines() def _MocaCtlGetField(self, outfcn, field): """Look for one field in a mocactl command. ex: field='SwVersion' would return 5.6.789 from vendorId : 999999999 HwVersion : 0x12345678 SwVersion : 5.6.789 self MoCA Version : 0x11 Args: outfcn: a function to call, which must return a list of text lines. field: the text string to look for. Returns: The value of the field, or None. """ m_re = re.compile(field + '\s*:\s+(\S+)') for line in outfcn(): mr = m_re.search(line) if mr is not None: return mr.group(1) return None @property def Enable(self): # TODO(dgentry) Supposed to be read/write, but we don't disable yet. return True @property def Status(self): if not self._pynet.is_up(): return 'Down' (speed, duplex, auto, link_up) = self._pynet.get_link_info() if link_up: return 'Up' else: return 'Dormant' @property def Name(self): return self._ifname @property def LastChange(self): up = self._MocaCtlGetField(self._MocaCtlShowStatus, 'linkUpTime').split(':') secs = 0 for t in up: # linkUpTime ex: '23h:41m:30s' num = IntOrZero(t[:-1]) if t[-1] == 'y': secs += int(num * (365.25 * 24.0 * 60.0 * 60.0)) elif t[-1] == 'w': secs += num * (7 * 24 * 60 * 60) elif t[-1] == 'd': secs += num * (24 * 60 * 60) elif t[-1] == 'h': secs += num * (60 * 60) elif t[-1] == 'm': secs += num * 60 elif t[-1] == 's': secs += num return secs @property def LowerLayers(self): # In theory this is writeable, but it is nonsensical to write to it. return '' @property def Upstream(self): return self.upstream @property def MACAddress(self): return self._pynet.get_mac() @property def FirmwareVersion(self): ver = self._MocaCtlGetField(self._MocaCtlShowStatus, 'SwVersion') return ver if ver else '0' def _RegToMoCA(self, regval): moca = {'0x10': '1.0', '0x11': '1.1', '0x20': '2.0', '0x21': '2.1'} return moca.get(regval, '0.0') @property def HighestVersion(self): reg = self._MocaCtlGetField(self._MocaCtlShowStatus, 'self MoCA Version') return self._RegToMoCA(reg) @property def CurrentVersion(self): reg = self._MocaCtlGetField(self._MocaCtlShowStatus, 'networkVersionNumber') return self._RegToMoCA(reg) @property def NetworkCoordinator(self): nodeid = self._MocaCtlGetField(self._MocaCtlShowStatus, 'ncNodeId') return IntOrZero(nodeid) @property def NodeID(self): nodeid = self._MocaCtlGetField(self._MocaCtlShowStatus, 'nodeId') return IntOrZero(nodeid) @property def BackupNC(self): bnc = nodeid = self._MocaCtlGetField(self._MocaCtlShowStatus, 'backupNcId') return bnc if bnc else '' @property def PrivacyEnabled(self): private = self._MocaCtlGetField(self._MocaCtlShowInitParms, 'Privacy') return True if private == 'enabled' else False @property def CurrentOperFreq(self): freq = self._MocaCtlGetField(self._MocaCtlShowStatus, 'rfChannel') if freq: return IntOrZero(freq.split()[0]) return 0 @property def LastOperFreq(self): last = self._MocaCtlGetField(self._MocaCtlShowInitParms, 'Nv Params - Last Oper Freq') if last: return IntOrZero(last.split()[0]) return 0 @property def QAM256Capable(self): qam = self._MocaCtlGetField(self._MocaCtlShowInitParms, 'qam256Capability') return True if qam == 'on' else False @property def PacketAggregationCapability(self): # example: "maxPktAggr : 10 pkts" pkts = self._MocaCtlGetField(self._MocaCtlShowConfig, 'maxPktAggr') if pkts: return IntOrZero(pkts.split()[0]) return 0 @property def AssociatedDeviceNumberOfEntries(self): return len(self.AssociatedDeviceList) def _MocaCtlGetNodeIDs(self): """Return a list of active MoCA Node IDs.""" mc = subprocess.Popen([MOCACTL, 'showtbl', '--nodestats'], stdout=subprocess.PIPE) out, _ = mc.communicate(None) node_re = re.compile('\ANode\s*: (\d+)') nodes = set() for line in out.splitlines(): node = node_re.search(line) if node is not None: nodes.add(int(node.group(1))) return list(nodes) def GetAssociatedDevice(self, nodeid): """Get an AssociatedDevice object for the given NodeID.""" ad = BrcmMocaAssociatedDevice(nodeid) if ad: ad.ValidateExports() return ad def IterAssociatedDevices(self): """Retrieves a list of all associated devices.""" mocanodes = self._MocaCtlGetNodeIDs() for idx, nodeid in enumerate(mocanodes): yield idx, self.GetAssociatedDevice(nodeid) def GetAssociatedDeviceByIndex(self, index): mocanodes = self._MocaCtlGetNodeIDs() return self.GetAssociatedDevice(mocanodes[index]) class BrcmMocaInterfaceStatsLinux26(netdev.NetdevStatsLinux26, BASE181MOCA.Interface.Stats): """tr181 Device.MoCA.Interface.Stats for Broadcom chipsets.""" def __init__(self, ifname): netdev.NetdevStatsLinux26.__init__(self, ifname) BASE181MOCA.Interface.Stats.__init__(self) class BrcmMocaAssociatedDevice(BASE181MOCA.Interface.AssociatedDevice): """tr-181 Device.MoCA.Interface.AssociatedDevice for Broadcom chipsets.""" def __init__(self, nodeid): BASE181MOCA.Interface.AssociatedDevice.__init__(self) self.NodeID = nodeid self.MACAddress = '' self.PreferredNC = False self.Unexport('HighestVersion') self.PHYTxRate = 0 self.PHYRxRate = 0 self.TxPowerControlReduction = 0 self.RxPowerLevel = 0 self.TxBcastRate = 0 self.RxBcastPowerLevel = 0 self.TxPackets = 0 self.RxPackets = 0 self.RxErroredAndMissedPackets = 0 self.QAM256Capable = 0 self.PacketAggregationCapability = 0 self.RxSNR = 0 self.Unexport('Active') self.ParseNodeStatus() self.ParseNodeStats() def ParseNodeStatus(self): """Run mocactl show --nodestatus for this node, parse the output.""" mac_re = re.compile( '^MAC Address\s+: ((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})') pnc_re = re.compile('Preferred NC\s+: (\d+)') ptx_re = re.compile('\ATxUc.+?(\d+[.]?\d*)\s+dBm.*?(\d+)\s+bps') prx_re = re.compile('\ARxUc.+?(\d+[.]?\d*)\s+dBm.*?(\d+)\s+bps' '\s+(\d+[.]?\d*) dB') rxb_re = re.compile('\ARxBc.+?(\d+[.]?\d*)\s+dBm.*?(\d+)\s+bps') qam_re = re.compile('256 QAM capable\s+:\s+(\d+)') agg_re = re.compile('Aggregated PDUs\s+:\s+(\d+)') mc = subprocess.Popen([MOCACTL, 'show', '--nodestatus', str(self.NodeID)], stdout=subprocess.PIPE) out, _ = mc.communicate(None) for line in out.splitlines(): mac = mac_re.search(line) if mac is not None: self.MACAddress = mac.group(1) pnc = pnc_re.search(line) if pnc is not None: self.PreferredNC = False if pnc.group(1) is '0' else True ptx = ptx_re.search(line) if ptx is not None: self.PHYTxRate = IntOrZero(ptx.group(2)) / 1000000 self.TxPowerControlReduction = int(FloatOrZero(ptx.group(1))) prx = prx_re.search(line) if prx is not None: self.PHYRxRate = IntOrZero(prx.group(2)) / 1000000 self.RxPowerLevel = int(FloatOrZero(prx.group(1))) # TODO(dgentry) This cannot be right. SNR should be dB, not an integer. self.RxSNR = int(FloatOrZero(prx.group(3))) rxb = rxb_re.search(line) if rxb is not None: self.TxBcastRate = IntOrZero(rxb.group(2)) / 1000000 self.RxBcastPowerLevel = int(FloatOrZero(rxb.group(1))) qam = qam_re.search(line) if qam is not None: self.QAM256Capable = False if qam.group(1) is '0' else True agg = agg_re.search(line) if agg is not None: self.PacketAggregationCapability = IntOrZero(agg.group(1)) def ParseNodeStats(self): """Run mocactl show --nodestats for this node, parse the output.""" tx_re = re.compile('Unicast Tx Pkts To Node\s+: (\d+)') rx_re = re.compile('Unicast Rx Pkts From Node\s+: (\d+)') e1_re = re.compile('Rx CodeWord ErrorAndUnCorrected\s+: (\d+)') e2_re = re.compile('Rx NoSync Errors\s+: (\d+)') mc = subprocess.Popen([MOCACTL, 'show', '--nodestats', str(self.NodeID)], stdout=subprocess.PIPE) out, _ = mc.communicate(None) rx_err = 0 for line in out.splitlines(): tx = tx_re.search(line) if tx is not None: self.TxPackets = IntOrZero(tx.group(1)) rx = rx_re.search(line) if rx is not None: self.RxPackets = IntOrZero(rx.group(1)) e1 = e1_re.search(line) if e1 is not None: rx_err += IntOrZero(e1.group(1)) e2 = e2_re.search(line) if e2 is not None: rx_err += IntOrZero(e2.group(1)) self.RxErroredAndMissedPackets = rx_err class BrcmMoca(BASE181MOCA): """An implementation of tr181 Device.MoCA for Broadcom chipsets.""" def __init__(self): BASE181MOCA.__init__(self) self.InterfaceList = {} @property def InterfaceNumberOfEntries(self): return len(self.InterfaceList) def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for tr-181 DeviceInfo.TemperatureStatus implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import datetime import os import unittest import google3 import tr.core import temperature TR181_BAD_TEMPERATURE = -274 class MockSensor(object): def __init__(self): self.temperature = 0.0 def GetTemperature(self): return self.temperature class MockTime(object): TIME = 1341359845.764075 @staticmethod def MockTimeNow(): return datetime.datetime.utcfromtimestamp(MockTime.TIME) fake_periodics = [] class FakePeriodicCallback(object): def __init__(self, callback, callback_time, io_loop=None): self.callback = callback self.callback_time = callback_time / 1000 self.io_loop = io_loop self.start_called = False self.stop_called = False fake_periodics.append(self) def start(self): self.start_called = True def stop(self): self.stop_called = True class TemperatureTest(unittest.TestCase): """Tests for temperature.py.""" def setUp(self): self.old_HDPARM = temperature.HDPARM self.old_PERIODICCALL = temperature.PERIODICCALL self.old_TIMENOW = temperature.TIMENOW temperature.HDPARM = 'testdata/temperature/hdparm-H' def tearDown(self): temperature.HDPARM = self.old_HDPARM temperature.PERIODICCALL = self.old_PERIODICCALL temperature.TIMENOW = self.old_TIMENOW def testHardDriveTemperature(self): hd = temperature.SensorHdparm('sda') self.assertEqual(hd.GetTemperature(), 50) hd = temperature.SensorHdparm('/dev/sda') self.assertEqual(hd.GetTemperature(), 50) def testTemperatureFromFile(self): t = temperature.SensorReadFromFile('testdata/temperature/file1') self.assertEqual(t.GetTemperature(), 72) t = temperature.SensorReadFromFile('testdata/temperature/file2') self.assertEqual(t.GetTemperature(), 73) t = temperature.SensorReadFromFile('testdata/temperature/file3') self.assertEqual(t.GetTemperature(), 74) t = temperature.SensorReadFromFile('testdata/temperature/file4') self.assertEqual(t.GetTemperature(), TR181_BAD_TEMPERATURE) t = temperature.SensorReadFromFile('no/such/file') self.assertEqual(t.GetTemperature(), TR181_BAD_TEMPERATURE) def testValidateExports(self): t = temperature.TemperatureSensor(name='TestTemp', sensor=MockSensor()) t.ValidateExports() fan = temperature.FanReadFileRPS('Fan1', 'testdata/temperature/file1') fan.ValidateExports() def testDefaults(self): sensor = MockSensor() sensor.temperature = TR181_BAD_TEMPERATURE t = temperature.TemperatureSensor(name='TestTemp', sensor=sensor) t.Reset = True self.assertTrue(t.Enable) self.assertEqual(t.HighAlarmValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.HighAlarmTime, '0001-01-01T00:00:00Z') self.assertEqual(t.LowAlarmValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.LowAlarmTime, '0001-01-01T00:00:00Z') self.assertEqual(t.MinValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.MinTime, '0001-01-01T00:00:00Z') self.assertEqual(t.MaxValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.MaxTime, '0001-01-01T00:00:00Z') self.assertEqual(t.LastUpdate, '0001-01-01T00:00:00Z') self.assertEqual(t.PollingInterval, 300) self.assertFalse(t.Reset) self.assertEqual(t.Status, 'Enabled') self.assertEqual(t.Value, TR181_BAD_TEMPERATURE) def testMinMax(self): temperature.TIMENOW = MockTime.MockTimeNow sensor = MockSensor() sensor.temperature = TR181_BAD_TEMPERATURE t = temperature.TemperatureSensor(name='TestTemp', sensor=sensor) t.Reset = True self.assertEqual(t.MaxTime, '0001-01-01T00:00:00Z') self.assertEqual(t.MaxValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.MinTime, '0001-01-01T00:00:00Z') self.assertEqual(t.MinValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.Value, TR181_BAD_TEMPERATURE) sensor.temperature = 90.0 MockTime.TIME = 1341359845.0 t.SampleTemperature() self.assertEqual(t.MaxTime, '2012-07-03T23:57:25Z') self.assertEqual(t.MaxValue, 90) self.assertEqual(t.MinTime, '2012-07-03T23:57:25Z') self.assertEqual(t.MinValue, 90) self.assertEqual(t.Value, 90) sensor.temperature = 110.0 MockTime.TIME = 1341359846 t.SampleTemperature() self.assertEqual(t.MaxTime, '2012-07-03T23:57:26Z') self.assertEqual(t.MaxValue, 110) self.assertEqual(t.MinTime, '2012-07-03T23:57:25Z') self.assertEqual(t.MinValue, 90) self.assertEqual(t.Value, 110) sensor.temperature = 80.0 MockTime.TIME = 1341359847 t.SampleTemperature() self.assertEqual(t.MaxTime, '2012-07-03T23:57:26Z') self.assertEqual(t.MaxValue, 110) self.assertEqual(t.MinTime, '2012-07-03T23:57:27Z') self.assertEqual(t.MinValue, 80) self.assertEqual(t.Value, 80) t.Reset = True self.assertEqual(t.MaxTime, '0001-01-01T00:00:00Z') self.assertEqual(t.MaxValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.MinTime, '0001-01-01T00:00:00Z') self.assertEqual(t.MinValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.Value, TR181_BAD_TEMPERATURE) def testAlarms(self): temperature.TIMENOW = MockTime.MockTimeNow sensor = MockSensor() t = temperature.TemperatureSensor(name='TestTemp', sensor=sensor) self.assertEqual(t.HighAlarmValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.HighAlarmTime, '0001-01-01T00:00:00Z') self.assertEqual(t.LowAlarmValue, TR181_BAD_TEMPERATURE) self.assertEqual(t.LowAlarmTime, '0001-01-01T00:00:00Z') t.HighAlarmValue = 100 t.LowAlarmValue = 50 sensor.temperature = 90.0 t.SampleTemperature() self.assertEqual(t.HighAlarmValue, 100) self.assertEqual(t.HighAlarmTime, '0001-01-01T00:00:00Z') self.assertEqual(t.LowAlarmValue, 50) self.assertEqual(t.LowAlarmTime, '0001-01-01T00:00:00Z') sensor.temperature = 110.0 MockTime.TIME = 1341359848 t.SampleTemperature() self.assertEqual(t.HighAlarmTime, '2012-07-03T23:57:28Z') self.assertEqual(t.LowAlarmTime, '0001-01-01T00:00:00Z') sensor.temperature = 40.0 MockTime.TIME = 1341359849 t.SampleTemperature() self.assertEqual(t.HighAlarmTime, '2012-07-03T23:57:28Z') self.assertEqual(t.LowAlarmTime, '2012-07-03T23:57:29Z') t.Reset = True self.assertEqual(t.HighAlarmValue, 100) self.assertEqual(t.HighAlarmTime, '0001-01-01T00:00:00Z') self.assertEqual(t.LowAlarmValue, 50) self.assertEqual(t.LowAlarmTime, '0001-01-01T00:00:00Z') def testPeriodicCallback(self): del fake_periodics[:] temperature.PERIODICCALL = FakePeriodicCallback t = temperature.TemperatureSensor(name='TestTemp', sensor=MockSensor()) self.assertTrue(t.Enable) self.assertEqual(len(fake_periodics), 1) self.assertTrue(fake_periodics[0].start_called) self.assertFalse(fake_periodics[0].stop_called) self.assertEqual(fake_periodics[0].callback_time, 300) self.assertEqual(t.Status, 'Enabled') t.StartTransaction() t.Enable = False t.CommitTransaction() self.assertEqual(t.Status, 'Disabled') self.assertTrue(fake_periodics[0].stop_called) t.StartTransaction() t.Enable = True t.PollingInterval = 400 t.CommitTransaction() self.assertEqual(len(fake_periodics), 2) self.assertTrue(fake_periodics[1].start_called) self.assertFalse(fake_periodics[1].stop_called) self.assertEqual(fake_periodics[1].callback_time, 400) del fake_periodics[0:1] def testTemperatureStatus(self): ts = temperature.TemperatureStatus() ts.AddSensor(name='Test1', sensor=MockSensor()) ts.AddSensor(name='Test2', sensor=MockSensor()) ts.ValidateExports() self.assertEqual(ts.TemperatureSensorNumberOfEntries, 2) self.assertEqual(ts.TemperatureSensorList[1].Name, 'Test1') self.assertEqual(ts.TemperatureSensorList[2].Name, 'Test2') def testFanRPS(self): fan = temperature.FanReadFileRPS('Fan1', 'testdata/temperature/file1') self.assertEqual(fan.Name, 'Fan1') self.assertEqual(fan.RPM, 4320) self.assertEqual(fan.DesiredRPM, -1) self.assertEqual(fan.DesiredPercentage, -1) fan = temperature.FanReadFileRPS('Fan2', 'testdata/temperature/file2') self.assertEqual(fan.Name, 'Fan2') self.assertEqual(fan.RPM, 4380) self.assertEqual(fan.DesiredRPM, -1) self.assertEqual(fan.DesiredPercentage, -1) fan = temperature.FanReadFileRPS('Fan3', 'testdata/temperature/file3') self.assertEqual(fan.Name, 'Fan3') self.assertEqual(fan.RPM, 4440) self.assertEqual(fan.DesiredRPM, -1) self.assertEqual(fan.DesiredPercentage, -1) fan = temperature.FanReadFileRPS('Fan4', 'testdata/temperature/file4') self.assertEqual(fan.Name, 'Fan4') self.assertTrue(fan.RPM < 0) self.assertEqual(fan.DesiredRPM, -1) self.assertEqual(fan.DesiredPercentage, -1) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-181 Device.ManagementServer hierarchy of objects. Handles the Device.ManagementServer portion of TR-181, as described in http://www.broadband-forum.org/cwmp/tr-181-2-2-0.html """ __author__ = 'dgentry@google.com (Denton Gentry)' import tr.core import tr.tr098_v1_4 import tr.tr181_v2_2 BASEMGMT181 = tr.tr181_v2_2.Device_v2_2.Device.ManagementServer BASE98IGD = tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice BASEMGMT98 = BASE98IGD.ManagementServer class ManagementServer181(BASEMGMT181): """Implementation of tr-181 Device.ManagementServer.""" MGMTATTRS = frozenset([ 'CWMPRetryIntervalMultiplier', 'CWMPRetryMinimumWaitInterval', 'ConnectionRequestPassword', 'ConnectionRequestURL', 'ConnectionRequestUsername', 'DefaultActiveNotificationThrottle', 'EnableCWMP', 'ParameterKey', 'Password', 'PeriodicInformEnable', 'PeriodicInformInterval', 'PeriodicInformTime', 'URL', 'Username']) def __init__(self, mgmt): """Proxy object for tr-181 ManagementServer support. All requests for active, supported parameters pass through to the underlying management server implementation. Args: mgmt: the real management configuration object. """ super(ManagementServer181, self).__init__() self.mgmt = mgmt self.Unexport('DownloadProgressURL') self.Unexport('KickURL') self.Unexport('NATDetected') self.Unexport('STUNMaximumKeepAlivePeriod') self.Unexport('STUNMinimumKeepAlivePeriod') self.Unexport('STUNPassword') self.Unexport('STUNServerAddress') self.Unexport('STUNServerPort') self.Unexport('STUNUsername') self.Unexport('UDPConnectionRequestAddress') self.ManageableDeviceList = {} self.ManageableDeviceNumberOfEntries = 0 def StartTransaction(self): self.mgmt.StartTransaction() def AbandonTransaction(self): self.mgmt.AbandonTransaction() def CommitTransaction(self): self.mgmt.CommitTransaction() @property def STUNEnable(self): return False @property def UpgradesManaged(self): return True def __getattr__(self, name): if name in self.MGMTATTRS: return getattr(self.mgmt, name) else: raise KeyError('No such attribute %s' % name) def __setattr__(self, name, value): if name in self.MGMTATTRS: setattr(self.mgmt, name, value) else: BASEMGMT181.__setattr__(self, name, value) def __delattr__(self, name): if name in self.MGMTATTRS: return delattr(self.mgmt, name) else: return BASEMGMT181.__delattr__(self, name) class ManagementServer98(BASEMGMT98): """Implementation of tr-98 InternetGatewayDevice.ManagementServer.""" MGMTATTRS = frozenset([ 'CWMPRetryIntervalMultiplier', 'CWMPRetryMinimumWaitInterval', 'ConnectionRequestPassword', 'ConnectionRequestURL', 'ConnectionRequestUsername', 'DefaultActiveNotificationThrottle', 'EnableCWMP', 'ParameterKey', 'Password', 'PeriodicInformEnable', 'PeriodicInformInterval', 'PeriodicInformTime', 'URL', 'Username']) def __init__(self, mgmt): """Proxy object for tr-98 ManagementServer support. All requests for active, supported parameters pass through to the underlying management server implementation. Args: mgmt: the real management configuration object. """ super(ManagementServer98, self).__init__() self.mgmt = mgmt self.Unexport('AliasBasedAddressing') self.Unexport('AutoCreateInstances') self.Unexport('DownloadProgressURL') self.Unexport('InstanceMode') self.Unexport('KickURL') self.Unexport('ManageableDeviceNotificationLimit') self.Unexport('NATDetected') self.Unexport('STUNEnable') self.Unexport('STUNMaximumKeepAlivePeriod') self.Unexport('STUNMinimumKeepAlivePeriod') self.Unexport('STUNPassword') self.Unexport('STUNServerAddress') self.Unexport('STUNServerPort') self.Unexport('STUNUsername') self.Unexport('UDPConnectionRequestAddress') self.Unexport('UDPConnectionRequestAddressNotificationLimit') self.EmbeddedDeviceList = {} self.ManageableDeviceList = {} self.VirtualDeviceList = {} def StartTransaction(self): self.mgmt.StartTransaction() def AbandonTransaction(self): self.mgmt.AbandonTransaction() def CommitTransaction(self): self.mgmt.CommitTransaction() @property def ManageableDeviceNumberOfEntries(self): return 0 @property def UpgradesManaged(self): return True @property def VirtualDeviceNumberOfEntries(self): return 0 def __getattr__(self, name): if name in self.MGMTATTRS: return getattr(self.mgmt, name) else: raise KeyError('No such attribute %s' % name) def __setattr__(self, name, value): if name in self.MGMTATTRS: return setattr(self.mgmt, name, value) else: return BASEMGMT98.__setattr__(self, name, value) def __delattr__(self, name): if name in self.MGMTATTRS: return delattr(self.mgmt, name) else: return BASEMGMT98.__delattr__(self, name) def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright 2012 Google Inc. All Rights Reserved. # # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for periodic_statistics.py.""" __author__ = 'jnewlin@google.com (John Newlin)' import datetime import mox import time import unittest import google3 import periodic_statistics import tornado.ioloop import tr.core import tr.http class FakeWLAN(tr.core.Exporter): def __init__(self): tr.core.Exporter.__init__(self) self.Export(['TotalBytesSent']) self.TotalBytesSent = 100 class PeriodicStatisticsTest(unittest.TestCase): def setUp(self): self.ps = periodic_statistics.PeriodicStatistics() def tearDown(self): pass def testValidateExports(self): self.ps.ValidateExports() # Add some samples sets and check again. self.ps.AddExportObject('SampleSet', '0') self.ps.AddExportObject('SampleSet', '1') self.assertTrue(0 in self.ps.sample_sets) self.assertTrue(1 in self.ps.sample_sets) self.ps.sample_sets[0].AddExportObject('Parameter', '0') self.ps.sample_sets[0].AddExportObject('Parameter', '1') self.ps.sample_sets[1].AddExportObject('Parameter', '0') self.ps.sample_sets[1].AddExportObject('Parameter', '1') self.assertTrue(0 in self.ps.sample_sets[0]._parameter_list) self.assertTrue(1 in self.ps.sample_sets[0]._parameter_list) self.assertTrue(0 in self.ps.sample_sets[1]._parameter_list) self.assertTrue(1 in self.ps.sample_sets[1]._parameter_list) self.ps.ValidateExports() def testSetCpeRoot(self): fake_cpe = object() fake_root = object() self.ps.SetCpe(fake_cpe) self.ps.SetRoot(fake_root) self.assertEqual(fake_cpe, self.ps._cpe) self.assertEqual(fake_root, self.ps._root) def testCollectSample(self): obj_name = 'InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.' obj_param = 'TotalBytesSent' sampled_param = periodic_statistics.PeriodicStatistics.SampleSet.Parameter() sampled_param.Enable = True sampled_param.Reference = obj_name + obj_param sample_set = periodic_statistics.PeriodicStatistics.SampleSet() m = mox.Mox() mock_root = m.CreateMock(tr.core.Exporter) mock_root.GetExport(mox.IsA(str)).AndReturn(1000) m.ReplayAll() sample_set.SetCpeAndRoot(cpe=object(), root=mock_root) sample_set.SetParameter('1', sampled_param) sample_set.CollectSample() m.VerifyAll() # Check that the sampled_param updated it's values. self.assertEqual('1000', sampled_param.Values) def testCollectSampleWrap(self): obj_name = 'InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.' obj_param = 'TotalBytesSent' sampled_param = periodic_statistics.PeriodicStatistics.SampleSet.Parameter() sampled_param.Enable = True sampled_param.Reference = obj_name + obj_param sample_set = periodic_statistics.PeriodicStatistics.SampleSet() m = mox.Mox() mock_root = m.CreateMock(tr.core.Exporter) mock_root.GetExport(mox.IsA(str)).AndReturn(1000) mock_root.GetExport(mox.IsA(str)).AndReturn(2000) mock_root.GetExport(mox.IsA(str)).AndReturn(3000) mock_root.GetExport(mox.IsA(str)).AndReturn(4000) mock_root.GetExport(mox.IsA(str)).AndReturn(5000) m.ReplayAll() sample_set.SetCpeAndRoot(cpe=object(), root=mock_root) sample_set.SetParameter('1', sampled_param) sample_set.ReportSamples = 1 sample_set._sample_start_time = 10 sample_set.CollectSample(20) self.assertEqual('10', sample_set.SampleSeconds) self.assertEqual('10', sampled_param.SampleSeconds) self.assertEqual('1000', sampled_param.Values) # Take a second sample sample_set._sample_start_time = 25 sample_set.CollectSample(30) self.assertEqual('5', sample_set.SampleSeconds) self.assertEqual('5', sampled_param.SampleSeconds) self.assertEqual('2000', sampled_param.Values) # change the ReportSamples sample_set.ReportSamples = 3 sample_set._sample_start_time = 24 sample_set.CollectSample(30) sample_set._sample_start_time = 33 sample_set.CollectSample(40) self.assertEqual('5,6,7', sample_set.SampleSeconds) self.assertEqual('5,6,7', sampled_param.SampleSeconds) self.assertEqual('2000,3000,4000', sampled_param.Values) # This next sample should cause the oldest sample to be discarded. sample_set._sample_start_time = 42 sample_set.CollectSample(50) self.assertEqual('6,7,8', sample_set.SampleSeconds) self.assertEqual('6,7,8', sampled_param.SampleSeconds) self.assertEqual('3000,4000,5000', sampled_param.Values) # Set ReportSamples to a smaller value and make sure old values # get trimmed. sample_set.ReportSamples = 2 self.assertEqual('7,8', sample_set.SampleSeconds) self.assertEqual('7,8', sampled_param.SampleSeconds) self.assertEqual('4000,5000', sampled_param.Values) m.VerifyAll() class SampleSetTest(unittest.TestCase): def setUp(self): self.ps = periodic_statistics.PeriodicStatistics() self.m = mox.Mox() self.mock_root = self.m.CreateMock(tr.core.Exporter) self.mock_cpe = self.m.CreateMock(tr.http.CPEStateMachine) self.ps.SetCpe(self.mock_cpe) self.ps.SetRoot(self.mock_root) def tearDown(self): self.m.VerifyAll() def testValidateExports(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() sample_set.ValidateExports() def testParameters(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() param1 = periodic_statistics.PeriodicStatistics.SampleSet.Parameter() sample_set.ParameterList['0'] = param1 self.assertEqual(1, len(sample_set.ParameterList)) for key in sample_set.ParameterList: self.assertEqual(key, '0') self.assertEqual(sample_set.ParameterList[key], param1) del sample_set.ParameterList['0'] self.assertEqual(0, len(sample_set.ParameterList)) def testReportSamples(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() self.assertEqual(0, sample_set.ReportSamples) sample_set.ReportSamples = '10' self.assertEqual(10, sample_set.ReportSamples) def testSampleInterval(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() self.ps.SampleSetList['0'] = sample_set self.assertEqual(0, sample_set.SampleInterval) sample_set.SampleInterval = 10 self.assertEqual(10, sample_set.SampleInterval) def testCollectSample(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() self.ps.SampleSetList['0'] = sample_set start1_time = time.time() sample_set.CollectSample() end1_time = time.time() self.assertEqual(1, len(sample_set._sample_times)) self.assertTrue(start1_time <= sample_set._sample_times[0][0]) self.assertTrue(end1_time >= sample_set._sample_times[0][1]) start1_time = time.time() sample_set.CollectSample() end2_time = time.time() self.assertEqual(2, len(sample_set._sample_times)) self.assertTrue( sample_set._sample_times[0][0] < sample_set._sample_times[1][0]) self.assertEqual(sample_set.SampleSeconds, '0,0') def testSampleTrigger(self): mock_ioloop = self.m.CreateMock(tornado.ioloop.IOLoop) self.mock_cpe.ioloop = mock_ioloop sample_set = periodic_statistics.PeriodicStatistics.SampleSet() self.ps.SampleSetList['0'] = sample_set mock_ioloop.add_timeout(mox.IsA(datetime.timedelta), mox.IgnoreArg()).AndReturn(1) self.m.ReplayAll() sample_set.SetSampleTrigger() def testUpdateSampling(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() self.m.StubOutWithMock(sample_set, 'SetSampleTrigger') self.m.StubOutWithMock(sample_set, 'StopSampling') # First call should call StopSampling sample_set.StopSampling() # first call sample_set.StopSampling() # Calle for Enable toggle sample_set.StopSampling() # Called when ReportSamples is set sample_set.SetSampleTrigger() # called when SampleInterval is set sample_set.StopSampling() self.m.ReplayAll() sample_set.UpdateSampling() sample_set.Enable = 'True' sample_set.ReportSamples = 100 sample_set.SampleInterval = 100 sample_set.Enable = 'False' def testSampleTimes(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() sample_set._sample_times = [] self.assertEqual('', sample_set.SampleSeconds) self.assertEqual('0001-01-01T00:00:00Z', sample_set.ReportStartTime) sample_time1 = (10.0, 12.5) sample_time2 = (13.0, 15.7) sample_time3 = (20.0, 25.3) sample_set._sample_times.append(sample_time1) self.assertEqual('3', sample_set.SampleSeconds) sample_set._sample_times.append(sample_time2) self.assertEqual('3,3', sample_set.SampleSeconds) sample_set._sample_times.append(sample_time3) self.assertEqual(sample_set.SampleSeconds, '3,3,5') # First sample is taken at absolute time 10.0, which is 10s after # the epoch. self.assertEqual('1970-01-01T00:00:10Z', sample_set.ReportStartTime) def testPassiveNotify(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() self.m.StubOutWithMock(sample_set, 'ClearSamplingData') self.m.StubOutWithMock(sample_set, 'SetSampleTrigger') PARAMETER = periodic_statistics.PeriodicStatistics.SampleSet.Parameter mock_cpe = self.m.CreateMock(tr.http.CPEStateMachine) mock_root = self.m.CreateMock(tr.core.Exporter) mock_param1 = self.m.CreateMock(PARAMETER) mock_param2 = self.m.CreateMock(PARAMETER) mock_param1.Reference = 'Fake.Param.One' mock_param2.Reference = 'Fake.Param.Two' sample_set.ClearSamplingData() mock_param1.CollectSample(start_time=10, current_time=20) mock_param2.CollectSample(start_time=10, current_time=20) sample_set.SetSampleTrigger(20) obj_name = 'Device.PeriodicStatistics.SampleSet.0' param_name = obj_name + '.Status' mock_root.GetCanonicalName(sample_set).AndReturn(obj_name) mock_cpe.SetNotificationParameters([(param_name, 'Trigger')]) self.m.ReplayAll() self.assertEqual({}, sample_set._parameter_list) sample_set._parameter_list['1'] = mock_param1 sample_set._parameter_list['2'] = mock_param2 sample_set.SetCpeAndRoot(cpe=mock_cpe, root=mock_root) self.assertEqual(0, sample_set.FetchSamples) sample_set.FetchSamples = 1 sample_set._sample_start_time = 10 self.assertEqual(1, sample_set.FetchSamples) sample_set._report_samples = 1 sample_set.Enable = 'True' sample_set._attributes['Notification'] = 1 sample_set.CollectSample(20) print "end testPassNotify" def testActiveNotify(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() self.m.StubOutWithMock(sample_set, 'ClearSamplingData') self.m.StubOutWithMock(sample_set, 'SetSampleTrigger') PARAMETER = periodic_statistics.PeriodicStatistics.SampleSet.Parameter mock_cpe = self.m.CreateMock(tr.http.CPEStateMachine) mock_root = self.m.CreateMock(tr.core.Exporter) mock_param1 = self.m.CreateMock(PARAMETER) mock_param2 = self.m.CreateMock(PARAMETER) mock_param1.Reference = 'Fake.Param.One' mock_param2.Reference = 'Fake.Param.Two' mock_param1.CollectSample(start_time=10, current_time=20) mock_param2.CollectSample(start_time=10, current_time=20) sample_set.SetSampleTrigger(20) obj_name = 'Device.PeriodicStatistics.SampleSet.0' param_name = obj_name + '.Status' sample_set.ClearSamplingData() mock_root.GetCanonicalName(sample_set).AndReturn(obj_name) mock_cpe.SetNotificationParameters([(param_name, 'Trigger')]) mock_cpe.NewValueChangeSession() self.m.ReplayAll() self.assertEqual({}, sample_set._parameter_list) sample_set._parameter_list['1'] = mock_param1 sample_set._parameter_list['2'] = mock_param2 sample_set.SetCpeAndRoot(cpe=mock_cpe, root=mock_root) self.assertEqual(0, sample_set.FetchSamples) sample_set.FetchSamples = 1 self.assertEqual(1, sample_set.FetchSamples) sample_set._report_samples = 1 sample_set.Enable = 'True' sample_set._attributes['Notification'] = 2 sample_set._sample_start_time = 10 sample_set.CollectSample(20) def testClearSamplingData(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() param1 = periodic_statistics.PeriodicStatistics.SampleSet.Parameter() param2 = periodic_statistics.PeriodicStatistics.SampleSet.Parameter() sample_set.ClearSamplingData() sample_set.ParameterList['0'] = param1 sample_set.ParameterList['1'] = param2 self.assertEqual(2, len(sample_set._parameter_list)) sample_set.ClearSamplingData() # put in some fake data sample_set._sample_seconds = [1, 2, 3] sample_set._fetch_samples = 10 sample_set._report_samples = 10 param1._values = ['1', '2', '3'] param1._sample_seconds = [5, 6, 7] param2._values = ['5', '6', '7'] param2._sample_seconds = [8, 9, 10] sample_set.ClearSamplingData() self.assertEqual(0, len(sample_set._sample_times)) self.assertEqual(0, len(param1._sample_times)) self.assertEqual(0, len(param2._sample_times)) self.assertEqual(0, len(param1._values)) self.assertEqual(0, len(param2._values)) def testCalcTimeToNext(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() sample_set._sample_interval = 60 self.assertEqual(60, sample_set.CalcTimeToNextSample(0)) sample_set.TimeReference = '2012-06-1T1:00:00.0Z' sample_set._sample_interval = 15 # Every 15 seconds. # Check time to sample if current time is 5 seconds after the timeref. current_time = time.mktime((2012, 6, 1, 1, 0, 5, -1, -1, -1)) time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(10, time_till_sample) # Check time to sample if current time is 16 seconds after the timeref. current_time = time.mktime((2012, 6, 1, 1, 0, 16, -1, -1, -1)) time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(14, time_till_sample) # Check time to sample if current time is 1 hour after the timeref current_time = time.mktime((2012, 6, 1, 2, 0, 5, -1, -1, -1)) time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(10, time_till_sample) # Check time to sample if current time is 1 day after the timeref current_time = time.mktime((2012, 6, 2, 1, 0, 0, -1, -1, -1)) time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(15, time_till_sample) # Check time to sample if current time is 1 day before the timeref current_time = time.mktime((2012, 6, 2, 1, 0, 0, -1, -1, -1)) time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(15, time_till_sample) # Check using TimeReference, where the time to sample would # be less than 1 sample_set.TimeReference = '1970-01-01T00:00:00Z' sample_set.SampleInterval = 5 time_till_sample = sample_set.CalcTimeToNextSample(current_time) current_time = time.mktime((2012, 6, 2, 1, 1, 4, -1, -1, -1)) time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(1, time_till_sample) current_time += 0.9 time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(1, time_till_sample) current_time += 0.2 time_till_sample = sample_set.CalcTimeToNextSample(current_time) self.assertEqual(5, time_till_sample) def testFetchSamplesTriggered(self): sample_set = periodic_statistics.PeriodicStatistics.SampleSet() sample_set._report_samples = 10 sample_set._fetch_samples = 7 sample_set._samples_collected = 0 self.assertFalse(sample_set.FetchSamplesTriggered()) sample_set._samples_collected = 7 self.assertTrue(sample_set.FetchSamplesTriggered()) sample_set._samples_collected = 10 self.assertFalse(sample_set.FetchSamplesTriggered()) sample_set._samples_collected = 17 self.assertTrue(sample_set.FetchSamplesTriggered()) sample_set._samples_collected = 27 self.assertTrue(sample_set.FetchSamplesTriggered()) # Make sure 0 doesn't do anything sample_set._fetch_samples = 0 sample_set._samples_collected = 10 self.assertFalse(sample_set.FetchSamplesTriggered()) # and if FetchSamples > ReportSamples do nothing sample_set._fetch_samples = 11 sample_set._samples_collected = 11 self.assertFalse(sample_set.FetchSamplesTriggered()) # check FetchSamples == ReportSamples sample_set._report_samples = 10 sample_set._fetch_samples = 10 sample_set._samples_collected = 10 self.assertTrue(sample_set.FetchSamplesTriggered()) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for brcmwifi.py implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import os import stat import tempfile import unittest import google3 import brcmwifi import netdev class BrcmWifiTest(unittest.TestCase): def setUp(self): self.old_WL_EXE = brcmwifi.WL_EXE brcmwifi.WL_EXE = 'testdata/brcmwifi/wlempty' brcmwifi.WL_SLEEP = 0 brcmwifi.WL_AUTOCHAN_SLEEP = 0 self.old_PROC_NET_DEV = netdev.PROC_NET_DEV self.files_to_remove = list() def tearDown(self): brcmwifi.WL_EXE = self.old_WL_EXE netdev.PROC_NET_DEV = self.old_PROC_NET_DEV for f in self.files_to_remove: os.remove(f) def MakeTestScript(self): """Create a script in /tmp, with an output file.""" scriptfile = tempfile.NamedTemporaryFile(mode='r+', delete=False) os.chmod(scriptfile.name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) outfile = tempfile.NamedTemporaryFile(delete=False) text = '#!/bin/sh\necho $* >> {0}'.format(outfile.name) scriptfile.write(text) scriptfile.close() # Linux won't run it if text file is busy self.files_to_remove.append(scriptfile.name) self.files_to_remove.append(outfile.name) return (scriptfile, outfile) def RmFromList(self, l, item): try: l.remove('-i wifi0 ' + item) return True except ValueError: return False def VerifyCommonWlCommands(self, cmd, rmwep=0, wsec=0, primary_key=1, wpa_auth=0, sup_wpa=1, amode='open', autochan=True): # Verify the number of "rmwep #" commands, and remove them. l = [x for x in cmd.split('\n') if x] # Suppress blank lines for i in range(rmwep, 4): self.assertTrue(self.RmFromList(l, 'rmwep %d' % i)) self.assertTrue(self.RmFromList(l, 'wsec %d' % wsec)) self.assertTrue(self.RmFromList(l, 'sup_wpa %d' % sup_wpa)) self.assertTrue(self.RmFromList(l, 'wpa_auth %d' % wpa_auth)) self.assertTrue(self.RmFromList(l, 'primary_key %d' % primary_key)) self.assertTrue(self.RmFromList(l, 'radio on')) self.assertTrue(self.RmFromList(l, 'ap 1')) self.assertTrue(self.RmFromList(l, 'bss down')) if autochan: self.assertTrue(self.RmFromList(l, 'down')) self.assertTrue(self.RmFromList(l, 'spect 0')) self.assertTrue(self.RmFromList(l, 'mpc 0')) self.assertTrue(self.RmFromList(l, 'up')) self.assertTrue(self.RmFromList(l, 'ssid')) self.assertTrue(self.RmFromList(l, 'autochannel 1')) self.assertTrue(self.RmFromList(l, 'autochannel 2')) self.assertTrue(self.RmFromList(l, 'down')) self.assertTrue(self.RmFromList(l, 'spect 1')) self.assertTrue(self.RmFromList(l, 'mpc 1')) return l def testValidateExports(self): netdev.PROC_NET_DEV = 'testdata/brcmwifi/proc_net_dev' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.ValidateExports() stats = brcmwifi.BrcmWlanConfigurationStats('wifi0') stats.ValidateExports() def testCounters(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlcounters' wl = brcmwifi.Wl('foo0') counters = wl.GetWlCounters() self.assertEqual(counters['rxrtsocast'], '93') self.assertEqual(counters['d11_txfrmsnt'], '0') self.assertEqual(counters['txfunfl'], ['59', '60', '61', '62', '63', '64']) def testStatus(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlbssup' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.Status, 'Up') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlbssdown' self.assertEqual(bw.Status, 'Disabled') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlbsserr' self.assertEqual(bw.Status, 'Error') def testChannel(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlchannel' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.Channel, 1) def testValidateChannel(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlchannel' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetChannel, '166') self.assertRaises(ValueError, bw.SetChannel, '14') self.assertRaises(ValueError, bw.SetChannel, '0') self.assertRaises(ValueError, bw.SetChannel, '20') def testSetChannel(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' bw.Channel = '11' bw.CommitTransaction() output = out.read() out.close() outlist = self.VerifyCommonWlCommands(output, autochan=False) self.assertTrue(self.RmFromList(outlist, 'channel 11')) self.assertFalse(outlist) def testPossibleChannels(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlchannels' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.PossibleChannels, '1-11,36,40,44,48,52,56,60,64,100,104,108,112,116,120,124,' '128,132,136,140,149,153,157,161,165') def testSSID(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlssid' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.SSID, 'MySSID') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlssidempty' self.assertEqual(bw.SSID, '') def testValidateSSID(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlssid' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.SSID = r'myssid' bw.SSID = r'my ssid' # A ValueError will fail the test here. self.assertRaises(ValueError, bw.SetSSID, r'myssidiswaaaaaaaaaaaaaaaaaytoolongtovalidate') def testSetSSID(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' out.truncate() bw.SSID = 'myssid' bw.CommitTransaction() output = out.read() out.close() outlist = self.VerifyCommonWlCommands(output) self.assertTrue(self.RmFromList(outlist, 'up')) self.assertTrue(self.RmFromList(outlist, 'ssid myssid')) self.assertFalse(outlist) def testInvalidSSID(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetSSID, 'abcdefghijklmnopqrstuvwxyz0123456789' 'abcdefghijklmnopqrstuvwxyz0123456789') def testBSSID(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlbssid' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.BSSID, '01:23:45:67:89:ab') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlempty' self.assertEqual(bw.BSSID, '00:00:00:00:00:00') def testValidateBSSID(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetBSSID, 'This is not a BSSID.') self.assertRaises(ValueError, bw.SetBSSID, '00:00:00:00:00:00') self.assertRaises(ValueError, bw.SetBSSID, 'ff:ff:ff:ff:ff:ff') def testSetBSSID(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' out.truncate() bw.BSSID = '00:99:aa:bb:cc:dd' bw.CommitTransaction() output = out.read() out.close() outlist = self.VerifyCommonWlCommands(output) self.assertTrue(self.RmFromList(outlist, 'bssid 00:99:aa:bb:cc:dd')) self.assertFalse(outlist) def testRegulatoryDomain(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlcountry.us' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.RegulatoryDomain, 'US') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlcountry.jp' self.assertEqual(bw.RegulatoryDomain, 'JP') def testInvalidRegulatoryDomain(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlcountrylist' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetRegulatoryDomain, 'ZZ') self.assertRaises(ValueError, bw.SetRegulatoryDomain, '') def testSetRegulatoryDomain(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlcountrylist' bw.StartTransaction() bw.RegulatoryDomain = 'US' (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw.Enable = 'True' out.truncate() bw.RadioEnabled = 'True' bw.CommitTransaction() output = out.read() out.close() outlist = self.VerifyCommonWlCommands(output) self.assertTrue(self.RmFromList(outlist, 'country US')) self.assertFalse(outlist) def testBasicRateSet(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlrateset' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.BasicDataTransmitRates, '1,2,5.5,11') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlrateset2' self.assertEqual(bw.BasicDataTransmitRates, '1,2,5.5,11,16.445') def testOperationalRateSet(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlrateset' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.OperationalDataTransmitRates, '1,2,5.5,6,9,11,12,18,24,36,48,54') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlrateset2' self.assertEqual(bw.OperationalDataTransmitRates, '1,2,5.5,7.5,11,16.445') def testTransmitPower(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlpwrpercent' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.TransmitPower, '25') def testValidateTransmitPower(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetTransmitPower, '101') self.assertRaises(ValueError, bw.SetTransmitPower, 'foo') def testSetTransmitPower(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' out.truncate() bw.TransmitPower = '77' bw.CommitTransaction() output = out.read() out.close() outlist = self.VerifyCommonWlCommands(output) self.assertTrue(self.RmFromList(outlist, 'pwr_percent 77')) self.assertFalse(outlist) def testTransmitPowerSupported(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.TransmitPowerSupported, '1-100') def testAutoRateFallBackEnabled(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlinterference0' self.assertFalse(bw.AutoRateFallBackEnabled) brcmwifi.WL_EXE = 'testdata/brcmwifi/wlinterference1' self.assertFalse(bw.AutoRateFallBackEnabled) brcmwifi.WL_EXE = 'testdata/brcmwifi/wlinterference2' self.assertFalse(bw.AutoRateFallBackEnabled) brcmwifi.WL_EXE = 'testdata/brcmwifi/wlinterference3' self.assertTrue(bw.AutoRateFallBackEnabled) brcmwifi.WL_EXE = 'testdata/brcmwifi/wlinterference4' self.assertTrue(bw.AutoRateFallBackEnabled) def testSetAutoRateFallBackEnabled(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' out.truncate() bw.AutoRateFallBackEnabled = 'True' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output) self.assertTrue(self.RmFromList(outlist, 'interference 4')) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.AutoRateFallBackEnabled = 'False' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output) out.close() self.assertTrue(self.RmFromList(outlist, 'interference 3')) self.assertFalse(outlist) def testSSIDAdvertisementEnabled(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlclosed0' self.assertTrue(bw.SSIDAdvertisementEnabled) brcmwifi.WL_EXE = 'testdata/brcmwifi/wlclosed1' self.assertFalse(bw.SSIDAdvertisementEnabled) def testSetSSIDAdvertisementEnabled(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw.Enable = 'True' bw.RadioEnabled = 'True' out.truncate() bw.SSIDAdvertisementEnabled = 'True' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output) self.assertTrue(self.RmFromList(outlist, 'closed 0')) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.SSIDAdvertisementEnabled = 'False' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output) out.close() self.assertTrue(self.RmFromList(outlist, 'closed 1')) self.assertFalse(outlist) def testRadioEnabled(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlradiooff' self.assertFalse(bw.RadioEnabled) brcmwifi.WL_EXE = 'testdata/brcmwifi/wlradioon' self.assertTrue(bw.RadioEnabled) def testSetRadioEnabled(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' out.truncate() bw.RadioEnabled = 'True' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.RadioEnabled = 'False' bw.CommitTransaction() output = out.read() out.close() self.assertEqual(output, '-i wifi0 radio off\n') def testNoEnable(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.Enable = 'False' output = out.read() out.close() self.assertFalse(output) self.assertFalse(bw.Enable) def testInvalidBooleans(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetAutoRateFallBackEnabled, 'InvalidBool') self.assertRaises(ValueError, bw.SetEnable, 'InvalidBool') self.assertRaises(ValueError, bw.SetRadioEnabled, 'InvalidBool') self.assertRaises(ValueError, bw.SetSSIDAdvertisementEnabled, 'InvalidBool') def testEncryptionModes(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec0' self.assertEqual(bw.IEEE11iEncryptionModes, 'X_CATAWAMPUS-ORG_None') self.assertEqual(bw.WPAEncryptionModes, 'X_CATAWAMPUS-ORG_None') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec1' self.assertEqual(bw.IEEE11iEncryptionModes, 'WEPEncryption') self.assertEqual(bw.WPAEncryptionModes, 'WEPEncryption') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec2' self.assertEqual(bw.IEEE11iEncryptionModes, 'TKIPEncryption') self.assertEqual(bw.WPAEncryptionModes, 'TKIPEncryption') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec3' self.assertEqual(bw.IEEE11iEncryptionModes, 'WEPandTKIPEncryption') self.assertEqual(bw.WPAEncryptionModes, 'WEPandTKIPEncryption') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec4' self.assertEqual(bw.IEEE11iEncryptionModes, 'AESEncryption') self.assertEqual(bw.WPAEncryptionModes, 'AESEncryption') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec5' self.assertEqual(bw.IEEE11iEncryptionModes, 'WEPandAESEncryption') self.assertEqual(bw.WPAEncryptionModes, 'WEPandAESEncryption') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec6' self.assertEqual(bw.IEEE11iEncryptionModes, 'TKIPandAESEncryption') self.assertEqual(bw.WPAEncryptionModes, 'TKIPandAESEncryption') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec7' self.assertEqual(bw.IEEE11iEncryptionModes, 'WEPandTKIPandAESEncryption') self.assertEqual(bw.WPAEncryptionModes, 'WEPandTKIPandAESEncryption') brcmwifi.WL_EXE = 'testdata/brcmwifi/wlwsec15' self.assertEqual(bw.IEEE11iEncryptionModes, 'WEPandTKIPandAESEncryption') self.assertEqual(bw.WPAEncryptionModes, 'WEPandTKIPandAESEncryption') def testInvalidEncryptionModes(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetBasicEncryptionModes, 'invalid') self.assertRaises(ValueError, bw.SetIEEE11iEncryptionModes, 'invalid') self.assertRaises(ValueError, bw.SetWPAEncryptionModes, 'invalid') def testInvalidBeaconType(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetBeaconType, 'FooFi') def testAuthenticationMode(self): bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertRaises(ValueError, bw.SetBasicAuthenticationMode, 'Invalid') bw.BasicAuthenticationMode = 'None' bw.BasicAuthenticationMode = 'SharedAuthentication' self.assertRaises(ValueError, bw.SetIEEE11iAuthenticationMode, 'Invalid') bw.IEEE11iAuthenticationMode = 'PSKAuthentication' self.assertRaises(ValueError, bw.SetWPAAuthenticationMode, 'Invalid') bw.WPAAuthenticationMode = 'PSKAuthentication' def testSetBeaconType(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' bw.BasicEncryptionModes = 'None' # wsec 0 bw.WPAEncryptionModes = 'TKIPEncryption' # wsec 2 bw.WPAAuthenticationMode = 'PSKAuthentication' bw.IEEE11iEncryptionModes = 'AESEncryption' # wsec 4 bw.IEEE11iAuthenticationMode = 'PSKAuthentication' bw.BeaconType = 'None' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=0, sup_wpa=0) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BeaconType = 'Basic' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=0, sup_wpa=0) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BasicEncryptionModes = 'WEPEncryption' # wsec 1 bw.BeaconType = 'Basic' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=1, sup_wpa=0) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BasicAuthenticationMode = 'SharedAuthentication' bw.BasicEncryptionModes = 'WEPEncryption' # wsec 1 bw.BeaconType = 'Basic' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=1, sup_wpa=0) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BeaconType = 'WPA' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=2, wpa_auth=4) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BeaconType = '11i' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=4, wpa_auth=128) self.assertFalse(outlist) out.truncate() # NOTE(jnewlin): I do not believe we should support these beacon types # below. bw.StartTransaction() bw.BeaconType = 'BasicandWPA' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=2, wpa_auth=4) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BeaconType = 'Basicand11i' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=4, wpa_auth=128) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BeaconType = 'WPAand11i' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=4, wpa_auth=128) self.assertFalse(outlist) out.truncate() bw.StartTransaction() bw.BeaconType = 'BasicandWPAand11i' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wsec=4, wpa_auth=128) self.assertFalse(outlist) out.truncate() def testAuthenticationModes(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, wpa_auth=0) self.assertFalse(outlist) out.truncate() # Test WEP bw.StartTransaction() bw.BeaconType = 'Basic' bw.BasicAuthenticationMode = 'None' bw.BasicEncryptionModes = 'WEPEncryption' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, sup_wpa=0, wpa_auth=0, wsec=1) self.assertFalse(outlist) # Test WPA-TKIP bw.StartTransaction() bw.BeaconType = 'WPA' bw.WPAAuthenticationMode = 'PSKAuthentication' bw.WPAEncryptionModes = 'TKIPEncryption' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, sup_wpa=1, wpa_auth=4, wsec=2) self.assertFalse(outlist) out.truncate() # Test WPA2-AES bw.StartTransaction() bw.BeaconType = '11i' bw.IEEE11iAuthenticationMode = 'PSKAuthentication' bw.IEEE11iEncryptionModes = 'AESEncryption' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, sup_wpa=1, wpa_auth=128, wsec=4) self.assertFalse(outlist) out.truncate() def testWepKey(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.WEPKeyList[1].WEPKey = 'password1' bw.WEPKeyList[2].WEPKey = 'password2' bw.WEPKeyList[3].WEPKey = 'password3' bw.WEPKeyList[4].WEPKey = 'password4' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, rmwep=4, wsec=0) self.assertTrue(self.RmFromList(outlist, 'addwep 0 password1')) self.assertTrue(self.RmFromList(outlist, 'addwep 1 password2')) self.assertTrue(self.RmFromList(outlist, 'addwep 2 password3')) self.assertTrue(self.RmFromList(outlist, 'addwep 3 password4')) print outlist self.assertFalse(outlist) def testPreSharedKey(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.PreSharedKeyList[1].PreSharedKey = 'password1' bw.CommitTransaction() output = out.read() outlist = self.VerifyCommonWlCommands(output, rmwep=0, wsec=0) self.assertTrue(self.RmFromList(outlist, 'set_pmk password1')) self.assertFalse(outlist) def testStats(self): netdev.PROC_NET_DEV = 'testdata/brcmwifi/proc_net_dev' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') stats = bw.Stats stats.ValidateExports() # pylint: disable-msg=E1101 self.assertEqual(stats.BroadcastPacketsReceived, None) self.assertEqual(stats.BroadcastPacketsSent, None) self.assertEqual(stats.BytesReceived, '1') self.assertEqual(stats.BytesSent, '9') self.assertEqual(stats.DiscardPacketsReceived, '4') self.assertEqual(stats.DiscardPacketsSent, '11') self.assertEqual(stats.ErrorsReceived, '9') self.assertEqual(stats.ErrorsSent, '12') self.assertEqual(stats.MulticastPacketsReceived, '8') self.assertEqual(stats.MulticastPacketsSent, None) self.assertEqual(stats.PacketsReceived, '100') self.assertEqual(stats.PacketsSent, '10') self.assertEqual(stats.UnicastPacketsReceived, '92') self.assertEqual(stats.UnicastPacketsSent, '10') self.assertEqual(stats.UnknownProtoPacketsReceived, None) def testAssociatedDevice(self): brcmwifi.WL_EXE = 'testdata/brcmwifi/wlassociated' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') self.assertEqual(bw.TotalAssociations, 3) speeds = {'a0:b0:c0:00:00:01': '1', 'a0:b0:c0:00:00:02': '2', 'a0:b0:c0:00:00:03': '3'} auth = {'a0:b0:c0:00:00:01': True, 'a0:b0:c0:00:00:02': False, 'a0:b0:c0:00:00:03': True} seen = set() for ad in bw.AssociatedDeviceList.values(): ad.ValidateExports() mac = ad.AssociatedDeviceMACAddress.lower() self.assertEqual(ad.LastDataTransmitRate, speeds[mac]) self.assertEqual(ad.AssociatedDeviceAuthenticationState, auth[mac]) seen.add(mac) self.assertEqual(len(seen), 3) def testKeyPassphrase(self): netdev.PROC_NET_DEV = 'testdata/brcmwifi/proc_net_dev' bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.KeyPassphrase = 'testpassword' self.assertEqual(bw.KeyPassphrase, bw.PreSharedKeyList[1].KeyPassphrase) def testAutoChannel(self): (script, out) = self.MakeTestScript() brcmwifi.WL_EXE = script.name bw = brcmwifi.BrcmWifiWlanConfiguration('wifi0') bw.StartTransaction() bw.Enable = 'True' bw.RadioEnabled = 'True' bw.AutoChannelEnable = 'True' out.truncate() bw.CommitTransaction() output = out.read() out.close() # AutoChannel changes the order of the initial commands # slightly. outlist = [x for x in output.split('\n') if x] self.assertEqual(outlist[0], '-i wifi0 radio on') self.assertEqual(outlist[1], '-i wifi0 ap 1') self.assertEqual(outlist[2], '-i wifi0 down') self.assertTrue(self.RmFromList(outlist, 'spect 0')) self.assertTrue(self.RmFromList(outlist, 'mpc 0')) self.assertTrue(self.RmFromList(outlist, 'up')) self.assertTrue(self.RmFromList(outlist, 'ssid')) self.assertTrue(self.RmFromList(outlist, 'autochannel 1')) self.assertTrue(self.RmFromList(outlist, 'autochannel 2')) self.assertTrue(self.RmFromList(outlist, 'down')) self.assertTrue(self.RmFromList(outlist, 'mpc 1')) self.assertTrue(self.RmFromList(outlist, 'spect 1')) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for ManagementServer implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import copy import unittest import google3 import management_server class MockConfig(object): def __init__(self): pass class MockCpeManagementServer(object): def __init__(self): self.CWMPRetryIntervalMultiplier = 1 self.CWMPRetryMinimumWaitInterval = 2 self.ConnectionRequestPassword = 'ConnectPassword' self.ConnectionRequestUsername = 'ConnectUsername' self.ConnectionRequestURL = 'http://example.com/' self.DefaultActiveNotificationThrottle = 3 self.EnableCWMP = True self.ParameterKey = 'ParameterKey' self.Password = 'Password' self.PeriodicInformEnable = False self.PeriodicInformInterval = 4 self.PeriodicInformTime = 5 self.URL = 'http://example.com/' self.Username = 'Username' def StartTransaction(self): self.copy = copy.copy(self) def CommitTransaction(self): del self.copy def AbandonTransaction(self): for k,v in self.copy.__dict__.iteritems(): self.__dict__[k] = v del self.copy class ManagementServerTest(unittest.TestCase): """Tests for management_server.py.""" def testGetMgmt181(self): mgmt = MockCpeManagementServer() mgmt181 = management_server.ManagementServer181(mgmt) self.assertEqual(mgmt181.ParameterKey, mgmt.ParameterKey) self.assertEqual(mgmt181.EnableCWMP, mgmt.EnableCWMP) self.assertTrue(mgmt181.UpgradesManaged) def testGetMgmt98(self): mgmt = MockCpeManagementServer() mgmt98 = management_server.ManagementServer98(mgmt) self.assertEqual(mgmt98.ParameterKey, mgmt.ParameterKey) self.assertEqual(mgmt98.EnableCWMP, mgmt.EnableCWMP) self.assertTrue(mgmt98.UpgradesManaged) mgmt98.ValidateExports() def testSetMgmt181(self): mgmt = MockCpeManagementServer() mgmt181 = management_server.ManagementServer181(mgmt) self.assertEqual(mgmt.CWMPRetryIntervalMultiplier, 1) self.assertEqual(mgmt181.CWMPRetryIntervalMultiplier, 1) mgmt181.CWMPRetryIntervalMultiplier = 2 self.assertEqual(mgmt.CWMPRetryIntervalMultiplier, 2) self.assertEqual(mgmt181.CWMPRetryIntervalMultiplier, 2) mgmt181.ValidateExports() def testSetMgmt98(self): mgmt = MockCpeManagementServer() mgmt98 = management_server.ManagementServer98(mgmt) self.assertEqual(mgmt.CWMPRetryIntervalMultiplier, 1) self.assertEqual(mgmt98.CWMPRetryIntervalMultiplier, 1) mgmt98.CWMPRetryIntervalMultiplier = 2 self.assertEqual(mgmt.CWMPRetryIntervalMultiplier, 2) self.assertEqual(mgmt98.CWMPRetryIntervalMultiplier, 2) def testDelMgmt181(self): mgmt = MockCpeManagementServer() mgmt181 = management_server.ManagementServer181(mgmt) delattr(mgmt181, 'CWMPRetryIntervalMultiplier') self.assertFalse(hasattr(mgmt, 'CWMPRetryIntervalMultiplier')) def testDelMgmt98(self): mgmt = MockCpeManagementServer() mgmt98 = management_server.ManagementServer98(mgmt) delattr(mgmt98, 'CWMPRetryIntervalMultiplier') self.assertFalse(hasattr(mgmt, 'CWMPRetryIntervalMultiplier')) def TransactionTester(self, mgmt_server): mgmt_server.StartTransaction() mgmt_server.CommitTransaction() mgmt_server.StartTransaction() mgmt_server.AbandonTransaction() save_pass = mgmt_server.ConnectionRequestPassword save_user = mgmt_server.ConnectionRequestUsername mgmt_server.StartTransaction() mgmt_server.ConnectionRequestUsername = 'username' mgmt_server.ConnectionRequestPassword = 'pass' mgmt_server.AbandonTransaction() self.assertEqual(save_pass, mgmt_server.ConnectionRequestPassword) self.assertEqual(save_user, mgmt_server.ConnectionRequestUsername) mgmt_server.StartTransaction() mgmt_server.ConnectionRequestUsername = 'newname' mgmt_server.ConnectionRequestPassword = 'newpass' mgmt_server.CommitTransaction() self.assertEqual('newpass', mgmt_server.ConnectionRequestPassword) self.assertEqual('newname', mgmt_server.ConnectionRequestUsername) def testTransactions181(self): mgmt = MockCpeManagementServer() mgmt181 = management_server.ManagementServer181(mgmt) self.TransactionTester(mgmt181) def testTransactions98(self): mgmt = MockCpeManagementServer() mgmt98 = management_server.ManagementServer98(mgmt) self.TransactionTester(mgmt98) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementations of platform-independant tr-98/181 WLAN objects.""" __author__ = 'dgentry@google.com (Denton Gentry)' import pbkdf2 import tr.tr098_v1_4 def ContiguousRanges(seq): """Given an integer sequence, return contiguous ranges. This is expected to be useful for the tr-98 WLANConfig PossibleChannels parameter. Args: seq: a sequence of integers, like [1,2,3,4,5] Returns: A string of the collapsed ranges. Given [1,2,3,4,5] as input, will return '1-5' """ in_range = False prev = seq[0] output = list(str(seq[0])) for item in seq[1:]: if item == prev + 1: if not in_range: in_range = True output.append('-') else: if in_range: output.append(str(prev)) output.append(',' + str(item)) in_range = False prev = item if in_range: output.append(str(prev)) return ''.join(output) class PreSharedKey98(tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice.LANDevice.WLANConfiguration.PreSharedKey): """InternetGatewayDevice.WLANConfiguration.{i}.PreSharedKey.{i}.""" def __init__(self): super(PreSharedKey98, self).__init__() self.Unexport('Alias') self.key = None self.passphrase = None self.key_pbkdf2 = None self.salt = None self.AssociatedDeviceMACAddress = None def GetKey(self, salt): """Return the key to program into the Wifi chipset. Args: salt: Per WPA2 spec, the SSID is used as the salt. Returns: The key as a hex string, or None if no key. """ if self.key is not None: return self.key if self.key_pbkdf2 is None or salt != self.salt: self.salt = salt self.key_pbkdf2 = self._GeneratePBKDF2(salt) if self.key_pbkdf2 is not None: return self.key_pbkdf2 return None def _GeneratePBKDF2(self, salt): """Compute WPA2 key from a passphrase.""" if self.passphrase is None: return None return pbkdf2.pbkdf2_hex(self.passphrase, salt=salt, iterations=4096, keylen=32) def SetPreSharedKey(self, value): self.key = value self.key_pbkdf2 = None def GetPreSharedKey(self): return self.key PreSharedKey = property( GetPreSharedKey, SetPreSharedKey, None, 'WLANConfiguration.{i}.PreSharedKey.{i}.PreSharedKey') def SetKeyPassphrase(self, value): self.passphrase = value self.key = None self.key_pbkdf2 = None def GetKeyPassphrase(self): return self.passphrase KeyPassphrase = property( GetKeyPassphrase, SetKeyPassphrase, None, 'WLANConfiguration.{i}.PreSharedKey.{i}.KeyPassphrase') class WEPKey98(tr.tr098_v1_4.InternetGatewayDevice_v1_10.InternetGatewayDevice.LANDevice.WLANConfiguration.WEPKey): """InternetGatewayDevice.WLANConfiguration.{i}.WEPKey.{i}.""" def __init__(self): super(WEPKey98, self).__init__() self.Unexport('Alias') self.WEPKey = None def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for tr-181 Ethernet.* implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import unittest import google3 import tr.tr181_v2_2 as tr181 import ethernet import netdev BASEETHERNET = tr181.Device_v2_2.Device.Ethernet class EthernetTest(unittest.TestCase): """Tests for ethernet.py.""" def setUp(self): self.old_PROC_NET_DEV = netdev.PROC_NET_DEV self.old_PYNETIFCONF = ethernet.PYNETIFCONF def tearDown(self): netdev.PROC_NET_DEV = self.old_PROC_NET_DEV ethernet.PYNETIFCONF = self.old_PYNETIFCONF def testInterfaceStatsGood(self): netdev.PROC_NET_DEV = 'testdata/ethernet/net_dev' eth = ethernet.EthernetInterfaceStatsLinux26('foo0') eth.ValidateExports() self.assertEqual(eth.BroadcastPacketsReceived, None) self.assertEqual(eth.BroadcastPacketsSent, None) self.assertEqual(eth.BytesReceived, '1') self.assertEqual(eth.BytesSent, '9') self.assertEqual(eth.DiscardPacketsReceived, '4') self.assertEqual(eth.DiscardPacketsSent, '11') self.assertEqual(eth.ErrorsReceived, '9') self.assertEqual(eth.ErrorsSent, '12') self.assertEqual(eth.MulticastPacketsReceived, '8') self.assertEqual(eth.MulticastPacketsSent, None) self.assertEqual(eth.PacketsReceived, '100') self.assertEqual(eth.PacketsSent, '10') self.assertEqual(eth.UnicastPacketsReceived, '92') self.assertEqual(eth.UnicastPacketsSent, '10') self.assertEqual(eth.UnknownProtoPacketsReceived, None) def testInterfaceStatsNonexistent(self): netdev.PROC_NET_DEV = 'testdata/ethernet/net_dev' eth = ethernet.EthernetInterfaceStatsLinux26('doesnotexist0') exception_raised = False try: eth.ErrorsReceived except AttributeError: exception_raised = True self.assertTrue(exception_raised) def _CheckEthernetInterfaceParameters(self, ifname, upstream, eth, pynet): self.assertEqual(eth.DuplexMode, 'Auto') self.assertEqual(eth.Enable, True) self.assertEqual(eth.LastChange, '0001-01-01T00:00:00Z') self.assertFalse(eth.LowerLayers) self.assertEqual(eth.MACAddress, pynet.v_mac) self.assertEqual(eth.MaxBitRate, -1) self.assertEqual(eth.Name, ifname) self.assertEqual(eth.Upstream, upstream) self.assertEqual(eth.X_CATAWAMPUS_ORG_ActualBitRate, pynet.v_speed) self.assertEqual(eth.X_CATAWAMPUS_ORG_ActualDuplexMode, 'Full' if pynet.v_duplex else 'Half') def testValidateExports(self): ethernet.PYNETIFCONF = MockPynet netdev.PROC_NET_DEV = 'testdata/ethernet/net_dev' eth = ethernet.EthernetInterfaceLinux26('foo0') eth.ValidateExports() def testInterfaceGood(self): ethernet.PYNETIFCONF = MockPynet netdev.PROC_NET_DEV = 'testdata/ethernet/net_dev' upstream = False eth = ethernet.EthernetInterfaceLinux26('foo0') self._CheckEthernetInterfaceParameters('foo0', upstream, eth, MockPynet) eth = ethernet.EthernetInterfaceLinux26('foo0') self._CheckEthernetInterfaceParameters('foo0', upstream, eth, MockPynet) MockPynet.v_is_up = False eth = ethernet.EthernetInterfaceLinux26('foo0') self._CheckEthernetInterfaceParameters('foo0', upstream, eth, MockPynet) MockPynet.v_duplex = False eth = ethernet.EthernetInterfaceLinux26('foo0') self._CheckEthernetInterfaceParameters('foo0', upstream, eth, MockPynet) MockPynet.v_auto = False eth = ethernet.EthernetInterfaceLinux26('foo0') self._CheckEthernetInterfaceParameters('foo0', upstream, eth, MockPynet) MockPynet.v_link_up = False eth = ethernet.EthernetInterfaceLinux26('foo0') self._CheckEthernetInterfaceParameters('foo0', upstream, eth, MockPynet) class MockPynet(object): v_is_up = True v_mac = '00:11:22:33:44:55' v_speed = 1000 v_duplex = True v_auto = True v_link_up = True def __init__(self, ifname): self.ifname = ifname def is_up(self): return self.v_is_up def get_mac(self): return self.v_mac def get_link_info(self): return (self.v_speed, self.v_duplex, self.v_auto, self.v_link_up) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 """Implementation of tr-181 Device.Bridging hierarchy of objects. Handles the Device.Bridging portion of TR-181, as described in http://www.broadband-forum.org/cwmp/tr-181-2-2-0.html """ __author__ = 'dgentry@google.com (Denton Gentry)' import tr.core import tr.tr181_v2_2 BASEBRIDGE = tr.tr181_v2_2.Device_v2_2.Device.Bridging class BridgingState(object): def __init__(self, brname): self.brname = brname class Bridging(BASEBRIDGE): def __init__(self): BASEBRIDGE.__init__(self) self._Bridges = {} self.MaxBridgeEntries = 32 self.MaxDBridgeEntries = 32 self.MaxQBridgeEntries = 32 self.MaxVLANEntries = 4096 self.MaxFilterEntries = 0 # TODO(dgentry) figure this out @property def BridgeNumberOfEntries(self): return len(self.BridgeList) @property def FilterNumberOfEntries(self): return len(self.FilterList) def main(): pass if __name__ == '__main__': main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for storage.py implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import collections import unittest import google3 import storage statvfsstruct = collections.namedtuple( 'statvfs', ('f_bsize f_frsize f_blocks f_bfree f_bavail f_files f_ffree ' 'f_favail f_flag f_namemax')) test_mtdpath = '' def OsStatVfs(rootpath): teststatvfs = dict() teststatvfs['/fakepath'] = statvfsstruct( f_bsize=4096, f_frsize=512, f_blocks=1024, f_bfree=512, f_bavail=498, f_files=1099, f_ffree=1092, f_favail=1050, f_flag=0, f_namemax=256) teststatvfs['/'] = statvfsstruct( f_bsize=4096, f_frsize=512, f_blocks=2048, f_bfree=100, f_bavail=120, f_files=2000, f_ffree=1000, f_favail=850, f_flag=0, f_namemax=256) teststatvfs['/tmp'] = statvfsstruct( f_bsize=8192, f_frsize=512, f_blocks=4096, f_bfree=1002, f_bavail=1202, f_files=9000, f_ffree=5000, f_favail=4000, f_flag=0, f_namemax=256) teststatvfs['/foo'] = statvfsstruct( f_bsize=2048, f_frsize=256, f_blocks=8192, f_bfree=5017, f_bavail=3766, f_files=6000, f_ffree=4000, f_favail=3000, f_flag=0x0001, f_namemax=256) return teststatvfs[rootpath] def GetMtdStats(mtdpath): global test_mtdpath test_mtdpath = mtdpath return storage.MtdEccStats(corrected=10, failed=20, badblocks=30, bbtblocks=40) class StorageTest(unittest.TestCase): def setUp(self): storage.STATVFS = OsStatVfs storage.GETMTDSTATS = GetMtdStats self.old_PROC_FILESYSTEMS = storage.PROC_FILESYSTEMS self.old_PROC_MOUNTS = storage.PROC_MOUNTS self.old_SMARTCTL = storage.SMARTCTL self.old_SYS_BLOCK = storage.SYS_BLOCK self.old_SYS_UBI = storage.SYS_UBI storage.SMARTCTL = 'testdata/storage/smartctl' storage.SYS_UBI = 'testdata/storage/sys/class' def tearDown(self): storage.PROC_FILESYSTEMS = self.old_PROC_FILESYSTEMS storage.PROC_MOUNTS = self.old_PROC_MOUNTS storage.SMARTCTL = self.old_SMARTCTL storage.SYS_BLOCK = self.old_SYS_BLOCK storage.SYS_UBI = self.old_SYS_UBI def testValidateExports(self): storage.PROC_FILESYSTEMS = 'testdata/storage/proc.filesystems' storage.PROC_MOUNTS = 'testdata/storage/proc.mounts' storage.SYS_BLOCK = 'testdata/storage/sys/block' service = storage.StorageServiceLinux26() service.ValidateExports() stor = storage.LogicalVolumeLinux26('/fakepath', 'fstype') stor.ValidateExports() pm = storage.PhysicalMediumDiskLinux26('sda') pm.ValidateExports() def testLogicalVolumeCapacity(self): stor = storage.LogicalVolumeLinux26('/fakepath', 'fstype') teststatvfs = OsStatVfs('/fakepath') expected = teststatvfs.f_bsize * teststatvfs.f_blocks / 1024 / 1024 self.assertEqual(stor.Capacity, expected) def testUsedSpace(self): stor = storage.LogicalVolumeLinux26('/fakepath', 'fstype') teststatvfs = OsStatVfs('/fakepath') used = (teststatvfs.f_blocks - teststatvfs.f_bavail) * teststatvfs.f_bsize self.assertEqual(stor.UsedSpace, used / 1024 / 1024) def testLogicalVolumeThresholdReached(self): stor = storage.LogicalVolumeLinux26('/fakepath', 'fstype') stor.ThresholdLimit = 1 self.assertFalse(stor.ThresholdReached) stor.ThresholdLimit = 4 self.assertTrue(stor.ThresholdReached) def testLogicalVolumeList(self): storage.PROC_MOUNTS = 'testdata/storage/proc.mounts' service = storage.StorageServiceLinux26() volumes = service.LogicalVolumeList self.assertEqual(len(volumes), 3) expectedFs = {'/': 'X_CATAWAMPUS-ORG_squashfs', '/foo': 'X_CATAWAMPUS-ORG_ubifs', '/tmp': 'X_CATAWAMPUS-ORG_tmpfs'} expectedRo = {'/': False, '/foo': True, '/tmp': False} for vol in volumes.values(): t = OsStatVfs(vol.Name) self.assertEqual(vol.Status, 'Online') self.assertTrue(vol.Enable) self.assertEqual(vol.FileSystem, expectedFs[vol.Name]) self.assertEqual(vol.Capacity, t.f_bsize * t.f_blocks / 1024 / 1024) expected = t.f_bsize * (t.f_blocks - t.f_bavail) / 1024 / 1024 self.assertEqual(vol.UsedSpace, expected) self.assertEqual(vol.X_CATAWAMPUS_ORG_ReadOnly, expectedRo[vol.Name]) def testCapabilitiesNone(self): storage.PROC_FILESYSTEMS = 'testdata/storage/proc.filesystems' cap = storage.CapabilitiesNoneLinux26() cap.ValidateExports() self.assertFalse(cap.FTPCapable) self.assertFalse(cap.HTTPCapable) self.assertFalse(cap.HTTPSCapable) self.assertFalse(cap.HTTPWritable) self.assertFalse(cap.SFTPCapable) self.assertEqual(cap.SupportedNetworkProtocols, '') self.assertEqual(cap.SupportedRaidTypes, '') self.assertFalse(cap.VolumeEncryptionCapable) def testCapabilitiesNoneFsTypes(self): storage.PROC_FILESYSTEMS = 'testdata/storage/proc.filesystems' cap = storage.CapabilitiesNoneLinux26() self.assertEqual(cap.SupportedFileSystemTypes, 'ext2,ext3,ext4,FAT32,X_CATAWAMPUS-ORG_iso9660,' 'X_CATAWAMPUS-ORG_squashfs,X_CATAWAMPUS-ORG_udf') def testPhysicalMediumName(self): pm = storage.PhysicalMediumDiskLinux26('sda') self.assertEqual(pm.Name, 'sda') pm.Name = 'sdb' self.assertEqual(pm.Name, 'sdb') def testPhysicalMediumFields(self): storage.SYS_BLOCK = 'testdata/storage/sys/block' pm = storage.PhysicalMediumDiskLinux26('sda') self.assertEqual(pm.Vendor, 'vendor_name') self.assertEqual(pm.Model, 'model_name') self.assertEqual(pm.SerialNumber, 'serial_number') self.assertEqual(pm.FirmwareVersion, 'firmware_version') self.assertTrue(pm.SMARTCapable) self.assertEqual(pm.Health, 'OK') self.assertFalse(pm.Removable) def testNotSmartCapable(self): storage.SMARTCTL = 'testdata/storage/smartctl_disabled' storage.SYS_BLOCK = 'testdata/storage/sys/block' pm = storage.PhysicalMediumDiskLinux26('sda') self.assertFalse(pm.SMARTCapable) def testHealthFailing(self): storage.SMARTCTL = 'testdata/storage/smartctl_healthfail' storage.SYS_BLOCK = 'testdata/storage/sys/block' pm = storage.PhysicalMediumDiskLinux26('sda') self.assertEqual(pm.Health, 'Failing') def testHealthError(self): storage.SMARTCTL = 'testdata/storage/smartctl_healtherr' storage.SYS_BLOCK = 'testdata/storage/sys/block' pm = storage.PhysicalMediumDiskLinux26('sda') self.assertEqual(pm.Health, 'Error') def testPhysicalMediumVendorATA(self): storage.SYS_BLOCK = 'testdata/storage/sys/block_ATA' pm = storage.PhysicalMediumDiskLinux26('sda') # vendor 'ATA' is suppressed, as it is useless self.assertEqual(pm.Vendor, '') def testPhysicalMediumCapacity(self): storage.SYS_BLOCK = 'testdata/storage/sys/block' pm = storage.PhysicalMediumDiskLinux26('sda') self.assertEqual(pm.Capacity, 512) def testPhysicalMediumConnType(self): storage.SYS_BLOCK = 'testdata/storage/sys/block' pm = storage.PhysicalMediumDiskLinux26('sda', conn_type='IDE') self.assertEqual(pm.ConnectionType, 'IDE') self.assertRaises(AssertionError, storage.PhysicalMediumDiskLinux26, 'sda', conn_type='NotValid') def testPhysicalMediumHotSwappable(self): storage.SYS_BLOCK = 'testdata/storage/sys/block' pm = storage.PhysicalMediumDiskLinux26('sda') self.assertFalse(pm.HotSwappable) storage.SYS_BLOCK = 'testdata/storage/sys/blockRemovable' self.assertTrue(pm.HotSwappable) def testFlashMedium(self): fm = storage.FlashMediumUbiLinux26('ubi2') fm.ValidateExports() self.assertEqual(fm.BadEraseBlocks, 4) self.assertEqual(fm.CorrectedErrors, 10) self.assertEqual(fm.EraseBlockSize, 1040384) self.assertEqual(fm.IOSize, 4096) self.assertEqual(fm.MaxEraseCount, 3) self.assertEqual(fm.Name, 'ubi2') self.assertEqual(fm.ReservedEraseBlocks, 10) self.assertEqual(fm.TotalEraseBlocks, 508) self.assertEqual(fm.UncorrectedErrors, 20) def testFlashSubVolume(self): sv = storage.FlashSubVolUbiLinux26('ubi2_0') sv.ValidateExports() self.assertEqual(sv.DataMBytes, 370) self.assertEqual(sv.Name, 'subvol0') self.assertEqual(sv.Status, 'OK') sv = storage.FlashSubVolUbiLinux26('ubi2_1') sv.ValidateExports() self.assertEqual(sv.DataMBytes, 56) self.assertEqual(sv.Name, 'subvol1') self.assertEqual(sv.Status, 'Corrupted') if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for tr-181 Device.MoCA.* implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import unittest import google3 import brcmmoca import netdev class MocaTest(unittest.TestCase): """Tests for brcmmoca.py.""" def setUp(self): self.old_MOCACTL = brcmmoca.MOCACTL self.old_PYNETIFCONF = brcmmoca.PYNETIFCONF self.old_PROC_NET_DEV = netdev.PROC_NET_DEV def tearDown(self): brcmmoca.MOCACTL = self.old_MOCACTL brcmmoca.PYNETIFCONF = self.old_PYNETIFCONF netdev.PROC_NET_DEV = self.old_PROC_NET_DEV def testMocaInterfaceStatsGood(self): netdev.PROC_NET_DEV = 'testdata/brcmmoca/proc/net/dev' moca = brcmmoca.BrcmMocaInterfaceStatsLinux26('foo0') moca.ValidateExports() self.assertEqual(moca.BroadcastPacketsReceived, None) self.assertEqual(moca.BroadcastPacketsSent, None) self.assertEqual(moca.BytesReceived, '1') self.assertEqual(moca.BytesSent, '9') self.assertEqual(moca.DiscardPacketsReceived, '4') self.assertEqual(moca.DiscardPacketsSent, '11') self.assertEqual(moca.ErrorsReceived, '9') self.assertEqual(moca.ErrorsSent, '12') self.assertEqual(moca.MulticastPacketsReceived, '8') self.assertEqual(moca.MulticastPacketsSent, None) self.assertEqual(moca.PacketsReceived, '100') self.assertEqual(moca.PacketsSent, '10') self.assertEqual(moca.UnicastPacketsReceived, '92') self.assertEqual(moca.UnicastPacketsSent, '10') self.assertEqual(moca.UnknownProtoPacketsReceived, None) def testMocaInterfaceStatsNonexistent(self): netdev.PROC_NET_DEV = 'testdata/brcmmoca/proc/net/dev' moca = brcmmoca.BrcmMocaInterfaceStatsLinux26('doesnotexist0') exception_raised = False try: moca.ErrorsReceived except AttributeError: exception_raised = True self.assertTrue(exception_raised) def testMocaInterface(self): brcmmoca.PYNETIFCONF = MockPynet brcmmoca.MOCACTL = 'testdata/brcmmoca/mocactl' netdev.PROC_NET_DEV = 'testdata/brcmmoca/proc/net/dev' moca = brcmmoca.BrcmMocaInterface(ifname='foo0', upstream=False) moca.ValidateExports() self.assertEqual(moca.Name, 'foo0') self.assertEqual(moca.LowerLayers, '') self.assertFalse(moca.Upstream) self.assertEqual(moca.MACAddress, MockPynet.v_mac) moca = brcmmoca.BrcmMocaInterface(ifname='foo0', upstream=True) self.assertTrue(moca.Upstream) MockPynet.v_is_up = True MockPynet.v_link_up = True self.assertEqual(moca.Status, 'Up') MockPynet.v_link_up = False self.assertEqual(moca.Status, 'Dormant') MockPynet.v_is_up = False self.assertEqual(moca.Status, 'Down') self.assertEqual(moca.FirmwareVersion, '5.6.789') self.assertEqual(moca.HighestVersion, '1.1') self.assertEqual(moca.CurrentVersion, '1.1') self.assertEqual(moca.BackupNC, '5') self.assertFalse(moca.PrivacyEnabled) self.assertEqual(moca.CurrentOperFreq, 999) self.assertEqual(moca.LastOperFreq, 899) self.assertEqual(moca.NetworkCoordinator, 1) self.assertEqual(moca.NodeID, 2) self.assertTrue(moca.QAM256Capable) self.assertEqual(moca.PacketAggregationCapability, 10) def testMocaInterfaceAlt(self): brcmmoca.PYNETIFCONF = MockPynet brcmmoca.MOCACTL = 'testdata/brcmmoca/mocactl_alt' moca = brcmmoca.BrcmMocaInterface(ifname='foo0', upstream=False) self.assertEqual(moca.HighestVersion, '1.0') self.assertEqual(moca.CurrentVersion, '2.0') self.assertEqual(moca.BackupNC, '2') self.assertTrue(moca.PrivacyEnabled) self.assertFalse(moca.QAM256Capable) self.assertEqual(moca.PacketAggregationCapability, 7) def testMocaInterfaceMocaCtlFails(self): brcmmoca.PYNETIFCONF = MockPynet brcmmoca.MOCACTL = 'testdata/brcmmoca/mocactl_fail' moca = brcmmoca.BrcmMocaInterface(ifname='foo0', upstream=False) self.assertEqual(moca.FirmwareVersion, '0') self.assertEqual(moca.HighestVersion, '0.0') self.assertEqual(moca.CurrentVersion, '0.0') self.assertEqual(moca.BackupNC, '') self.assertFalse(moca.PrivacyEnabled) self.assertFalse(moca.QAM256Capable) self.assertEqual(moca.PacketAggregationCapability, 0) def testLastChange(self): brcmmoca.PYNETIFCONF = MockPynet moca = brcmmoca.BrcmMocaInterface(ifname='foo0', upstream=False) brcmmoca.MOCACTL = 'testdata/brcmmoca/mocactl_up1' self.assertEqual(moca.LastChange, 6090) brcmmoca.MOCACTL = 'testdata/brcmmoca/mocactl_up2' self.assertEqual(moca.LastChange, 119728800) def testAssociatedDevice(self): brcmmoca.MOCACTL = 'testdata/brcmmoca/mocactl' moca = brcmmoca.BrcmMocaInterface(ifname='foo0', upstream=False) self.assertEqual(2, moca.AssociatedDeviceNumberOfEntries) ad = moca.GetAssociatedDevice(0) ad.ValidateExports() self.assertEqual(ad.MACAddress, '00:01:00:11:23:33') self.assertEqual(ad.NodeID, 0) self.assertEqual(ad.PreferredNC, False) self.assertEqual(ad.PHYTxRate, 293) self.assertEqual(ad.PHYRxRate, 291) self.assertEqual(ad.TxPowerControlReduction, 3) self.assertEqual(ad.RxPowerLevel, 4) self.assertEqual(ad.TxBcastRate, 290) self.assertEqual(ad.RxBcastPowerLevel, 2) self.assertEqual(ad.TxPackets, 1) self.assertEqual(ad.RxPackets, 2) self.assertEqual(ad.RxErroredAndMissedPackets, 11) self.assertEqual(ad.QAM256Capable, True) self.assertEqual(ad.PacketAggregationCapability, 10) self.assertEqual(ad.RxSNR, 39) ad = moca.GetAssociatedDevice(1) ad.ValidateExports() self.assertEqual(ad.MACAddress, '00:01:00:11:23:44') self.assertEqual(ad.NodeID, 1) self.assertEqual(ad.PreferredNC, True) self.assertEqual(ad.PHYTxRate, 283) self.assertEqual(ad.PHYRxRate, 281) self.assertEqual(ad.TxPowerControlReduction, 2) self.assertEqual(ad.RxPowerLevel, 3) self.assertEqual(ad.TxBcastRate, 280) self.assertEqual(ad.RxBcastPowerLevel, 1) self.assertEqual(ad.TxPackets, 7) self.assertEqual(ad.RxPackets, 8) self.assertEqual(ad.RxErroredAndMissedPackets, 23) self.assertEqual(ad.QAM256Capable, False) self.assertEqual(ad.PacketAggregationCapability, 7) self.assertEqual(ad.RxSNR, 38) class MockPynet(object): v_is_up = True v_mac = '00:11:22:33:44:55' v_speed = 1000 v_duplex = True v_auto = True v_link_up = True def __init__(self, ifname): self.ifname = ifname def is_up(self): return self.v_is_up def get_mac(self): return self.v_mac def get_link_info(self): return (self.v_speed, self.v_duplex, self.v_auto, self.v_link_up) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # unittest requires method names starting in 'test' #pylint: disable-msg=C6409 """Unit tests for netdev.py implementation.""" __author__ = 'dgentry@google.com (Denton Gentry)' import unittest import google3 import netdev class NetdevTest(unittest.TestCase): """Tests for netdev.py.""" def setUp(self): self._old_PROC_NET_DEV = netdev.PROC_NET_DEV def tearDown(self): netdev.PROC_NET_DEV = self._old_PROC_NET_DEV def testInterfaceStatsGood(self): netdev.PROC_NET_DEV = 'testdata/ethernet/net_dev' eth = netdev.NetdevStatsLinux26(ifname='foo0') self.assertEqual(eth.BroadcastPacketsReceived, None) self.assertEqual(eth.BroadcastPacketsSent, None) self.assertEqual(eth.BytesReceived, '1') self.assertEqual(eth.BytesSent, '9') self.assertEqual(eth.DiscardPacketsReceived, '4') self.assertEqual(eth.DiscardPacketsSent, '11') self.assertEqual(eth.ErrorsReceived, '9') self.assertEqual(eth.ErrorsSent, '12') self.assertEqual(eth.MulticastPacketsReceived, '8') self.assertEqual(eth.MulticastPacketsSent, None) self.assertEqual(eth.PacketsReceived, '100') self.assertEqual(eth.PacketsSent, '10') self.assertEqual(eth.UnicastPacketsReceived, '92') self.assertEqual(eth.UnicastPacketsSent, '10') self.assertEqual(eth.UnknownProtoPacketsReceived, None) def testInterfaceStatsReal(self): # A test using a /proc/net/dev line taken from a running Linux 2.6.32 # system. Most of the fields are zero, so we exercise the other handling # using the foo0 fake data instead. netdev.PROC_NET_DEV = 'testdata/ethernet/net_dev' eth = netdev.NetdevStatsLinux26('eth0') self.assertEqual(eth.BroadcastPacketsReceived, None) self.assertEqual(eth.BroadcastPacketsSent, None) self.assertEqual(eth.BytesReceived, '21052761139') self.assertEqual(eth.BytesSent, '10372833035') self.assertEqual(eth.DiscardPacketsReceived, '0') self.assertEqual(eth.DiscardPacketsSent, '0') self.assertEqual(eth.ErrorsReceived, '0') self.assertEqual(eth.ErrorsSent, '0') self.assertEqual(eth.MulticastPacketsReceived, '0') self.assertEqual(eth.MulticastPacketsSent, None) self.assertEqual(eth.PacketsReceived, '91456760') self.assertEqual(eth.PacketsSent, '80960002') self.assertEqual(eth.UnicastPacketsReceived, '91456760') self.assertEqual(eth.UnicastPacketsSent, '80960002') self.assertEqual(eth.UnknownProtoPacketsReceived, None) if __name__ == '__main__': unittest.main()
Python
#!/usr/bin/python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 #pylint: disable-msg=W0404 # """An implementation of Device.IP.Diagnostics.TraceRoute.""" __author__ = 'apenwarr@google.com (Avery Pennarun)' import os import re import subprocess import sys import google3 import tr.core import tr.mainloop import tr.tr181_v2_2 BASE_TRACEROUTE = tr.tr181_v2_2.Device_v2_2.Device.IP.Diagnostics.TraceRoute MIN_PACKET_SIZE = 52 # from MacOS; Linux can apparently go smaller? class State(object): """Possible values for Device.IP.Diagnostics.TraceRoute.DiagnosticsState.""" NONE = 'None' REQUESTED = 'Requested' COMPLETE = 'Complete' ERROR_CANNOT_RESOLVE_HOSTNAME = 'Error_CannotResolveHostName' ERROR_MAX_HOP_COUNT_EXCEEDED = 'Error_MaxHopCountExceeded' class TraceRoute(BASE_TRACEROUTE): """Implementation of the TraceRoute object from TR-181.""" def __init__(self, loop): BASE_TRACEROUTE.__init__(self) self.loop = loop self.subproc = None self.error = None self.buffer = '' self.Host = None self.NumberOfTries = 3 self.Timeout = 5000 # milliseconds self.DataBlockSize = 38 self.MaxHopCount = 30 self.ResponseTime = None self.RouteHopsList = {} @property def Interface(self): # not implemented return None @property def DSCP(self): # not implemented return None @property def RouteHopsNumberOfEntries(self): return len(self.RouteHopsList) def _ClearHops(self): self.RouteHopsList = {} def _AddHop(self, hop, ipaddr, hostname, icmp_error, rttimes): print 'addhop: %r %r %r %r' % (hostname, ipaddr, icmp_error, rttimes) self.RouteHopsList[int(hop)] = self.RouteHops(Host=hostname, HostAddress=ipaddr, ErrorCode=icmp_error, RTTimes=rttimes) if rttimes: self.ResponseTime = sum(rttimes)/len(rttimes) if int(hop) >= int(self.MaxHopCount): self.error = State.ERROR_MAX_HOP_COUNT_EXCEEDED def _GetState(self): if self.subproc: return State.REQUESTED elif self.error: return self.error elif self.RouteHopsList: return State.COMPLETE else: return State.NONE def _SetState(self, value): if value != State.REQUESTED: raise Exception('DiagnosticsState can only be set to "Requested"') self._StartProc() #pylint: disable-msg=W1001 DiagnosticsState = property(_GetState, _SetState) def _EndProc(self): print 'traceroute finished.' if self.subproc: self.loop.ioloop.remove_handler(self.subproc.stdout.fileno()) if self.subproc.poll() is None: self.subproc.kill() rv = self.subproc.poll() print 'traceroute: return code was %d' % rv if rv == 2 or not self.RouteHopsList: self.error = State.ERROR_CANNOT_RESOLVE_HOSTNAME self.subproc = None def _StartProc(self): self._EndProc() self._ClearHops() self.error = None print 'traceroute starting.' if not self.Host: raise Exception('TraceRoute.Host is not set') if ':' in self.Host: # IPv6 argv_base = ['traceroute6'] if sys.platform == 'darwin': argv_base += ['-l'] # tell MacOS traceroute6 to include IP addr else: # assume IPv4 argv_base = ['traceroute'] argv = argv_base + ['-m', '%d' % int(self.MaxHopCount), '-q', '%d' % int(self.NumberOfTries), '-w', '%d' % (int(self.Timeout)/1000.0), self.Host, '%d' % max(MIN_PACKET_SIZE, int(self.DataBlockSize))] print ' %r' % argv self.subproc = subprocess.Popen(argv, stdout=subprocess.PIPE) self.loop.ioloop.add_handler(self.subproc.stdout.fileno(), self._GotData, self.loop.ioloop.READ) #pylint: disable-msg=W0613 def _GotData(self, fd, events): data = os.read(fd, 4096) if not data: self._EndProc() else: self.buffer += data while '\n' in self.buffer: before, after = self.buffer.split('\n', 1) self.buffer = after self._GotLine(before) def _GotLine(self, line): # TODO(apenwarr): find out how traceroute reports host-unreachable/etc # TODO(apenwarr): check that traceroute output is same on OpenWRT print 'traceroute line: %r' % (line,) g = re.match(r'^\s*(\d+)\s+(\S+) \(([\d:.]+)\)((\s+[\d.]+ ms)+)', line) if g: hop = g.group(1) hostname = g.group(2) ipaddr = g.group(3) times = g.group(4) timelist = re.findall(r'\s+([\d.]+) ms', times) self._AddHop(hop, ipaddr, hostname, icmp_error=0, rttimes=[int(float(t)) for t in timelist]) g = re.match(r'^\s*(\d+)\s+\* \* \*', line) if g: hop = g.group(1) self._AddHop(hop, None, '*', icmp_error=0, rttimes=[]) if __name__ == '__main__': print tr.core.DumpSchema(TraceRoute(None))
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TR-069 has mandatory attribute names that don't comply with policy #pylint: disable-msg=C6409 #pylint: disable-msg=W0404 # """The Device Model root, allowing specific platforms to populate it.""" __author__ = 'dgentry@google.com (Denton Gentry)' import google3 import dm.catawampus import dm.management_server import tr.core def _RecursiveImport(name): return __import__(name, fromlist=['']) class DeviceModelRoot(tr.core.Exporter): """A class to hold the device models.""" def __init__(self, loop, platform): tr.core.Exporter.__init__(self) if platform: self.device = _RecursiveImport('platform.%s.device' % platform) (params, objects) = self.device.PlatformInit(name=platform, device_model_root=self) else: (params, objects) = (list(), list()) self.X_CATAWAMPUS_ORG_CATAWAMPUS = dm.catawampus.CatawampusDm() objects.append('X_CATAWAMPUS-ORG_CATAWAMPUS') self.Export(params=params, objects=objects) def get_platform_config(self, ioloop): """Return the platform_config.py object for this platform.""" return self.device.PlatformConfig(ioloop=ioloop) def add_management_server(self, mgmt): # tr-181 Device.ManagementServer try: ms181 = self.GetExport('Device') ms181.ManagementServer = dm.management_server.ManagementServer181(mgmt) except (AttributeError, KeyError): pass # no tr-181 for this platform # tr-98 InternetGatewayDevice.ManagementServer try: ms98 = self.GetExport('InternetGatewayDevice') ms98.ManagementServer = dm.management_server.ManagementServer98(mgmt) except (AttributeError, KeyError): pass # no tr-98 for this platform def configure_tr157(self, cpe): """Adds the cpe and root objects to the tr157 periodic stat object.""" BASE157PS_IGD = 'InternetGatewayDevice.PeriodicStatistics' tr157_object = None try: tr157_object = self.GetExport(BASE157PS_IGD) tr157_object.SetCpe(cpe) tr157_object.SetRoot(self) except (AttributeError, KeyError): pass # no tr-157 object on the InternetGatewayDevice. # Check on the Device object. BASE157PS_DEV = 'Device.PeriodicStatistics' try: tr157_object = self.GetExport(BASE157PS_DEV) tr157_object.SetCpe(cpe) tr157_object.SetRoot(self) except (AttributeError, KeyError): pass # no tr-157 object found on the Device object.
Python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # """Platform-specific information which the rest of Catawampus needs.""" __author__ = 'dgentry@google.com (Denton Gentry)' import abc class PlatformConfigMeta(object): """Class to provide platform-specific information like directory locations. Each platform is expected to subclass PlatformMeta and supply concrete implementations of all methods. We use a Python Abstract Base Class to protect against future versions. If we add fields to this class, any existing platform implementations will be prompted to add implementations (because they will fail to startup when their PlatformMeta fails to instantiate). """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def ConfigDir(self): """Directory where configs and download metadata should be stored. This directory needs to persist its contents across reboots. It will store configs of a few tens to hundreds of kilobytes, and metadata about a small number of active downloads of less than one Kbyte each. """ return None @abc.abstractmethod def DownloadDir(self): """Directory where downloaded files should be stored. This directory will store software image downloads, which can be large but do not need to survive a reboot. An image is downloaded and applied, then the system reboots. """ return None @abc.abstractmethod def GetAcsUrl(self): """Return the current ACS_URL. Handling of the ACS URL to use is platform and/or deployment specific. For example, the platform may implement the CWMP ACS_URL option for DHCP, or it may have a hard-coded ACS URL for a particular ISP deployment. """ return None @abc.abstractmethod def SetAcsUrl(self, url): """Called for a SetParameterValue of DeviceInfo.ManagementServer.URL. Args: url: the URL to set It is up to the platform to determine the relative priority of ACS URLs set via DeviceInfo.ManagementServer.URL versus other mechanisms. If the platform does not allow the ACS to be set, this routine should raise an AttributeError. """ return None @abc.abstractmethod def AcsAccessAttempt(self, url): """Called before attempting to initiate a connection with the ACS. Args: url: the ACS_URL being contacted. """ return None @abc.abstractmethod def AcsAccessSuccess(self, url): """Called at the end of every successful ACS session. Args: url: the ACS_URL being contacted. """ return None
Python
from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import sys import os from google.appengine.ext.webapp import template from models import * class MainPage(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: user_id=i.admissionnumber if i.privilege=='admin': self.redirect("/admin") return elif i.approved==False: self.redirect("/usererror") return team=db.GqlQuery("SELECT * FROM teamDetails") project=db.GqlQuery("SELECT * FROM projectDetails") notif=db.GqlQuery("SELECT * FROM notificationDetails") qns=db.GqlQuery("SELECT * FROM questionanswer") tid=[] ti=[] temp=[] fla=0 for i in team: stri=i.teammember b=stri.split(',') for j in b: if (user_id==j): tid.append(i.projectids) t=[] for i in notif : if i.admissionnumber==user_id: temp1=[i.notification,i.notificationid] t.append(temp1) ans=[] for i in qns : if i.admissionnumber==user_id: temp1=[i.question,i.answer,i.questionid] ans.append(temp1) for i in project: for j in tid: temp=[] if i.projectid==j: temp=[i.projectname,i.projectid,i.teamid,i.category,i.abstract,i.confirmed] ti.append(temp) path = os.path.join(os.path.dirname(__file__),'tab.html')#use template self.response.out.write(template.render(path,{"items":ti,"noti":t,"email":user.email(),"ans":ans}))#using template except: self.redirect("/") else: self.redirect(users.create_login_url("/")) def post(self): delid=self.request.get("delval") if delid: notif=db.GqlQuery("SELECT * FROM notificationDetails WHERE notificationid='%s'"%(delid)) for i in notif : i.delete() delid=self.request.get("delans") if delid: ans=db.GqlQuery("SELECT * FROM questionanswer WHERE questionid='%s'"%(delid)) for i in ans : i.delete() self.redirect("/") application=webapp.WSGIApplication([('/user',MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime global ids class MainPage(webapp.RequestHandler,db.Model): global ids def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global ids ids=self.request.get("ids") category=[] c1=db.GqlQuery("SELECT * FROM projectFields") for i in c1: temp=[] temp.append(i.fieldname.replace(" ","_")) temp.append(i.fieldname) category.append(temp) lang=[] c1=db.GqlQuery("SELECT * FROM languages") for i in c1: lang.append(i.language) path = os.path.join(os.path.dirname(__file__),'create.html')#use template self.response.out.write(template.render(path,{"category":category,"language":lang}))#using template def post(self): global ids pro=db.GqlQuery("SELECT * FROM projectDetails") for k in pro: if k.projectid==ids: break c1=db.GqlQuery("SELECT * FROM languages") k.languages="" for i in c1: if self.request.get(i.language)=="yes": if k.languages=="": k.languages=k.languages+i.languageid else: k.languages=k.languages+","+i.languageid c1=db.GqlQuery("SELECT * FROM projectFields") k.fieldnames="" for i in c1: if self.request.get(i.fieldname.replace(" ","_"))=="yes": if(k.fieldnames==""): k.fieldnames=k.fieldnames+i.fieldid else: k.fieldnames=k.fieldnames+","+i.fieldid k.projectname=self.request.get("projectname") k.abstract=self.request.get("abstrct") k.link=self.request.get("link") k.confirmed=False k.put() c1=db.GqlQuery("SELECT * FROM teamDetails") for i in c1: if i.teamid==k.teamid: team=i.teammember.split(",") c2=db.GqlQuery("SELECT * FROM userDetails") for j in c2: if j.admissionnumber in team: if j.projectids==None: j.projectids=ids else: j.projectids=j.projectids+','+ids j.put() self.redirect("/user") application = webapp.WSGIApplication([('/create', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
"""Models""" from google.appengine.ext import db class userDetails(db.Model): #To store individual student details username=db.StringProperty() #Student name email=db.EmailProperty() #Email of student mobilenumber=db.StringProperty() #Mobile phone number admissionnumber=db.StringProperty() #Admission number branch=db.StringProperty() #College department projectids=db.StringProperty() #Current project IDs privilege=db.StringProperty() #User/administrator timestamp=db.DateTimeProperty(auto_now_add=True) #Data entry time approved=db.BooleanProperty() #Approval status class projectDetails(db.Model): #To store details of confirmed projects to be undertaken projectname=db.StringProperty() #Project name projectid=db.StringProperty() #Project ID teamid=db.StringProperty() #Team ID of team undertaking this project category=db.StringProperty() #Categories under which the project falls languages=db.StringProperty() #Programming languages fieldnames=db.StringProperty() #Field span of the project abstract=db.StringProperty() #Abstract of the project reviewdate=db.StringProperty() #Next review date confirmed=db.BooleanProperty() #Whether project is approved or not maxmembers=db.StringProperty() #Number of members per project (admin property) link=db.StringProperty() #Reference link pool=db.BooleanProperty() #To check if the project is from the pool class teamDetails(db.Model): #Details of individual teams teamid=db.StringProperty() #Team ID teammember=db.StringProperty() #Team members (number variable) projectids=db.StringProperty() #Project IDs of projects under this team locked=db.BooleanProperty() #Team members lock property class projectPool(db.Model): #Holds details of projects in the project pool poolprojectid=db.StringProperty() #Temporary project ID in the pool projectname=db.StringProperty() #Project name languages=db.StringProperty() #Programming languages abstract=db.StringProperty() #Project abstract category=db.StringProperty() fieldnames=db.StringProperty() lock=db.BooleanProperty() class projectCategory(db.Model): #Admin facility to store project categories categoryid=db.StringProperty() #Category ID categorytype=db.StringProperty() #The name of the category itself maxmembers=db.IntegerProperty() #Maximum number of members in a team who can undertake this type of project maxprojects=db.IntegerProperty() class notificationDetails(db.Model): #Details of notifications notificationid=db.StringProperty() #Notification ID admissionnumber=db.StringProperty() #Users who are concerned with the notification notification=db.StringProperty() #The notification itself class languages(db.Model): #Programming languages offered languageid=db.StringProperty() #ID of the programming language language=db.StringProperty() #Programming language class projectFields(db.Model): #Fields of the projects e.g.ML,HPC,Robotics... fieldid=db.StringProperty() #Field ID fieldname=db.StringProperty() #Name of the field class questionanswer(db.Model): #Q&A facility admissionnumber=db.StringProperty() #User ID that generated the question questionid=db.StringProperty() #Unique question ID question=db.StringProperty() #The question itself answer=db.StringProperty() #Answer
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ from models import * import datetime import random import re logout="""<p><a href="http://localhost:8080/_ah/login?continue=http%3A//localhost%3A8080/&action=Logout">Logout</a></p>""" go=""" <form action="/choice" method="get"> <input type="submit" value="Continue"> </form> """ class notificationPage(webapp.RequestHandler,db.Model): def get(self): global user,usr user = users.get_current_user() if user: self.response.out.write('Hello, '+user.nickname()) path = os.path.join(os.path.dirname(__file__),'test.html') self.response.out.write(template.render(path,{})) self.response.out.write(logout) else: self.redirect(users.create_login_url(self.request.uri)) def validate_emailid(self,emailid): #validating email ids if (re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", emailid)): return 1 else: return 0 def post(self): user = users.get_current_user() u=user.email() email=self.request.get("emailadr") emailid=email.split(',') n=1 f=0 f2=0 rest="" not_id="" frm_usrid="" userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: if (usr.email==u): frm_usrid=usr.userid f2=0 break else: f2=1 if (f2!=0): self.response.out.write("No user details available for current user! \n") else: for i in emailid: a=i if(a!=""): check=self.validate_emailid(i) if(check==1): userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: if (usr.email==a): rest=usr.userid+', '+rest not_id="NOTIFICATION"+str(random.randint(0,400)) n=notificationDetails(notificationid=not_id,frm_userid=frm_usrid,to_userid=usr.userid) n.put() path2 = os.path.join(os.path.dirname(__file__),'msg.html') self.response.out.write(template.render(path2,{'msg':' Notifications sent to: '+i})) f=emailid.index(a) else: not_found=emailid.index(a) if (f<emailid.index(a)): path2 = os.path.join(os.path.dirname(__file__),'msg.html') self.response.out.write(template.render(path2,{'msg':'No records found for :'+a})) else: path2 = os.path.join(os.path.dirname(__file__),'msg.html') self.response.out.write(template.render(path2,{'msg':i+' is not a valid email id!'})) if(rest!=""): tid="CS"+str(random.randint(0,140)) team=teamDetails(teamid=tid,teammember=rest+frm_usrid) team.put() self.response.out.write(go) application = webapp.WSGIApplication([('/', notificationPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ from models import * import datetime import random import re global ids class HelloPage(webapp.RequestHandler,db.Model): global ids def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global user,usr user = users.get_current_user() global ids ids="" user = users.get_current_user() url = self.request.url flag=0 for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): ids=ids+url[i] i=i+1 flag=1 break if flag==0: ids=self.request.get("ids") if user: self.response.out.write('Hello, '+user.nickname()) self.response.out.write(ids) path = os.path.join(os.path.dirname(__file__),'notifications.html') self.response.out.write(template.render(path,{"ids":ids})) else: self.redirect(users.create_login_url(self.request.uri)) def validate_emailid(self,emailid): #validating email ids if (re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", emailid)): return 1 else: return 0 def check_user(self,admno): #checks if member to be added is in anyother team. global m m="" t1=db.GqlQuery("SELECT * FROM teamDetails") for i in t1: self.response.out.write("hello"); mem=i.teammember.split(',') for j in mem: if admno==j: m='user hit!' self.response.out.write(m) return 0 return 1 def post(self): global ids user = users.get_current_user() u=user.email() email=self.request.get("emailadr") emailid=email.split(',') n=1 f=0 f2=0 rest="" not_id="" frm_usrid="" global m m="" msg=[] check2=2 dont_enter=0 userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: if (usr.email==u): sender=usr.username frm_usrid=usr.admissionnumber f2=0 break else: f2=1 if self.request.get("single")=="Continue": team=teamDetails(teammember=frm_usrid,projectids=ids) key=team.put() tid=key.id() team.teamid=str(tid) team.put() proj=db.GqlQuery("SELECT * FROM projectDetails") for i in proj: if i.projectid==ids: break i.teamid=str(tid) i.maxmembers=str(1) i.put() m='Single user successfully added!' msg.append(m) self.response.out.write(ids) path2 = os.path.join(os.path.dirname(__file__),'notifications_msg.html') self.response.out.write(template.render(path2,{'msg':msg,'back':dont_enter,'ids':ids})) #passing message frm 1st loop to template else: max_members=1 for i in emailid: #1st loop to extract email ids frm list a=i if(a!=""): check=self.validate_emailid(i) if(check==1): userDetails=db.GqlQuery("SELECT * FROM userDetails") for usr in userDetails: #2nd loop to retrieve userdetails (usr id) if (usr.email==a): admno=usr.admissionnumber check2=self.check_user(admno) self.response.out.write("<br>"+str(check2)+"<br>"); if check2==1: max_members=max_members+1 rest=usr.admissionnumber+','+rest message="You have been added to the team of '%s'" %sender n=notificationDetails(notificationid=not_id,admissionnumber=usr.admissionnumber,notification=message) key=n.put() noteid=key.id() n.notificationid=str(noteid) n.put() m='Notifications sent to: '+i msg.append(m) f=emailid.index(a) elif check2==0: m=a+' has been already added!' msg.append(m) f=emailid.index(a) dont_enter=1 else: not_found=emailid.index(a) if (f<emailid.index(a)): m='No Records found for: '+a msg.append(m) dont_enter=1 else: m=i+' is not a valid email id!' msg.append(m) dont_enter=1 if(rest!="" and dont_enter==0): team=teamDetails(teammember=rest+frm_usrid,projectids=ids) key=team.put() tid=key.id() team.teamid=str(tid) team.put() proj=db.GqlQuery("SELECT * FROM projectDetails") for i in proj: if i.projectid==ids: break i.teamid=str(tid) i.maxmembers=str(max_members) i.put() self.response.out.write(ids) path2 = os.path.join(os.path.dirname(__file__),'notifications_msg.html') self.response.out.write(template.render(path2,{'msg':msg,'back':dont_enter,'ids':ids})) #passing message frm 1st loop to template class SentPage(webapp.RequestHandler,db.Model): global ids def get(self): global ids self.redirect("/choice?%s=id" %ids) application = webapp.WSGIApplication([('/notification', HelloPage),('/sent',SentPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class Language(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() languages=[] alllanguages=db.GqlQuery("SELECT * FROM languages") for language in alllanguages: tmp=[] tmp.append(language.languageid) tmp.append(language.language) languages.append(tmp) path = os.path.join(os.path.dirname(__file__),'language.html')#specify file name self.response.out.write(template.render(path,{"list":languages}))#var name 'list' and 'name' is used in html def post(self): lang=db.GqlQuery("SELECT * FROM languages") for i in lang: if self.request.get(i.languageid) != i.languageid: i.delete() langs=self.request.get("addlan") langid=langs.split(',') for i in langid: if i: la=languages(language=str(i)) key=la.put() idnum=key.id() la.languageid=str(idnum) la.put() self.redirect("/admin") application = webapp.WSGIApplication([('/updatelanguage', Language)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ReviewProjectSubmission(webapp.RequestHandler): global projectid def post(self): global projectid is_confirm = self.request.get('confirm', None) is_reject = self.request.get('reject', None) details=[] projects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %projectid) for project in projects: teamid=project.teamid pname=project.projectname members=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %teamid) mem=members if is_confirm: query="SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid) confirmMe = db.GqlQuery(query) for project in confirmMe: note="Your project '%s' has been confirmed" %project.projectname project.confirmed=True project.put() for i in mem: listmembers=i.teammember members=listmembers.split(",") for member in members: newnote=notificationDetails(admissionnumber=member,notification=note) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_reject: query="SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid) deleteMe = db.GqlQuery(query) for project in deleteMe: note="Your project '%s' has been rejected" %project.projectname project.delete() for i in mem: listmembers=i.teammember members=listmembers.split(",") for member in members: newnote=notificationDetails(admissionnumber=member,notification=note) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() else: raise Exception('no form action given') self.redirect("/reviewprojectmain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global projectid projectid='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): projectid=projectid+url[i] i=i+1 break currentproject=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'"%projectid) tmp=[] for project in currentproject: tmp1=[] tmp1.append(project.projectid) tmp1.append(project.projectname) tmp1.append(project.abstract) tmp1.append(project.languages) tmp1.append(project.category) tmp1.append(project.fieldnames) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'reviewproject.html')#use template self.response.out.write(template.render(path,{"review":tmp}))#using template class ReviewProjectMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() notConfirmed=db.GqlQuery("SELECT * FROM projectDetails WHERE confirmed=False") path = os.path.join(os.path.dirname(__file__),'reviewprojectmain.html')#use template tmp=[] for project in notConfirmed: tmp1=[] tmp1.append(project.projectname) tmp1.append(project.projectid) tmp.append(tmp1) self.response.out.write(template.render(path,{"projects":tmp}))#using template application = webapp.WSGIApplication([('/reviewprojectsubmission', ReviewProjectSubmission),('/reviewprojectmain', ReviewProjectMain)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class BrowseUserActivity(webapp.RequestHandler): def post(self): self.redirect("/browseuseractivitymain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() admissionnumber='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): admissionnumber=admissionnumber+url[i] i=i+1 break users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %admissionnumber) for user in users: tmp=[] tmp.append(user.username) currentprojectids=user.projectids if(currentprojectids==None): self.redirect("/browseuseractivitymain") return projids=currentprojectids.split(",") tmp1=[] for pid in projids: currentprojects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %pid) for project in currentprojects: tmpprojs=project.projectname tmp1.append(tmpprojs) tmp.append(tmp1) break path = os.path.join(os.path.dirname(__file__),'browseuser.html')#use template self.response.out.write(template.render(path,{"details":tmp}))#using template class BrowseUserActivityMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() users=db.GqlQuery("SELECT * FROM userDetails") tmp=[] for user in users: tmp1=[] tmp1.append(user.admissionnumber) tmp1.append(user.username) tmp1.append(user.branch) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'browseusermain.html')#use template self.response.out.write(template.render(path,{"users":tmp}))#using template application = webapp.WSGIApplication([('/browseuseractivitymain', BrowseUserActivityMain),('/browseuseractivity', BrowseUserActivity)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class EditUser(webapp.RequestHandler): global admissionnumber def post(self): global admissionnumber is_confirm = self.request.get('confirm', None) is_cancel = self.request.get('cancel', None) is_delete = self.request.get('delete', None) uname=self.request.get("username") umail=self.request.get("useremail") umobile=self.request.get("usermobile") uadmission=self.request.get("useradmission") ubranch=self.request.get("userbranch") uprivilege=self.request.get("userprivilege") users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %(admissionnumber)) if is_confirm: for user in users: user.username=uname user.email=umail user.mobilenumber=umobile user.admissionnumber=uadmission user.privilege=uprivilege user.put() message="Your details have been edited by the administrator" newnote=notificationDetails(admissionnumber=admissionnumber,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_delete: for user in users: notesforme=db.GqlQuery("SELECT * FROM notificationDetails WHERE admissionnumber='%s'" %admissionnumber) for note in notesforme: note.delete() qnsfromme=db.GqlQuery("SELECT * FROM questionanswer WHERE admissionnumber='%s'" %admissionnumber) for qn in qnsfromme: qn.delete() userinteams=db.GqlQuery("SELECT * FROM teamDetails") for team in userinteams: members=team.teammember.split(",") for member in members: if member==uadmission: members.remove(member) newmembers='' for member in members: message="The member '%s' has been pulled out of your team" %uname newnote=notificationDetails(admissionnumber=member,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() if not newmembers: newmembers=member else: newmembers=newmembers+","+member team.teammember=newmembers team.put() user.delete() emptyteams=db.GqlQuery("SELECT * FROM teamDetails") for team in emptyteams: if team.teammember=="": team.delete() self.redirect("editusermain") return elif is_cancel: self.redirect("editusermain") return else: raise Exception('no form action given') self.redirect("/editusermain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global admissionnumber admissionnumber='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): admissionnumber=admissionnumber+url[i] i=i+1 break users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %admissionnumber) tmp=[] for user in users: path = os.path.join(os.path.dirname(__file__),'edituser.html')#use template self.response.out.write(template.render(path,{"name":user.username,"email":user.email,"mob":user.mobilenumber,"admno":user.admissionnumber,"branch":user.branch,"privilege":user.privilege}))#using template class EditUserMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() allusers=db.GqlQuery("SELECT * FROM userDetails") tmp=[] for user in allusers: tmp1=[] tmp1.append(user.admissionnumber) tmp1.append(user.username) tmp1.append(user.email) tmp1.append(user.branch) tmp1.append(user.mobilenumber) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'editusermain.html')#use template self.response.out.write(template.render(path,{"users":tmp}))#using template application = webapp.WSGIApplication([('/edituser', EditUser),('/editusermain', EditUserMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class AddToPool(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() category=[] allcategories=db.GqlQuery("SELECT * FROM projectCategory") for spcategory in allcategories: tmp=[] tmp.append(spcategory.categoryid) tmp.append(spcategory.categorytype) category.append(tmp) languages=[] alllanguages=db.GqlQuery("SELECT * FROM languages") for language in alllanguages: tmp=[] tmp.append(language.languageid) tmp.append(language.language) languages.append(tmp) fieldnames=[] allfields=db.GqlQuery("SELECT * FROM projectFields") for fieldname in allfields: tmp=[] tmp.append(fieldname.fieldid) tmp.append(fieldname.fieldname) fieldnames.append(tmp) path = os.path.join(os.path.dirname(__file__),'addtopool.html')#use template self.response.out.write(template.render(path,{"category":category,"language":languages,"fieldname":fieldnames}))#using template def post(self): pname=self.request.get("projectname") pabstract=self.request.get("abstract") pcategory=str(self.request.get("category")) pfields='' planguages='' allfields=db.GqlQuery("SELECT * FROM projectFields") alllanguages=db.GqlQuery("SELECT * FROM languages") for language in alllanguages: if(self.request.get("l"+language.languageid)=='yes'): if(planguages!=''): planguages=planguages+","+language.languageid else: planguages=language.languageid for fieldname in allfields: if(self.request.get("f"+fieldname.fieldid)=='yes'): if(pfields!=''): pfields=pfields+","+fieldname.fieldid else: pfields=fieldname.fieldid projecttopool=projectPool(projectname=pname,languages=planguages,category=pcategory,abstract=pabstract,fieldnames=pfields,lock=False) key=projecttopool.put() idnum=key.id() projecttopool.poolprojectid=str(idnum) projecttopool.put() self.redirect("/admin") application = webapp.WSGIApplication([('/addtopool', AddToPool)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime import string global category global project global fields global name global ids flag=False class MainPage(webapp.RequestHandler,db.Model): global category global project global fields global name global ids def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global ids global category global project global fields ids=self.request.get("ids") category=[] project=[[],[],[],[],[],[]] fields=[] c1=db.GqlQuery("SELECT * FROM projectDetails") for i in c1: if i.projectid==ids: self.response.out.write("Hello") cat=i.category c1=db.GqlQuery("SELECT * FROM projectFields") for i in c1: tmp=[] tmp.append(i.fieldname.replace(" ","_")) tmp.append(i.fieldname) category.append(tmp) c1=db.GqlQuery("SELECT * FROM projectCategory") for i in c1: if i.categoryid==cat: cat=i.categorytype c1=db.GqlQuery("SELECT * FROM projectPool where category='%s'" %cat) for i in c1: if i.lock != True: project[0].append(i.projectname.replace(" ","_")) project[1].append(i.fieldnames.replace(" ","_")) project[2].append(i.abstract) project[3].append(i.lock) project[4].append(i.poolprojectid) project[5].append(i.languages) path = os.path.join(os.path.dirname(__file__),'pool.html')#use template self.response.out.write(template.render(path,{"category":category},"field"))#using template def post(self): #This is the function which calls topic.html name is the variable being pased global category global project global fields global name global ids name=[] path = os.path.join(os.path.dirname(__file__),'topic.html')#use template for i in category: if self.request.get(i[0])=="yes": fields.append(i[0]) field_names=[] f=1 temp=[] if fields : q=-1 for j in project[1]: temp=[] q=q+1 field_names=j.split(',') e=0 for k in field_names: e=e+1 temp=[] if k in fields: flag=True else: flag=False break if len(fields)!=e: flag=False if flag: f=0 self.response.out.write(f) temp.append(project[0][q]) temp.append(project[2][q]) temp.append(project[0][q].replace("_"," ")) temp.append(project[5][q]) name.append(temp) self.response.out.write(project[5]) if f==0: self.response.out.write(template.render(path,{"name":name,"back":"Back","ids":ids}))#using template if len(fields) == 0: f=0 for i in project[0]: temp=[] temp.append(i) temp.append(project[2][project[0].index(i)]) temp.append(i.replace("_"," ")) temp.append(project[5][project[0].index(i)]) name.append(temp) self.response.out.write(template.render(path,{"name":name,"back":"Back","ids":ids})) if f : path = os.path.join(os.path.dirname(__file__),'rong.html')#use template self.response.out.write(template.render(path,{"wro":"wrong","ids":ids}))#,"language":lang}))#using template del field_names[:] del fields[:] class SelectPage(webapp.RequestHandler,db.Model): global category global project global fields global name global ids def get(self): f=0 global category global project global fields global name global ids field_names=[] f='' pro=db.GqlQuery("SELECT * FROM projectDetails ") for j in project[0]: if self.request.get(j)=="Submit": for k in pro: if k.projectid==ids: k.projectname=j.replace("_"," ") prof=db.GqlQuery("SELECT * FROM projectFields") project[1][project[0].index(j)]=project[1][project[0].index(j)].replace("_"," ") field_names=project[1][project[0].index(j)].split(',') for i in prof: if i.fieldname in field_names: if(f!=''): f=f+","+i.fieldid else: f=i.fieldid k.fieldnames=f f='' k.abstract=project[2][project[0].index(j)] lang=project[5][project[0].index(j)].split(',') prol=db.GqlQuery("SELECT * FROM languages") for i in prol: if i.language in lang: if(f!=''): f=f+","+i.languageid else: f=i.languageid k.languages=f k.confirmed=True k.put() c1=db.GqlQuery("SELECT * FROM teamDetails") for i in c1: if i.teamid==k.teamid: team=i.teammember.split(",") c1=db.GqlQuery("SELECT * FROM userDetails") for i in c1: if i.admissionnumber in team: if i.projectids==None: i.projectids=ids else: i.projectids=i.projectids+','+ids i.put() c1=db.GqlQuery("SELECT * FROM projectPool") for i in c1: j=j.replace("_"," ") if i.projectname==j: f=1 i.lock=True i.put() if f: del category[:] del project[0][:] del project[1][:] del project[2][:] del name[:] self.redirect("/user") application = webapp.WSGIApplication([('/pool', MainPage),('/sel', SelectPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from google.appengine.ext import db from google.appengine.api import users from models import * cat=db.GqlQuery("SELECT * FROM projectCategory") for i in cat: i.delete() cat=db.GqlQuery("SELECT * FROM projectDetails") for i in cat: i.delete() u1=projectCategory(categoryid="CSHPC",maxmembers=100,categorytype="HPC New",categorylead="mahesh") u1.put() u2=projectCategory(categoryid="CSMini",maxmembers=3,categorytype="Mini Project",categorylead="mahesh") u2.put() u3=projectCategory(categoryid="CSMain",maxmembers=3,categorytype="Main Project",categorylead="Mase") u3.put() p1=projectDetails(projectid="KF01") p1.put() p2=projectDetails(projectid="KF02") p2.put() p3=projectDetails(projectid="KF03") p3.put() print "hai"
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime class MainPage(webapp.RequestHandler,db.Model): def get(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': self.redirect("/admin") return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def post(self): user = users.get_current_user() details=models.userDetails() details.username=self.request.get("name") details.email=user.email() details.mobilenumber=self.request.get("phone") details.privilege="user" details.projecteamids="" details.admissionnumber=self.request.get("admno") details.userid=self.request.get("admno") details.branch=self.request.get("branch") details.approved=False details.put() self.redirect("/user") class Display(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: path = os.path.join(os.path.dirname(__file__),'home.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) class Home(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': self.redirect("/admin") return elif i.approved==False: return path = os.path.join(os.path.dirname(__file__),'landing.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template except: self.redirect("/") else: self.redirect(users.create_login_url("/")) class Logout(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: self.redirect(users.create_logout_url("/")) else: self.redirect(users.create_login_url("/")) class Admin(webapp.RequestHandler): def get(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': self.redirect("/") return path = os.path.join(os.path.dirname(__file__),'admin.html')#use template self.response.out.write(template.render(path,{"email":"Administrator"}))#using template except: self.redirect("/") else: self.redirect(users.create_login_url("/")) application = webapp.WSGIApplication([('/', MainPage),('/inser', Display),('/home', Home),('/logout', Logout),('/admin',Admin)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ProjectPool(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() projectpool=[] projectsinpool=db.GqlQuery("SELECT * FROM projectPool") for proj in projectsinpool: tmp=[] tmp.append(proj.poolprojectid) tmp.append(proj.projectname) projectpool.append(tmp) path = os.path.join(os.path.dirname(__file__),'projectpool.html')#use template self.response.out.write(template.render(path, {"projectpool":projectpool}))#using template application = webapp.WSGIApplication([('/projectpool', ProjectPool)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import sys import os from google.appengine.ext.webapp import template from models import * global pcategory class MainPage(webapp.RequestHandler): global pcategory def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global pcategory c=db.GqlQuery("SELECT * FROM projectCategory") pcategory=[] self.response.out.write(c) for i in c: tmp=[] tmp.append(i.categorytype.replace(" ","_")) tmp.append(i.categorytype) tmp.append(i.categoryid) tmp.append(i.maxprojects) pcategory.append(tmp) path = os.path.join(os.path.dirname(__file__),'cat.html')#use template self.response.out.write(template.render(path,{"category":pcategory}))#using template def post(self): global pcategory k=projectDetails() k.category=self.request.get("category") for i in pcategory: if i[0]==k.category: break k.category=i[2] user = users.get_current_user() if user: try: userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='%s'" %(user.email())) for i in userdet: if(i.projectids==None): break projunderme=i.projectids.split(",") for pid in projunderme: projdets=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %pid) for j in projdets: if j.category==k.category: path = os.path.join(os.path.dirname(__file__),'categoryerror.html')#use template self.response.out.write(template.render(path,{}))#using template return key=k.put() ids=key.id() k.projectid=str(ids) k.put() del pcategory[:] self.redirect("/notification?%s=id" %ids) except: pass application=webapp.WSGIApplication([('/category',MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ViewTeam(webapp.RequestHandler): def get(self): allteams=db.GqlQuery("SELECT * FROM teamDetails") tmp2=[] for team in allteams: teams=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %team.teamid) tmp1=[] for team in teams: tmp=[] for member in team.teammember: mem=member.split(',') membername = db.GqlQuery("SELECT username FROM userDetails WHERE userid='%s'" %mem) tmp.append(membername) tmp1.append(team.teamid) tmp1.append(tmp) for project in team.projectids: proj=project.split(',') projectname = db.GqlQuery("SELECT projectname FROM projectDetails WHERE projectid='%s'" %proj) tmp1.append(projectname) tmp2.append(tmp1) path = os.path.join(os.path.dirname(__file__),'viewteam.html')#use template self.response.out.write(template.render(path,{"team":tmp2}))#using template application = webapp.WSGIApplication([('/viewteam', ViewTeam)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from google.appengine.ext import db from google.appengine.api import users from models import * u1=userDetails(username="kev",email="kev@gmail.com",userid="221",mobilenumber="111",admissionnumber="1",branch="CSE",projecteamids="",privilege="stud",timestamp="") u1.put() u2=userDetails(username="jozf",email="jozf@gmail.com",userid="222",mobilenumber="222",admissionnumber="2",branch="CSE",projecteamids="",privilege="stud",timestamp="") u2.put() u3=userDetails(username="jay",email="jay@gmail.com",userid="223",mobilenumber="333",admissionnumber="3",branch="CSE",projecteamids="",privilege="stud",timestamp="") u3.put() u4=userDetails(username="dp",email="dp@gmail.com",userid="224",mobilenumber="444",admissionnumber="4",branch="CSE",projecteamids="",privilege="stud",timestamp="") u4.put() u5=userDetails(username="chak",email="chak@gmail.com",userid="225",mobilenumber="555",admissionnumber="5",branch="CSE",projecteamids="",privilege="stud",timestamp="") u5.put() u6=userDetails(username="jerry",email="jerry@gmail.com",userid="226",mobilenumber="777",admissionnumber="6",branch="CSE",projecteamids="",privilege="stud",timestamp="") u6.put() print "hai"
Python
from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app import sys import os from google.appengine.ext.webapp import template from models import * class MainPage(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() user = users.get_current_user() t_email=user.email() usrdtl=db.GqlQuery("SELECT * FROM userDetails") for k in usrdtl: if k.email==t_email: user_id=k.userid teamDetails=db.GqlQuery("SELECT * FROM teamDetails") projectDetails=db.GqlQuery("SELECT * FROM projectDetails") notif=db.GqlQuery("SELECT * FROM notificationDetails") tid=[] temp=[] fla=0 for i in teamDetails: stri=i.teammember b=stri.split(',') for j in b: if j==user_id: fla=1 tid.append(i.projectids) t=[] for i in notif : if i.userid==user_id: temp1=[i.notification,i.notificationid] t.append(temp1) for i in projectDetails: for j in tid: if i.projectid==j: temp=[i.projectname,i.projectid,i.teamid,i.category,i.abstract,i.confirmed] tid.append(temp) path = os.path.join(os.path.dirname(__file__),'tab.html')#use template self.response.out.write(template.render(path,{"items":tid,"noti":t}))#using template def post(self): delid=self.request.get("delval") notif=db.GqlQuery("SELECT * FROM notificationDetails WHERE notificationid='%s'"%(delid)) for i in notif : i.delete() self.redirect("/") application=webapp.WSGIApplication([('/',MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime import random ids=["102","103","104","105","106","107","108","109","112","113","114","115","116","117","118","119"] field=["HPC","Machine Learning","Robotics","TOC","GAME","ANDROID","ELECTRONICS","WEB DEVELOPMENT"] name=["Compiler Design","Face Detection","QuadraCopter","Travelling Sales Man","Develop a open source","Android Media Player","Andrino Prog","HTML5 Website","Panda 3d Game","Android Battery monitor","Robotic Arm","Google Hacking","Coffee detection ROBOT","FB hacking"] abst=["qwertyuiop","poiuytrewwq","asdfghjkl","lkjhgfdsa","zxcvbnm","mnbvcxz","blsahahah","blahahaha","blsahahah","blahahaha","blsahahah","blahahaha"] lang=["pyhton","C","java","c++","perl"] class MainPage(webapp.RequestHandler,db.Model): def get(self): c1=db.GqlQuery("SELECT * FROM projectFields") for i in c1: i.delete() c1=db.GqlQuery("SELECT * FROM projectPool") for i in c1: i.delete() c1=db.GqlQuery("SELECT * FROM projectPool") for i in c1: self.response.out(i) for i in range(0,14): project=models.projectPool() project.poolprojectid=ids[i] project.fieldnames=field[random.randint(0,7)] for k in range(0,random.randint(0,2)): project.fieldnames=project.fieldnames+","+field[random.randint(0,7)] project.projectname=name[i] project.abstract=abst[random.randint(0,11)] project.languages=lang[random.randint(0,4)]+","+lang[random.randint(0,4)] project.put() self.response.out.write("Field : "+project.fieldnames+" ") self.response.out.write("Name : "+project.projectname+" ") self.response.out.write("Abstract : "+project.abstract+" <br>") for i in range(0,8): p1=models.projectFields() p1.fieldname=field[i] p1.put() self.response.out.write("Field : "+p1.fieldname+" ") """ self.response.out.write("category: "+self.request.get("category")+"<br>") self.response.out.write("Lan: ") c1=db.GqlQuery("SELECT * FROM languages") project.languages="" for i in c1: self.response.out.write(i.language+" : "+self.request.get(i.language)+"<br>") if self.request.get(i.language)=="yes": project.languages=project.languages+i.language+"," self.response.out.write("<br>category: "+self.request.get("abs")+"<br>") self.response.out.write("<br>projectname: "+self.request.get("projectname")+"<br>") project.categories=self.request.get("category") project.projectname=self.request.get("projectname") project.abstract=self.request.get("abs") project.confirmed=False project.put() """ application = webapp.WSGIApplication([('/', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class QAPage(webapp.RequestHandler): global questionid def post(self): global questionid answer=self.request.get("ans") question=db.GqlQuery("SELECT * FROM questionanswer WHERE questionid='%s'" %questionid) for qn in question: qn.answer=answer qn.put() self.redirect("/answerquestionmain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global questionid questionid='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): questionid=questionid+url[i] i=i+1 break question=db.GqlQuery("SELECT * FROM questionanswer WHERE questionid='%s' AND answer=NULL" %questionid) for qn in question: path = os.path.join(os.path.dirname(__file__),'qnans.html')#use template self.response.out.write(template.render(path,{"question":qn.question,"questionid":qn.questionid}))#using template class QAPageMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() unansweredqns=db.GqlQuery("SELECT * FROM questionanswer WHERE answer=NULL") ques=[] for question in unansweredqns: temp=[] temp.append(question.question) temp.append(question.questionid) ques.append(temp) path = os.path.join(os.path.dirname(__file__),'qnansmain.html')#use template self.response.out.write(template.render(path,{"question":ques}))#using template application = webapp.WSGIApplication([('/answerquestion', QAPage),('/answerquestionmain', QAPageMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class EditProject(webapp.RequestHandler): global projectid def post(self): global projectid is_confirm = self.request.get('confirm', None) is_delete = self.request.get('delete', None) is_cancel = self.request.get('cancel', None) if is_confirm: pname=self.request.get("projname") pabstract=self.request.get("projabstract") pteamid=self.request.get("projteamids") pcategory=self.request.get("catsel") planguages='' languages=db.GqlQuery("SELECT * FROM languages") for i in languages: if self.request.get("l"+i.languageid) == "l"+i.languageid: if not planguages: planguages=i.languageid else: planguages=planguages+","+i.languageid pfields='' fields=db.GqlQuery("SELECT * FROM projectFields") for i in fields: if self.request.get("f"+i.fieldid) == "f"+i.fieldid: if not pfields: pfields=i.fieldid else: pfields=pfields+","+i.fieldid previewdate=self.request.get("projreviewdate") previewdate=self.request.get("projmaxmem") project=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid)) for projdetails in project: projdetails.projectname=pname projdetails.category=pcategory projdetails.languages=planguages projdetails.abstract=pabstract projdetails.teamid=pteamid projdetails.reviewdate=previewdate projdetails.fieldnames=pfields projdetails.put() teammembers=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %pteamid) for mem in teammembers: notifymembers=mem.teammember.split(",") message="The project "+pname+" has been edited by the administrator" for member in notifymembers: newnote=notificationDetails(admissionnumber=member,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_delete: project=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid)) for projdetails in project: pname=projdetails.projectname pteamid=projdetails.teamid delfromteam=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %pteamid) for team in delfromteam: teamprojs=team.projectids.split(",") teamuser=team.teammember.split(",") for user in teamuser: delprojuser=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %user) for delproj in delprojuser: userprojects=delproj.projectids.split(",") for projs in userprojects: if(projs==projectid): userprojects.remove(projectid) for prjcts in userprojects: userprojs='' for prjcts in projs: if not userprojs: userprojs=prjcts else: userprojs=userprojs+","+prjcts delproj.projectids=userprojs delproj.put() for projid in teamprojs: if(projid==projectid): teamprojs.remove(projectid) teamprojs='' for projid in teamprojs: if not teamprojs: teamprojs=projid else: teamprojs=teamprojs+","+projid team.projectids=teamprojs team.put() projdetails.delete() teammembers=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %(pteamid)) for member in teammembers: notifymembers=member.teammember.split(",") message="The project '"+pname+"' has been deleted by the administrator" for singlemember in notifymembers: newnote=notificationDetails(admissionnumber=singlemember,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_cancel: self.redirect("/editprojectmain") else: raise Exception('no form action given') self.redirect("/editprojectmain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global projectid projectid='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): projectid=projectid+url[i] i=i+1 break projects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %projectid) path = os.path.join(os.path.dirname(__file__),'editproject.html')#use template tmp=[] for project in projects: categoryselected=[] fieldsselected=[] languageselected=[] categoryunselected=[] fieldsunselected=[] languageunselected=[] catdet=db.GqlQuery("SELECT * FROM projectCategory") for catg in catdet: if catg.categoryid==project.category: categoryselected.append(catg.categoryid) categoryselected.append(catg.categorytype) else: tmp=[] tmp.append(catg.categoryid) tmp.append(catg.categorytype) categoryunselected.append(tmp) langdet=db.GqlQuery("SELECT * FROM languages") for lang in langdet: selflag=0 for sellang in project.languages.split(","): if lang.languageid==sellang: tmp=[] tmp.append(lang.languageid) tmp.append(lang.language) languageselected.append(tmp) selflag=1 break if selflag==0: tmp=[] tmp.append(lang.languageid) tmp.append(lang.language) languageunselected.append(tmp) fielddet=db.GqlQuery("SELECT * FROM projectFields") for fld in fielddet: selflag=0 for indfield in project.fieldnames.split(","): if fld.fieldid==indfield: tmp=[] tmp.append(fld.fieldid) tmp.append(fld.fieldname) fieldsselected.append(tmp) selflag=1 break if selflag==0: tmp=[] tmp.append(fld.fieldid) tmp.append(fld.fieldname) fieldsunselected.append(tmp) self.response.out.write(template.render(path,{"pname":project.projectname,"abstract":project.abstract,"teamid":project.teamid,"categoryunselected":categoryunselected,"categoryselected":categoryselected,"languageunselected":languageunselected,"languageselected":languageselected,"fieldsunselected":fieldsunselected,"fieldsselected":fieldsselected,"reviewdate":project.reviewdate,"maxmembers":project.maxmembers}))#using template class EditProjectMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() confirmed=db.GqlQuery("SELECT * FROM projectDetails") path = os.path.join(os.path.dirname(__file__),'editprojectmain.html')#use template tmp=[] for project in confirmed: tmp1=[] tmp1.append(project.projectname) tmp1.append(project.projectid) tmp.append(tmp1) self.response.out.write(template.render(path,{"projects":tmp}))#using template application = webapp.WSGIApplication([('/editproject', EditProject),('/editprojectmain', EditProjectMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class NextReviewMain(webapp.RequestHandler): def post(self): pteams='' date=self.request.get("date") allteams=db.GqlQuery("SELECT * FROM teamDetails") for team in allteams: if(self.request.get(team.teamid)=='teams'): if(pteams!=''): pteams=pteams+","+team.teammember else: pteams=team.teammember notemembers=pteams.split(",") message="Your team has a review on '%s'" %date for memberid in notemembers: newnote=notificationDetails(admissionnumber=memberid,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() self.redirect("/nextreview") class NextReview(webapp.RequestHandler): def post(self): selcategory=self.request.get("category") catid=str(selcategory) projects=db.GqlQuery("SELECT * FROM projectDetails WHERE category='%s'" %catid) details=[] #self.response.out.write(projects) for project in projects: teamid=project.teamid pname=project.projectname members=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %teamid) mem=members for i in mem: listmembers=i.teammember members=listmembers.split(",") membernames='' for member in members: indmember=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %member) for mem in indmember: membernames=membernames+mem.username tmp=[] tmp.append(teamid) tmp.append(pname) tmp.append(membernames) details.append(tmp) path = os.path.join(os.path.dirname(__file__),'nextreviewmain.html') self.response.out.write(template.render(path,{"members":details})) def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() category=[] allcategories=db.GqlQuery("SELECT * FROM projectCategory") for spcategory in allcategories: tmp=[] tmp.append(spcategory.categoryid) tmp.append(spcategory.categorytype) category.append(tmp) path = os.path.join(os.path.dirname(__file__),'nextreview.html')#use template self.response.out.write(template.render(path,{"category":category}))#using template application = webapp.WSGIApplication([('/nextreview', NextReview),('/nextreviewmain', NextReviewMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class ConfirmUser(webapp.RequestHandler): global admissionnumber def post(self): global admissionnumber is_confirm = self.request.get('confirm', None) is_cancel = self.request.get('cancel', None) if is_confirm: users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %(admissionnumber)) for user in users: user.approved=True user.put() message="Your details have been verified and accepted by the administrator" newnote=notificationDetails(admissionnumber=admissionnumber,notification=message) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() elif is_cancel: users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %(admissionnumber)) for user in users: user.delete() else: raise Exception('no form action given') self.redirect("/confirmusermain") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() global admissionnumber admissionnumber='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): admissionnumber=admissionnumber+url[i] i=i+1 break users=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s' AND approved=False" %admissionnumber) tmp=[] for user in users: tmp1=[] tmp1.append(user.username) tmp1.append(user.email) tmp1.append(user.mobilenumber) tmp1.append(user.admissionnumber) tmp1.append(user.branch) tmp1.append(user.privilege) tmp.append(tmp1) path = os.path.join(os.path.dirname(__file__),'confirmuser.html')#use template self.response.out.write(template.render(path,{"users":tmp}))#using template class ConfirmUserMain(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() allusers=db.GqlQuery("SELECT * FROM userDetails WHERE approved=False") tmp=[] path = os.path.join(os.path.dirname(__file__),'confirmusermain.html')#use template for user in allusers: tmp1=[] tmp1.append(user.admissionnumber) tmp1.append(user.username) tmp.append(tmp1) self.response.out.write(template.render(path,{"users":tmp}))#using template application = webapp.WSGIApplication([('/confirmuser', ConfirmUser),('/confirmusermain', ConfirmUserMain)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import cgi from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app import os from google.appengine.ext.webapp import template from models import * class MainPage(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() user = users.get_current_user() template_values = { } path = os.path.join(os.path.dirname(__file__), 'question.html') self.response.out.write(template.render(path, template_values)) def post(self): x=self.request.get("t1") user = users.get_current_user() t_email=user.email() usrdtl=db.GqlQuery("SELECT * FROM userDetails") for j in usrdtl: if j.email==t_email: user_ano=j.admissionnumber self.response.out.write(user_ano) tempvar=questionanswer(admissionnumber=str(user_ano),question=x) key=tempvar.put() tempvar.questionid=str(key.id()) tempvar.put() self.redirect('/user') application = webapp.WSGIApplication([('/question', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class AdminLogout(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() user=users.get_current_user() if user: self.redirect(users.create_logout_url("/")) else: self.redirect(users.create_logout_url("/")) class MainAdminPage(webapp.RequestHandler): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() path = os.path.join(os.path.dirname(__file__),'admin.html')#use template self.response.out.write(template.render(path,{}))#using template application = webapp.WSGIApplication([ ('/admin', MainAdminPage),('/adminlogout', AdminLogout)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime import string class MainPage(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='user': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/admin") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() ids='' url = self.request.url for i in range(0,len(url),1): if(url[i]=='?'): i=i+1 while(url[i]!='='): ids=ids+str(url[i]) i=i+1 break ids=str(ids) self.response.out.write(str(ids)) path = os.path.join(os.path.dirname(__file__),'choice.html')#use template self.response.out.write(template.render(path,{"ids":ids}))#using template application = webapp.WSGIApplication([('/choice', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class UserError(webapp.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__),'usererror.html')#use template self.response.out.write(template.render(path,{}))#using template application = webapp.WSGIApplication([('/usererror', UserError)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class Field(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() fieldnames=[] allfields=db.GqlQuery("SELECT * FROM projectFields") for fieldname in allfields: tmp=[] tmp.append(fieldname.fieldid) tmp.append(fieldname.fieldname) fieldnames.append(tmp) path = os.path.join(os.path.dirname(__file__),'field.html') self.response.out.write(template.render(path,{"fieldname":fieldnames})) def post(self): field=db.GqlQuery("SELECT * FROM projectFields") for i in field: if self.request.get(i.fieldid) != i.fieldid: i.delete() fieldentry=self.request.get("addfield") fieldentrylist=fieldentry.split(',') for i in fieldentrylist: if i: pf=projectFields(fieldname=str(i)) key=pf.put() idnum=key.id() pf.fieldid=str(idnum) pf.put() self.redirect("/admin") application = webapp.WSGIApplication([('/updatefield', Field)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import sys import os from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library use_library('django', '0.96') from os import environ import models import datetime class Category(webapp.RequestHandler,db.Model): def verifyLogin(self): user = users.get_current_user() if user: usercheck=models.userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.path.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() category=[] allcategories=db.GqlQuery("SELECT * FROM projectCategory") for spcategory in allcategories: tmp=[] tmp.append(spcategory.categoryid) tmp.append(spcategory.categorytype) category.append(tmp) path = os.path.join(os.path.dirname(__file__),'category.html') self.response.out.write(template.render(path,{"category":category})) def post(self): category=db.GqlQuery("SELECT * FROM projectCategory") for i in category: if self.request.get(i.categoryid) != i.categoryid: i.delete() categoryentry=self.request.get("addcategory") categoryentrylist=categoryentry.split(',') maximum=self.request.get("maximum") maximum=maximum.split(',') maxprojs=self.request.get("maxprojects") maxprojs=maxprojs.split(',') for i in range(0,len(categoryentrylist)): if categoryentrylist[i]: pf=models.projectCategory(categorytype=str(categoryentrylist[i]),maxmembers=int(maximum[i]),maxprojects=int(maxprojs[i])) key=pf.put() idnum=key.id() pf.categoryid=str(idnum) pf.put() self.redirect("/admin") application = webapp.WSGIApplication([('/updatecategory', Category)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
import datetime,cgi import sys import os from google.appengine.ext.webapp import template from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.dist import use_library from os import environ from models import * class MeetMe(webapp.RequestHandler): def post(self): userdetails=db.GqlQuery("SELECT * FROM userDetails") details=[] for i in userdetails: temp=[] temp.append(i.admissionnumber) temp.append(i.username) details.append(temp) date=self.request.get("date") note="Administrator says: come and meet me on '%s'" %date for i in details : if self.request.get(i[0])=="yes": newnote=notificationDetails(admissionnumber=i[0],notification=note) key=newnote.put() idnum=key.id() newnote.notificationid=str(idnum) newnote.put() self.redirect("/meetme") def verifyLogin(self): user = users.get_current_user() if user: usercheck=userDetails.all() usercheck.filter("email =",user.email()) try: currentuser=usercheck.fetch(1)[0] userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'") for i in userdet: if i.privilege=='admin': return elif i.approved==False: self.redirect("/usererror") return self.redirect("/user") except: path = os.path.join(os.pathi.admissionnumber.dirname(__file__),'form.html')#use template self.response.out.write(template.render(path,{"email":user.email()}))#using template else: self.redirect(users.create_login_url(self.request.uri)) def get(self): self.verifyLogin() userdetails=db.GqlQuery("SELECT * FROM userDetails") details=[] for i in userdetails: temp=[] temp.append(i.admissionnumber) temp.append(i.username) details.append(temp) path = os.path.join(os.path.dirname(__file__),'meetme.html')#use template self.response.out.write(template.render(path,{"details":details}))#using template application = webapp.WSGIApplication([('/meetme', MeetMe)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
Python
from sysIB.dbnew import setup_blank_tables from sysIB.dbconnect import get_db_filename, connection from sysIB.dbtablestatic import staticdata from sysIB.dbtablets import tsdata import os import pandas as pd dbname="mydb" dbfilename=get_db_filename(dbname) try: os.remove(dbfilename) except: pass setup_blank_tables(dbfilename, ["CREATE TABLE timeseries (datetime text, code text, price float)", "CREATE TABLE static (code text, fullname text)"]) st_table=staticdata(dbname) st_table.add("FTSE", "FTSE 100 index") assert st_table.read("FTSE")=="FTSE 100 index" st_table.modify("FTSE", "FTSE all share") assert st_table.read("FTSE")=="FTSE all share" st_table.delete("FTSE") assert st_table.read("FTSE") is None dt_table=tsdata(dbname) somprices=pd.TimeSeries(range(100), pd.date_range('1/1/2014', periods=100)) dt_table.add("FTSE", somprices) assert dt_table.read("FTSE").values[-1]==99.0 ## Remove the file so example is clean next time os.remove(dbfilename) print "No problems"
Python
import pandas as pd import numpy as np DEFAULT_VALUE=np.nan class autodf(object): ''' Object to make it easy to add data in rows and return pandas time series Initialise with autodf("name1", "name2", ...) Add rows with autodf.add_row(name1=..., name2=...., ) To data frame with autodf.to_pandas ''' def __init__(self, *args): storage=dict() self.keynames=args for keyname in self.keynames: storage[keyname]=[] self.storage=storage def add_row(self, **kwargs): for keyname in self.storage.keys(): if keyname in kwargs: self.storage[keyname].append(kwargs[keyname]) else: self.storage[keyname].append(DEFAULT_VALUE) def to_pandas(self, indexname=None): if indexname is not None: data=self.storage index=self.storage[indexname] data.pop(indexname) return pd.DataFrame(data, index=index) else: return pd.DataFrame(self.storage) def bs_resolve(x): if x<0: return 'SELL' if x>0: return 'BUY' if x==0: raise Exception("trying to trade with zero") def action_ib_fill(execlist): """ Get fills Note that fills are cumulative, eg for an order of +10 first fill would be +3, then +9, then +10 implying we got 3,6,1 lots in consecutive fills The price of each fill then is the average price for the order so far """ print "recived fill as follows:" print "" print execlist print "" if __name__=="__main__": ans=autodf("datetime", "price", "volume") ans.add_row(datetime=pd.datetime(1985,12,1), price=25.9, volume=30) ans.add_row(datetime=pd.datetime(1985,12,2), price=25.9) ans.add_row(datetime=pd.datetime(1985,12,3), volume=40) print ans.to_pandas("datetime")
Python
from sysIB.wrapper_v5 import IBWrapper, IBclient from swigibpy import Contract as IBcontract import time if __name__=="__main__": """ This simple example places an order, checks to see if it is active, and receives fill(s) Note: If you are running this on the 'edemo' account it will probably give you back garbage Though the mechanics should still work This is because you see the orders that everyone demoing the account is trading!!! """ callback = IBWrapper() client=IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry="201406" ibcontract.symbol="GBL" ibcontract.exchange="DTB" ## Get contract details cdetails=client.get_contract_details(ibcontract) ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm ## expiry since certain contracts expire the month before they should! print "Expiry is %s" % cdetails['expiry'] ## Once you have the portfolio positions then you can use these expiries to map back positions=client.get_IB_positions() accountinfo=client.get_IB_account_data() print "\n Positions" print positions[0] print "\n FX" print positions[1] print "\n account info" print accountinfo
Python
from swigibpy import EWrapper import time import datetime from swigibpy import EPosixClientSocket from sysIB.IButils import autodf ### how many seconds before we give up MAX_WAIT=30 def return_IB_connection_info(): """ Returns the tuple host, port, clientID required by eConnect """ host="" port=4001 clientid=999 return (host, port, clientid) class IBWrapper(EWrapper): """ Callback object passed to TWS, these functions will be called directly by TWS. """ def error(self, id, errorCode, errorString): """ error handling, simple for now Here are some typical IB errors INFO: 2107, 2106 WARNING 326 - can't connect as already connected CRITICAL: 502, 504 can't connect to TWS. 200 no security definition found 162 no trades """ global iserror global finished ## Any errors not on this list we just treat as information ERRORS_TO_TRIGGER=[201, 103, 502, 504, 509, 200, 162, 420, 2105, 1100, 478, 201, 399] if errorCode in ERRORS_TO_TRIGGER: iserror=True errormsg="IB error id %d errorcode %d string %s" %(id, errorCode, errorString) print errormsg finished=True ## Wrapper functions don't have to return anything this is to tidy return 0 def currentTime(self, time_from_server): global the_time_now_is global finished the_time_now_is=time_from_server finished=True def nextValidId(self, orderId): pass def managedAccounts(self, openOrderEnd): pass def historicalData(self, reqId, date, openprice, high, low, close, volume, barCount, WAP, hasGaps): global historicdata global finished if date[:8] == 'finished': finished=True else: date=datetime.datetime.strptime(date,"%Y%m%d") historicdata.add_row(date=date, open=openprice, high=high, low=low, close=close, volume=volume) class IBclient(object): def __init__(self, callback): tws = EPosixClientSocket(callback) (host, port, clientid)=return_IB_connection_info() tws.eConnect(host, port, clientid) self.tws=tws def speaking_clock(self): global the_time_now_is global finished global iserror print "Getting the time..." self.tws.reqCurrentTime() start_time=time.time() finished=False iserror=False the_time_now_is="didnt get time" while not finished: if (time.time() - start_time) > MAX_WAIT: finished=True pass if iserror: print "Error happened" return the_time_now_is def get_IB_historical_data(self, ibcontract, durationStr="1 Y", barSizeSetting="1 day", tickerid=999): """ Returns historical prices for a contract, up to today tws is a result of calling IBConnector() """ global historicdata global finished global iserror finished=False iserror=False today=datetime.datetime.now() historicdata=autodf("date", "open", "high", "low", "close", "volume") # Request some historical data. self.tws.reqHistoricalData( tickerid, # tickerId, ibcontract, # contract, today.strftime("%Y%m%d %H:%M:%S %Z"), # endDateTime, durationStr, # durationStr, barSizeSetting, # barSizeSetting, "TRADES", # whatToShow, 1, # useRTH, 1 # formatDate ) start_time=time.time() while not finished: if (time.time() - start_time) > MAX_WAIT: finished=True iserror=True pass if iserror: raise Exception("Problem getting historic data") results=historicdata.to_pandas("date") return results
Python
from swigibpy import EWrapper import time from swigibpy import EPosixClientSocket, ExecutionFilter from swigibpy import Order as IBOrder from sysIB.IButils import bs_resolve, action_ib_fill MAX_WAIT_SECONDS=10 MEANINGLESS_NUMBER=1830 def return_IB_connection_info(): """ Returns the tuple host, port, clientID required by eConnect """ host="" port=4001 clientid=999 return (host, port, clientid) class IBWrapper(EWrapper): """ Callback object passed to TWS, these functions will be called directly by the TWS or Gateway. """ def error(self, id, errorCode, errorString): """ error handling, simple for now Here are some typical IB errors INFO: 2107, 2106 WARNING 326 - can't connect as already connected CRITICAL: 502, 504 can't connect to TWS. 200 no security definition found 162 no trades """ global iserror global finished ## Any errors not on this list we just treat as information ERRORS_TO_TRIGGER=[201, 103, 502, 504, 509, 200, 162, 420, 2105, 1100, 478, 201, 399] if errorCode in ERRORS_TO_TRIGGER: iserror=True errormsg="IB error id %d errorcode %d string %s" %(id, errorCode, errorString) print errormsg finished=True ## Wrapper functions don't have to return anything this is to tidy return 0 """ Following methods will be called, but we don't use them """ def nextValidId(self, id): pass def managedAccounts(self, openOrderEnd): pass def orderStatus(self, reqid, status, filled, remaining, avgFillPrice, permId, parentId, lastFilledPrice, clientId, whyHeld): pass def commissionReport(self, blah): pass def contractDetailsEnd(self, reqId): """ Finished getting contract details """ global finished finished=True def contractDetails(self, reqId, contractDetails): """ Return contract details If you submit more than one request watch out to match up with reqId """ global contract_details contract_details={} contract_details["contractMonth"]=contractDetails.contractMonth contract_details["liquidHours"]=contractDetails.liquidHours contract_details["longName"]=contractDetails.longName contract_details["minTick"]=contractDetails.minTick contract_details["tradingHours"]=contractDetails.tradingHours contract_details["timeZoneId"]=contractDetails.timeZoneId contract_details["underConId"]=contractDetails.underConId contract_details["evRule"]=contractDetails.evRule contract_details["evMultiplier"]=contractDetails.evMultiplier contract2 = contractDetails.summary contract_details["expiry"]=contract2.expiry contract_details["exchange"]=contract2.exchange contract_details["symbol"]=contract2.symbol contract_details["secType"]=contract2.secType contract_details["currency"]=contract2.currency def updatePortfolio(self, contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName): """ Add a row to the portfolio structure """ portfolio_structure.append((contract.symbol, contract.expiry, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName, contract.currency)) def updateAccountValue(self, key, value, currency, accountName): """ Populates account value dictionary """ account_value.append((key, value, currency, accountName)) def accountDownloadEnd(self, accountName): """ Finished can look at portfolio_structure and account_value """ finished=True def updateAccountTime(self, timeStamp): pass class IBclient(object): """ Client object Used to interface with TWS for outside world, does all handling of streaming waiting etc Create like this callback = IBWrapper() client=IBclient(callback) We then use various methods to get prices etc """ def __init__(self, callback, accountid="DU15237"): """ Create like this callback = IBWrapper() client=IBclient(callback) """ tws = EPosixClientSocket(callback) (host, port, clientid)=return_IB_connection_info() tws.eConnect(host, port, clientid) self.tws=tws self.accountid=accountid def get_contract_details(self, ibcontract): """ Returns a dictionary of contract_details """ global finished global iserror global contract_details finished=False iserror=False contract_details={} self.tws.reqContractDetails( MEANINGLESS_NUMBER, # reqId, ibcontract, # contract, ) start_time=time.time() while not finished: if (time.time() - start_time) > MAX_WAIT_SECONDS: finished=True iserror=True pass if iserror or contract_details=={}: raise Exception("Problem getting details") return contract_details def get_IB_account_data(self): global finished global iserror global account_value finished=False iserror=False account_value=[] ## Turn on the streaming of accounting information self.tws.reqAccountUpdates(True, self.accountid) start_time=time.time() while not finished: if (time.time() - start_time) > MAX_WAIT_SECONDS: finished=True iserror=True pass ## Turn off the streaming ## Note portfolio_structure will also be updated self.tws.reqAccountUpdates(False, self.accountid) if len(account_value)==0 or iserror: msg="No account data recieved" raise Exception(msg) return account_value def get_IB_positions(self): """ Returns positions held - a particular kind of accounting information """ global finished global iserror global portfolio_structure global account_value finished=False iserror=False portfolio_structure=[] account_value=[] ## Ask to get accounting info, both positions and account details self.tws.reqAccountUpdates(True, self.accountid) start_time=time.time() while not finished: if (time.time() - start_time) > MAX_WAIT_SECONDS: finished=True iserror=True pass self.tws.reqAccountUpdates(False, self.accountid) exchange_rates={} ## Create a dictionary of exchange rates for x in account_value: if x[0]=="ExchangeRate": exchange_rates[x[2]]=float(x[1]) return (portfolio_structure, exchange_rates)
Python
from swigibpy import EWrapper import time from swigibpy import EPosixClientSocket ### how many seconds before we give up MAX_WAIT=30 def return_IB_connection_info(): """ Returns the tuple host, port, clientID required by eConnect """ host="" port=4001 clientid=999 return (host, port, clientid) class IBWrapper(EWrapper): """ Callback object passed to TWS, these functions will be called directly by TWS. """ def error(self, id, errorCode, errorString): """ error handling, simple for now Here are some typical IB errors INFO: 2107, 2106 WARNING 326 - can't connect as already connected CRITICAL: 502, 504 can't connect to TWS. 200 no security definition found 162 no trades """ global iserror global finished ## Any errors not on this list we just treat as information ERRORS_TO_TRIGGER=[201, 103, 502, 504, 509, 200, 162, 420, 2105, 1100, 478, 201, 399] if errorCode in ERRORS_TO_TRIGGER: iserror=True errormsg="IB error id %d errorcode %d string %s" %(id, errorCode, errorString) print errormsg finished=True ## Wrapper functions don't have to return anything this is to tidy return 0 def currentTime(self, time_from_server): global the_time_now_is global finished the_time_now_is=time_from_server finished=True def nextValidId(self, orderId): pass def managedAccounts(self, openOrderEnd): pass class IBclient(object): def __init__(self, callback): tws = EPosixClientSocket(callback) (host, port, clientid)=return_IB_connection_info() tws.eConnect(host, port, clientid) self.tws=tws def speaking_clock(self): global the_time_now_is global finished global iserror print "Getting the time..." self.tws.reqCurrentTime() start_time=time.time() finished=False iserror=False the_time_now_is="didnt get time" while not finished: if (time.time() - start_time) > MAX_WAIT: finished=True pass if iserror: print "Error happened" return the_time_now_is
Python
from swigibpy import EWrapper import time import numpy as np import datetime from swigibpy import EPosixClientSocket MEANINGLESS_ID=502 def return_IB_connection_info(): """ Returns the tuple host, port, clientID required by eConnect """ host="" port=4001 clientid=999 return (host, port, clientid) class IBWrapper(EWrapper): """ Callback object passed to TWS, these functions will be called directly by the TWS or Gateway. """ def error(self, id, errorCode, errorString): """ error handling, simple for now Here are some typical IB errors INFO: 2107, 2106 WARNING 326 - can't connect as already connected CRITICAL: 502, 504 can't connect to TWS. 200 no security definition found 162 no trades """ global iserror global finished ## Any errors not on this list we just treat as information ERRORS_TO_TRIGGER=[201, 103, 502, 504, 509, 200, 162, 420, 2105, 1100, 478, 201, 399] if errorCode in ERRORS_TO_TRIGGER: iserror=True errormsg="IB error id %d errorcode %d string %s" %(id, errorCode, errorString) print errormsg finished=True ## Wrapper functions don't have to return anything this is to tidy return 0 def nextValidId(self, orderId): pass def managedAccounts(self, openOrderEnd): pass def realtimeBar(self, reqId, time, open, high, low, close, volume, wap, count): """ Note we don't use all the information here Just append close prices. """ global pricevalue global finished pricevalue.append(close) def tickString(self, TickerId, field, value): global marketdata ## update string ticks tickType=field if int(tickType)==0: ## bid size marketdata[0]=int(value) elif int(tickType)==3: ## ask size marketdata[1]=int(value) elif int(tickType)==1: ## bid marketdata[0][2]=float(value) elif int(tickType)==2: ## ask marketdata[0][3]=float(value) def tickGeneric(self, TickerId, tickType, value): global marketdata ## update generic ticks if int(tickType)==0: ## bid size marketdata[0]=int(value) elif int(tickType)==3: ## ask size marketdata[1]=int(value) elif int(tickType)==1: ## bid marketdata[2]=float(value) elif int(tickType)==2: ## ask marketdata[3]=float(value) def tickSize(self, TickerId, tickType, size): ## update ticks of the form new size global marketdata if int(tickType)==0: ## bid marketdata[0]=int(size) elif int(tickType)==3: ## ask marketdata[1]=int(size) def tickPrice(self, TickerId, tickType, price, canAutoExecute): ## update ticks of the form new price global marketdata if int(tickType)==1: ## bid marketdata[2]=float(price) elif int(tickType)==2: ## ask marketdata[3]=float(price) def updateMktDepth(self, id, position, operation, side, price, size): """ Only here for completeness - not required. Market depth is only available if you subscribe to L2 data. Since I don't I haven't managed to test this. Here is the client side call for interest tws.reqMktDepth(999, ibcontract, 9) """ pass def tickSnapshotEnd(self, tickerId): finished=True class IBclient(object): """ Client object Used to interface with TWS for outside world, does all handling of streaming waiting etc Create like this callback = IBWrapper() client=IBclient(callback) We then use various methods to get prices etc """ def __init__(self, callback): """ Create like this callback = IBWrapper() client=IBclient(callback) """ tws = EPosixClientSocket(callback) (host, port, clientid)=return_IB_connection_info() tws.eConnect(host, port, clientid) self.tws=tws def get_IB_market_data(self, ibcontract, seconds=30): """ Returns more granular market data Returns a tuple (bid price, bid size, ask price, ask size) """ global marketdata global finished global iserror finished=False iserror=False ## initialise the tuple marketdata=[np.nan, np.nan, np.nan, np.nan] # Request a market data stream self.tws.reqMktData( MEANINGLESS_ID, ibcontract, "", False) start_time=time.time() while not finished: if (time.time() - start_time) > seconds: finished=True pass self.tws.cancelMktData(MEANINGLESS_ID) ## marketdata should now contain some interesting information ## Note in this implementation we overwrite the contents with each tick; we could keep them if iserror: raise Exception("Problem getting market data") return marketdata def get_IB_snapshot_prices(self, ibcontract): """ Returns a list of snapshotted prices, averaged over 'real time bars' tws is a result of calling IBConnector() """ tws=self.tws global finished global iserror global pricevalue iserror=False finished=False pricevalue=[] # Request current price in 5 second increments # It turns out this is the only way to do it (can't get any other increments) tws.reqRealTimeBars( MEANINGLESS_ID, # tickerId, ibcontract, # contract, 5, "MIDPOINT", 0) start_time=time.time() ## get about 16 seconds worth of samples ## could obviously just stop at N bars as well eg. while len(pricevalue)<N: while not finished: if iserror: finished=True if (time.time() - start_time) > 20: ## get ~4 samples over 15 seconds finished=True pass ## Cancel the stream tws.cancelRealTimeBars(MEANINGLESS_ID) if len(pricevalue)==0 or iserror: raise Exception("Failed to get price") return pricevalue
Python
from sysIB.wrapper_v3 import IBWrapper, IBclient from swigibpy import Contract as IBcontract if __name__=="__main__": """ This simple example returns streaming price data """ callback = IBWrapper() client=IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry="201406" ibcontract.symbol="GBL" ibcontract.exchange="DTB" ans=client.get_IB_snapshot_prices(ibcontract) print "Real time prices over seconds" print ans ans=client.get_IB_market_data(ibcontract) print "Bid size, Ask size; Bid price; Ask price" print ans
Python
from sysIB.wrapper import IBWrapper, IBclient if __name__=="__main__": """ This simple example returns the time """ callback = IBWrapper() client=IBclient(callback) print client.speaking_clock()
Python
from sysIB.wrapper import IBWrapper, IBclient if __name__=="__main__": """ This simple example returns the time """ callback = IBWrapper() client=IBclient(callback) print client.speaking_clock()
Python
""" Static example """ from sysIB.dbconnect import connection class staticdata(object): ''' Very basic table for static data Does not do checking eg for multiple records etc ''' def __init__(self, dbname): self.connection=connection(dbname) def add(self, code, fullname): self.connection.write("INSERT INTO static VALUES (?, ?)", (code, fullname)) def modify(self, code, newname): self.connection.write("UPDATE static SET fullname=? WHERE code=?", (newname, code)) def read(self, code): ans=self.connection.read("SELECT fullname FROM static WHERE code=?", (code,)) if len(ans)==0: return None return str(ans[0][0]) def delete(self, code): self.connection.write("DELETE FROM static WHERE code=?", (code,))
Python
from sysIB.wrapper_v2 import IBWrapper, IBclient from swigibpy import Contract as IBcontract from matplotlib.pyplot import show if __name__=="__main__": """ This simple example returns the time """ callback = IBWrapper() client=IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry="201406" ibcontract.symbol="Z" ibcontract.exchange="LIFFE" ans=client.get_IB_historical_data(ibcontract) ans.close.plot() show()
Python
""" Time series database example """ from sysIB.dbconnect import connection import pandas as pd import datetime def date_as_string(dtobject=datetime.datetime.now()): return str(dtobject.strftime("%Y-%m-%d %H:%M:%S.%f")) class tsdata(object): ''' Very basic table for ts data Does not do checking eg for multiple records etc ''' def __init__(self, dbname): self.connection=connection(dbname) def add(self, code, pandasts): for datetime in pandasts.index: price=pandasts[datetime] self.addrow(code, datetime, price) def addrow(self, code, datetime, price): self.connection.write("INSERT INTO timeseries VALUES (?, ?, ?)", (date_as_string(datetime), code, float(price))) def read(self, code): ans=self.connection.read("SELECT datetime, price FROM timeseries WHERE code=?", (code,)) dindex=[pd.to_datetime(x[0]) for x in ans] prices=[float(x[1]) for x in ans] ans=pd.TimeSeries(prices, index=dindex) return ans
Python
""" This abstracts the database connection, i.e. exact file and way of accessing The init of the object returns a database connection object which can be used to do common things """ import sqlite3 DBDICT=dict(mydb="mydb.db") def get_db_filename(dbname): try: dbfilename=DBDICT[dbname] except KeyError: raise Exception("%s not in DBDICT" % dbname) return dbfilename def get_db_connsql3_for(dbname): """ Database connections Returns a sqllite3 connection """ dbfilename=get_db_filename(dbname) try: conn=sqlite3.connect(dbfilename, timeout=30) except: error_msg="Couldn't connect to database specified as %s resolved to %s" % (dbfilename, dbfilename) raise Exception(error_msg) return conn class connection(object): ''' object is a connection ''' def __init__(self, dbname): self.conn=get_db_connsql3_for(dbname) def close(self): """ Close the database connection """ self.conn.close() def write(self, sqltext, argtuplelist=[]): """ """ if len(argtuplelist)==0: self.conn.execute(sqltext) else: self.conn.execute(sqltext, argtuplelist) self.conn.commit() def read(self, sqltext, argtuplelist=[]): """ Perform a generic select command, returns list of lists """ self.conn.row_factory=sqlite3.Row if len(argtuplelist)==0: ans=self.conn.execute(sqltext) else: ans=self.conn.execute(sqltext, argtuplelist) ans=ans.fetchall() return ans
Python
from sysIB.wrapper_v4 import IBWrapper, IBclient from swigibpy import Contract as IBcontract import time if __name__=="__main__": """ This simple example places an order, checks to see if it is active, and receives fill(s) Note: If you are running this on the 'edemo' account it will probably give you back garbage Though the mechanics should still work This is because you see the orders that everyone demoing the account is trading!!! """ callback = IBWrapper() client=IBclient(callback) ibcontract = IBcontract() ibcontract.secType = "FUT" ibcontract.expiry="201406" ibcontract.symbol="GBL" ibcontract.exchange="DTB" ## Get contract details cdetails=client.get_contract_details(ibcontract) ## In particular we want the expiry. You cannot just use cdetails['expiry'][:6] to map back to the yyyymm ## expiry since certain contracts expire the month before they should! print "Expiry is %s" % cdetails['expiry'] ## Place the order, asking IB to tell us what the next order id is ## Note limit price of zero orderid1=client.place_new_IB_order(ibcontract, 10, 0.0, "MKT", orderid=None) print "" print "Placed market order, orderid is %d" % orderid1 ## And here is a limit order, unlikely ever to be filled ## Note limit price of 100 orderid2=client.place_new_IB_order(ibcontract, -10, 200.0, "LMT", orderid=None) print "" print "Placed limit order, orderid is %d" % orderid2 ## Short wait so dialog is in order, not neccessary time.sleep(5) order_structure=client.get_open_orders() ## Note that the market order has probably filled by now print "Active orders: (should just be limit order)" print order_structure print "" print "Cancelling the limit order" client.tws.cancelOrder(orderid2) print "Waiting for cancellation to finish" while client.any_open_orders(): pass print "No active orders now" print client.any_open_orders() print "" ## Get the executions (gives you everything for last business day) execlist=client.get_executions() print "Following executed since midnight this morning:" print "" print execlist
Python
import sqlite3 import os import stat def setup_blank_tables(dbfilename, setupcodelist): """ setup a new sqllite database """ with sqlite3.connect(dbfilename) as conn: for setuptable in setupcodelist: conn.execute(setuptable) conn.commit() ## Set permissions os.chmod(dbfilename, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH) print "created %s " % dbfilename
Python
from swigibpy import EWrapper import time from swigibpy import EPosixClientSocket, ExecutionFilter from swigibpy import Order as IBOrder from sysIB.IButils import bs_resolve, action_ib_fill MAX_WAIT_SECONDS=10 MEANINGLESS_NUMBER=1729 def return_IB_connection_info(): """ Returns the tuple host, port, clientID required by eConnect """ host="" port=4001 clientid=999 return (host, port, clientid) class IBWrapper(EWrapper): """ Callback object passed to TWS, these functions will be called directly by the TWS or Gateway. """ def error(self, id, errorCode, errorString): """ error handling, simple for now Here are some typical IB errors INFO: 2107, 2106 WARNING 326 - can't connect as already connected CRITICAL: 502, 504 can't connect to TWS. 200 no security definition found 162 no trades """ global iserror global finished ## Any errors not on this list we just treat as information ERRORS_TO_TRIGGER=[201, 103, 502, 504, 509, 200, 162, 420, 2105, 1100, 478, 201, 399] if errorCode in ERRORS_TO_TRIGGER: iserror=True errormsg="IB error id %d errorcode %d string %s" %(id, errorCode, errorString) print errormsg finished=True ## Wrapper functions don't have to return anything this is to tidy return 0 """ Following methods will be called, but we don't use them """ def managedAccounts(self, openOrderEnd): pass def orderStatus(self, reqid, status, filled, remaining, avgFillPrice, permId, parentId, lastFilledPrice, clientId, whyHeld): pass def commissionReport(self, blah): pass def execDetails(self, reqId, contract, execution): """ This is called if a) we have submitted an order and a fill has come back (in which case getting_executions is False) b) We have asked for recent fills to be given to us (in which case it is True) In case (a) we call action_ib_fill with the fill details; and for case (b) we add the fill to a list See API docs, C++, SocketClient Properties, Contract and Execution for more details """ global execlist global getting_executions execid=execution.execId exectime=execution.time thisorderid=execution.orderId account=execution.acctNumber exchange=execution.exchange permid=execution.permId avgprice=execution.price cumQty=execution.cumQty clientid=execution.clientId symbol=contract.symbol expiry=contract.expiry side=execution.side execdetails=dict(side=str(side), times=str(exectime), orderid=str(thisorderid), qty=int(cumQty), price=float(avgprice), symbol=str(symbol), expiry=str(expiry), clientid=str(clientid), execid=str(execid), account=str(account), exchange=str(exchange), permid=int(permid)) if getting_executions: execlist.append(execdetails) else: ## one off fill action_ib_fill(execdetails) def execDetailsEnd(self, reqId): """ No more orders to look at if execution details requested """ global finished finished=True def openOrder(self, orderID, contract, order, orderState): """ Tells us about any orders we are working now Note these objects are not persistent or interesting so we have to extract what we want """ global order_structure ## Get a selection of interesting things about the order orderdict=dict(symbol=contract.symbol , expiry=contract.expiry, qty=int(order.totalQuantity) , side=order.action , orderid=orderID, clientid=order.clientId ) order_structure.append(orderdict) def nextValidId(self, orderId): """ Give the next valid order id Note this doesn't 'burn' the ID; if you call again without executing the next ID will be the same """ global brokerorderid global finished brokerorderid=orderId def openOrderEnd(self): """ Finished getting open orders """ global finished finished=True def contractDetailsEnd(self, reqId): """ Finished getting contract details """ global finished finished=True def contractDetails(self, reqId, contractDetails): """ Return contract details If you submit more than one request watch out to match up with reqId """ global contract_details contract_details={} contract_details["contractMonth"]=contractDetails.contractMonth contract_details["liquidHours"]=contractDetails.liquidHours contract_details["longName"]=contractDetails.longName contract_details["minTick"]=contractDetails.minTick contract_details["tradingHours"]=contractDetails.tradingHours contract_details["timeZoneId"]=contractDetails.timeZoneId contract_details["underConId"]=contractDetails.underConId contract_details["evRule"]=contractDetails.evRule contract_details["evMultiplier"]=contractDetails.evMultiplier contract2 = contractDetails.summary contract_details["expiry"]=contract2.expiry contract_details["exchange"]=contract2.exchange contract_details["symbol"]=contract2.symbol contract_details["secType"]=contract2.secType contract_details["currency"]=contract2.currency class IBclient(object): """ Client object Used to interface with TWS for outside world, does all handling of streaming waiting etc Create like this callback = IBWrapper() client=IBclient(callback) We then use various methods to get prices etc """ def __init__(self, callback): """ Create like this callback = IBWrapper() client=IBclient(callback) """ tws = EPosixClientSocket(callback) (host, port, clientid)=return_IB_connection_info() tws.eConnect(host, port, clientid) self.tws=tws def get_contract_details(self, ibcontract): """ Returns a dictionary of contract_details """ global finished global iserror global contract_details finished=False iserror=False contract_details={} self.tws.reqContractDetails( MEANINGLESS_NUMBER, # reqId, ibcontract, # contract, ) start_time=time.time() while not finished: if (time.time() - start_time) > MAX_WAIT_SECONDS: finished=True iserror=True pass if iserror or contract_details=={}: raise Exception("Problem getting details") return contract_details def get_next_brokerorderid(self): """ Get the next brokerorderid """ global finished global brokerorderid global iserror finished=False brokerorderid=None iserror=False start_time=time.time() ## Note for more than one ID change '1' self.tws.reqIds(1) while not finished: if (time.time() - start_time) > MAX_WAIT_SECONDS: finished=True if brokerorderid is not None: finished=True pass if brokerorderid is None or iserror: raise Exception("Problem getting next broker orderid") return brokerorderid def place_new_IB_order(self, ibcontract, trade, lmtPrice, orderType, orderid=None): """ Places an order Returns brokerorderid raises exception if fails """ global iserror global brokerorderid global finished global getting_executions global order_structure iborder = IBOrder() iborder.action = bs_resolve(trade) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(trade) iborder.tif='DAY' iborder.transmit=True getting_executions=False order_structure=[] ## We can eithier supply our own ID or ask IB to give us the next valid one if orderid is None: print "Getting orderid from IB" orderid=self.get_next_brokerorderid() print "Using order id of %d" % orderid # Place the order self.tws.placeOrder( orderid, # orderId, ibcontract, # contract, iborder # order ) return orderid def any_open_orders(self): """ Simple wrapper to tell us if we have any open orders """ return len(self.get_open_orders())>0 def get_open_orders(self): """ Returns a list of any open orders """ global finished global iserror global order_structure iserror=False finished=False order_structure=[] start_time=time.time() self.tws.reqAllOpenOrders() while not finished: if (time.time() - start_time) > MAX_WAIT_SECONDS: ## You should have thought that IB would teldl you we had finished finished=True pass if iserror: raise Exception("Problem getting open orders") return order_structure def get_executions(self): """ Returns a list of all executions done today """ global finished global iserror global execlist global getting_executions iserror=False finished=False execlist=[] ## Tells the wrapper we are getting executions, not expecting fills ## Note that if you try and get executions when fills should be coming will be confusing! ## BE very careful with fills code getting_executions=True start_time=time.time() ## We can change ExecutionFilter to subset different orders self.tws.reqExecutions(MEANINGLESS_NUMBER, ExecutionFilter()) while not finished: if (time.time() - start_time) > MAX_WAIT_SECONDS: finished=True iserror=True pass ## Change this flag back so that the process gets fills properly getting_executions=False if iserror: raise Exception("Problem getting executions") return execlist
Python
#!/usr/bin/python import sys from Foundation import * from ScriptingBridge import * ab = SBApplication.applicationWithBundleIdentifier_("com.apple.AddressBook") for person in ab.people(): fname = person.firstName() pfname = person.phoneticFirstName() lname = person.lastName() plname = person.phoneticLastName() note = person.note() print "%s %s %s %s %s" % (fname, pfname, lname, plname, note) if pfname and plname: cname = lname + fname if note: note = cname + "\n" + note else: note = cname person.setPhoneticLastName_("") person.setPhoneticFirstName_("") person.setFirstName_(pfname) person.setLastName_(plname) person.setNote_(note) print "Done."
Python
#!/usr/bin/env python import sys import re def ip2int(ip) : ret = 0 match = re.match("(\d*)\.(\d*)\.(\d*)\.(\d*)", ip) if not match : return 0 for i in xrange(4) : ret = (ret << 8) + int(match.groups()[i]) return ret def int2ip(ipnum) : ip1 = ipnum >> 24 ip2 = ipnum >> 16 & 0xFF ip3 = ipnum >> 8 & 0xFF ip4 = ipnum & 0xFF return "%d.%d.%d.%d" % (ip1, ip2, ip3, ip4) def printrange(startip, endip) : bits = 1 mask = 1 while bits < 32 : newip = startip | mask if (newip>endip) or (((startip>>bits) << bits) != startip) : bits = bits - 1 mask = mask >> 1 break bits = bits + 1 mask = (mask<<1) + 1 newip = startip | mask bits = 32 - bits print "%s/%d" % (int2ip(startip), bits) if newip < endip : printrange(newip + 1, endip) while 1 : line = sys.stdin.readline().strip() if not line : break chars = line.split(" ") print "#%s - %s" % (chars[0], chars[1]) ip1 = ip2int(chars[0]) ip2 = ip2int(chars[1]) printrange(ip1, ip2)
Python
#!/usr/bin/env python import sys import os from types import StringType # get bencode package from http://github.com/fishy/scripts/downloads from bencode.bencode import bencode, bdecode, BTFailure try : torrent = sys.argv[1] except IndexError : print "Usage: \"%s <torrent_file> [tracker_url]\" to show torrent info (without tracker_url), or to add tracker(s)" % sys.argv[0] sys.exit() size = os.stat(torrent).st_size file = open(torrent, "rb") data = file.read(size) file.close() info = bdecode(data) if len(sys.argv) == 2 : print info sys.exit() if 'announce-list' not in info : list = [info['announce']] for i in range(len(sys.argv)-2) : tracker = sys.argv[i+2] if tracker not in list : list.append(tracker) print list info['announce-list'] = [list] else : list = info['announce-list'][0] if type(list) == StringType : list = [list] for i in range(len(sys.argv)-2) : tracker = sys.argv[i+2] if tracker not in list : list.append(tracker) print list info['announce-list'][0] = list writedata = bencode(info) file = open(torrent, "wb") file.write(writedata) file.close()
Python
#!/usr/bin/env python import sys, getpass, getopt import hmac, hashlib, base64 lengths = [20] # default value optlist, args = getopt.getopt(sys.argv[1:], 'hl:', [ 'length=', 'help' ]) for opt in optlist : name, value = opt if (name == '-l') or (name == '--length') : lengths = value.split(',') for i in xrange(len(lengths)) : try : lengths[i] = int(lengths[i]) except ValueError : sys.stderr.write('ERROR: \"%s\" is not a valid length arg.\n' % value) sys.exit(-1) elif (name == '-h') or (name == '--help') : print 'Usage:' print ' %s [-l|--length lengths] [sitekey]' % sys.argv[0] print ' %s -h|--help' % sys.argv[0] print print 'optional arguments:' print ' -h, --help\tshow this help message and exit' print ' -l, --length\tset a comma seperated output password length list, default=20' print ' sitekey\tthe main name of the domain (e.g. \"google\", \"facebook\", etc.)' print print 'tip:' print ' you can add the following line to your bashrc to set default lengths to 8, 10 & 20:' print '\talias onepwd=\"onepwd.py --length=8,10,20\"' print sys.exit(0) try : msg = args[0] except IndexError : sys.stderr.write(' sitekey: ') msg = sys.stdin.readline().rstrip() key = getpass.getpass('masterkey: ', sys.stderr) pwd = base64.b64encode(hmac.new(key, msg, hashlib.md5).digest()).rstrip('=').replace('+', '').replace('/', '') sys.stderr.write('\n') for length in lengths : sys.stdout.write('%4d: ' % length) sys.stdout.write(pwd[:length]) sys.stdout.flush() sys.stderr.write('\n')
Python
#!/usr/bin/env python import sys import re line = sys.stdin.readline().strip() if not line : sys.exit() names = line.split(",") for i in range(len(names)) : names[i] = names[i].strip(' \t\r\n\x00') timere = re.compile(r'(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)') print r'<?xml version="1.0" encoding="UTF-8"?>' print r'<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1">' waypoints = [] print r'<trk>' print r'<trkseg>' while 1 : line = sys.stdin.readline().strip() if not line : break fields = line.split(",") point = {} for i in range(len(fields)) : point[names[i]] = fields[i].strip(' \t\r\n\x00') if names[i] == "LATITUDE N/S" : str = point[names[i]] point[names[i]] = float(point[names[i]].strip('NS')) if str.rfind('S') != -1 : point[names[i]] = 0 - point[names[i]] elif names[i] == "LONGITUDE E/W" : str = point[names[i]] point[names[i]] = float(point[names[i]].strip('EW')) if str.rfind('W') != -1 : point[names[i]] = 0 - point[names[i]] elif names[i] == "HDOP" or names[i] == "VDOP" or names[i] == "PDOP" : try : point[names[i]] = float(point[names[i]]) except ValueError : pass try : if point['HDOP'] <= 0 or point['HDOP'] >= 20 or point['VDOP'] <= 0 or point['VDOP'] >= 20 or point['PDOP'] <= 0 or point['PDOP'] >= 20 : continue except KeyError : pass # fix missed keys try : foo = point['HDOP'] except KeyError : point['HDOP'] = 0 try : foo = point['VDOP'] except KeyError : point['VDOP'] = 0 try : foo = point['PDOP'] except KeyError : point['PDOP'] = 0 try : foo = point['VALID'] except KeyError : point['VALID'] = None try : foo = point['FIX MODE'] except KeyError : point['FIX MODE'] = None point['fix'] = 'none' if point['VALID'] == 'DGPS' : point['fix'] = 'dgps' elif point['FIX MODE'] == '2D' : point['fix'] = '2d' elif point['FIX MODE'] == '3D' : point['fix'] = '3d' else : point['fix'] = 'none' del point['FIX MODE'] del point['VALID'] timestr = point['DATE'] + point['TIME'] del point['DATE'] del point['TIME'] groups = timere.match(timestr) if groups : point['time'] = "20%s-%s-%sT%s:%s:%sZ" % (groups.group(1), groups.group(2), groups.group(3), groups.group(4), groups.group(5), groups.group(6)) else : point['time'] = "" point['name'] = point['VOX'] del point['VOX'] if point['TAG'] == 'C' : point['name'] = "Waypoint #%d" % len(waypoints) if len(point['name']) > 0 : waypoints.append(point) print r'<trkpt lat="%f" lon="%f"><time>%s</time><ele>%s</ele><course>%s</course><speed>%s</speed><fix>%s</fix><hdop>%f</hdop><vdop>%f</vdop><pdop>%f</pdop></trkpt>' % ( point['LATITUDE N/S'], point['LONGITUDE E/W'], point['time'], point['HEIGHT'], point['HEADING'], point['SPEED'], point['fix'], point['HDOP'], point['VDOP'], point['PDOP']) print r'</trkseg>' print r'</trk>' for point in waypoints : print r'<wpt lat="%f" lon="%f"><name>%s</name><desc>%s</desc><time>%s</time><ele>%s</ele><course>%s</course><speed>%s</speed><fix>%s</fix><hdop>%f</hdop><vdop>%f</vdop><pdop>%f</pdop></wpt>' % ( point['LATITUDE N/S'], point['LONGITUDE E/W'], point['name'], point['name'], point['time'], point['HEIGHT'], point['HEADING'], point['SPEED'], point['fix'], point['HDOP'], point['VDOP'], point['PDOP']) print r'</gpx>'
Python
#!/usr/bin/env python import sys, os, re import zipfile import tempfile import shutil # if your case is not zh-CN, change it here LANG = "zh-CN" # and yes, it's "zh-CN", NOT "zh_CN" tag = "xml:lang" html_re = re.compile(r'(\<html[^\>]*)\>') replace = r'\1 %s="%s">' % (tag, LANG) def addZip(archive, base, curdir) : dirname = os.path.join(base, curdir) for f in os.listdir(dirname) : filename = os.path.join(curdir, f) fullname = os.path.join(base, filename) if os.path.isfile(fullname) : if f.lower().endswith("html") or f.lower().endswith("xml") : [tmpFile, tmpName] = tempfile.mkstemp() tmpFile = os.fdopen(tmpFile, 'w') htmlFile = open(fullname, 'r') for line in htmlFile.xreadlines() : if line.find(tag) == -1 : newline = html_re.sub(replace, line) if newline != line : logfile.write(filename + ":\n") logfile.write(line) logfile.write("->\n") logfile.write(newline) logfile.write("\n") line = newline tmpFile.write(line) tmpFile.close() os.remove(fullname) os.rename(tmpName, fullname) archive.write(fullname, filename) elif os.path.isdir(fullname) : addZip(archive, base, filename) try : epub = sys.argv[1] except IndexError : print "Usage: \"%s <filename.epub>\" to fix filename.epub, get filename.fix.epub" % sys.argv[0] sys.exit() tmpdir = tempfile.mkdtemp() logfile = os.fdopen(2, 'w') # use stderr epubFile = zipfile.ZipFile(epub, "r") epubFile.extractall(tmpdir) epubFile.close() epub = re.sub(r'(.*)\.epub', r'\1.fix.epub', epub) epubFile = zipfile.ZipFile(epub, "w", zipfile.ZIP_DEFLATED) addZip(epubFile, tmpdir, '.') epubFile.close() shutil.rmtree(tmpdir)
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python