def doSetVolume(val): vcmd = { 'cmd' : 'Volume', 'args' : {'value' : val}} for ip in Hosts().getHostIps(): if ip == Hosts().getLocalHost(): setVolume(val) continue Hosts().sendToHost(ip,vcmd)
def __init__(self, username): self.name = username gateway_hostgroup = config.get('gateway_group') idp = config.get('idp') logging.debug("Core: using Identity Provider {0}".format(idp)) self.hosts = Hosts(config, self.name, gateway_hostgroup, idp) self.allowed_ssh_hosts, self.hostgroups = self.hosts.list_allowed()
def sendVoiceMsg(cmdStr): cmd = { 'cmd' : cmdStr, 'args' : [""] } for ip in Hosts().getHostIps(): phrase = Hosts().getAttr(ip,'phrase') if phrase['enabled'] and phrase['voice']: Hosts().sendToHost(ip,cmd) return 0
def run(self): print("%s starting" % self.name) self.setRunning(SoundFile().testBumpCollection()) loop = Specs().s['musicLoop'] while self.isRunning(): if self.checkMsg(): continue entry = SoundFile().getSoundEntry() Debug().p("player choosing %s" % entry) count = 0 if self.musicBlocks[Hosts().getLocalHost()].mute: Debug().p("%s local %s mute so ignoring" % (self.name, Hosts().getLocalHost())) else: for t in SoundTrackManager().eventThreads: choice = random.choice(entry) Debug().p("sending %s request to %s" % (choice, t.name)) t.setCurrentSound(choice) for ip in self.musicBlocks.keys(): if Hosts().isLocalHost(ip): Debug().p("%s: ignoring %s" % (self.name, ip)) continue if self.musicBlocks[ip].mute: Debug().p("%s: ignoring muted %s %s" % (self.name, ip, self.musicBlocks[ip].mute)) continue try: url = "http://" + ip + ":8080" Debug().p("%s: url: %s" % (self.name, url)) cmd = {'cmd': "Sound", 'args': choice} req = urllib2.Request(url, json.dumps(cmd), {'Content-Type': 'application/json'}) timeout = 1 f = urllib2.urlopen(req, None, timeout) test = f.read() Debug().p("%s: got response:%s" % (self.name, test)) except urllib2.URLError as ve: Debug().p("%s: got URLError %s on ip:%s" % (self.name, ve, ip)) continue except Exception as e: print("%s got exception %s" % (self.name, e)) continue self.waitTime = random.randint(Specs().s['minChange'], Specs().s['maxChange']) Debug().p("next change: %d" % self.waitTime) #Debug().p("number busy channels %d"%n if SoundFile().testBumpCollection() is False: print "waiting for channels to be done" n = pygame.mixer.get_busy() while n != 0: n = pygame.mixer.get_busy() print "number busy channels", n if self.checkMsg(): continue if loop: SoundFile().setCurrentCollection(self.collection) else: self.SetRunning(false) self.doExit()
def __init__(self, username): self.name = username configparser = ConfigParser() configparser.read(config_file) gateway_hostgroup = configparser.get('General', 'gateway_group') self.hosts = Hosts(username, gateway_hostgroup) self.allowed_ssh_hosts = self.hosts.list_allowed()
class User(object): def __init__(self, username): self.name = username gateway_hostgroup = config.get('gateway_group') idp = config.get('idp') logging.debug("Core: using Identity Provider {0}".format(idp)) self.hosts = Hosts(config, self.name, gateway_hostgroup, idp) self.allowed_ssh_hosts, self.hostgroups = self.hosts.list_allowed() def get_priv_key(self): try: # TODO: check better identity options privkey = paramiko.RSAKey.from_private_key_file( os.path.expanduser("~/.ssh/id_rsa")) except Exception as e: logging.error( "Core: Invalid Private Key for user {0} : {1} ".format( self.name, e.message)) raise Exception("Core: Invalid Private Key") else: return privkey def refresh_allowed_hosts(self, fromcache): logging.info( "Core: reloading hosts for user {0} from backened identity provider".format( self.name)) self.allowed_ssh_hosts, self.hostgroups = self.hosts.list_allowed( from_cache=fromcache)
def test_scenario3(self): '''Scenario 3.''' h=Hosts(self.hostsfile) h['localhost'] = '10.0.0.3' h['10.0.0.3'] ='toto' del h['toto'] del h['broadcasthost'] # Add a name to an address, change the address of a hostname h['localhost'] = '127.0.0.1' h.append('localhost', 'localhost.yemen') del h['127.0.0.1'] h.write(self.emptyfile) correct = """## # Host Database # # localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 1.0.0.1 localhost localhost.yemen # very pertinent comment ::1 localhost fe80::1%lo0 localhost 1.0.0.2 mc02 """ self.assertEqual(file(self.emptyfile).read(), '')
def doStartMusic(cmd): smcmd = { 'cmd' : 'StartMusic', 'args' : [""] } hosts = Hosts().getHostIps() for ip in hosts: music = Hosts().getAttr(ip,'music') if music['enabled']: Hosts().sendToHost(ip,smcmd) return 0
def sendRecogMsg(cmdStr): cmd = { 'cmd' : cmdStr, 'args' : [""] } rval = "" for ip in Hosts().getHostIps(): recog = Hosts().getAttr(ip,'recog') if recog['enabled'] and recog['engine']: rval = Hosts().sendToHost(ip,cmd) return rval
def test_del(self): '''Del''' h=Hosts() h['mc'], h['mc02'], h['127.0.0.1'] = '10.0.0.1', '10.0.0.2', 'localhost' del h['10.0.0.1'] del h['mc02'] del h['localhost'] self.assertRaises(KeyError, h.__delitem__, 'tata') self.assertEqual(h.keys(), [])
def test_remove_one(self): self.hosts.set_one("test", "1.2.3.4") self.hosts.write(self.hosts_file) self.hosts = Hosts(self.hosts_file) self.hosts.remove_one("test") self.hosts.write(self.hosts_file) self.assertDoesNotHaveHostLine("1.2.3.4 test")
def test_write(self): '''Write''' h=Hosts() h['localhost'], h['mc02'] = '1.0.0.1', '1.0.0.2' h.write(self.emptyfile) h.write(self.emptyfile) correct = '1.0.0.1\t\t\tlocalhost\n1.0.0.2\t\t\tmc02\n' self.assertEqual(file(self.emptyfile).read(), correct)
def test_constructor(self): '''Constructors and read''' eq=self.assertEqual h=Hosts() eq(h.keys(),[]) h=Hosts(mc='1.0.0.1', mc02='1.0.0.2') eq(h['mc'],'1.0.0.1') eq(h['mc02'],'1.0.0.2') eq(h['1.0.0.1'],'mc') eq(h['1.0.0.2'],'mc02') h=Hosts({'pc':'1.0.0.3','pc02':'1.0.0.4'}) eq(h['pc'],'1.0.0.3') eq(h['pc02'],'1.0.0.4') eq(h['1.0.0.3'],'pc') eq(h['1.0.0.4'],'pc02') h=Hosts(self.hostsfile, ac03='1.0.0.5', ac02='1.0.0.6') eq(h['ac03'],'1.0.0.5') eq(h['ac02'],'1.0.0.6') eq(h['broadcasthost'],'255.255.255.255') eq(h['127.0.0.1'],'localhost localhost.yemen') eq(h['localhost.yemen'],'127.0.0.1') eq(h['localhost'],'127.0.0.1')
def test_keys_values(self): '''Parsing regexp''' line=Hosts().line for (i,(a,h)) in self.options: m=line.match(i) self.assertEqual( m.group('address'), a ) self.assertEqual( m.group('hostnames'), h ) for i in self.broken_options: self.assertEqual( line.match(i), None )
def test_read(self): '''Read''' eq=self.assertEqual h=Hosts() h.read(self.hostsfile) eq(h.keys(), ['localhost.yemen', 'broadcasthost', 'localhost', '127.0.0.1', '255.255.255.255']) eq(h['broadcasthost'],'255.255.255.255') eq(h['127.0.0.1'],'localhost localhost.yemen') eq(h['localhost.yemen'],'127.0.0.1') eq(h['localhost'],'127.0.0.1')
def doProbe(self, args): state = {} state['status'] = "ok" attr = Hosts().getHost(Hosts().getLocalHost()) for k in attr.keys(): state[k] = attr[k] for cb in self.probeCallbacks: info = cb() for k in info.keys(): state[k] = info[k] return json.dumps(state)
def sendPhrase(self,ip,text): lang = random.choice(Specs().s['langList']) phr = Hosts().getAttr(ip,'phrase') args = {} args["phrase"] = text if phr['voice']: args["phraseData"] = makeSpeakData("%s %s"%(text[0],text[1]),lang) else: args["phraseData"] = "" cmd = { 'cmd' : "Phrase", 'args' : args} Debug().p("%s: ip %s sending %s"%(self.name,ip,args['phrase'])) Hosts().sendToHost(ip,cmd)
def sendCargs(p,cargs): if len(p.name) + len(p.ip) + len(p.sub) == 0: Hosts().sendToHosts(cargs) return 0 if len(p.name) != 0: Hosts().sendByName(p.name,cargs) if len(p.sub) != 0: Hosts().sendWithSubnet(p.sub,cargs) if len(p.ip) != 0: for h in parms.ip: print "h:",h Hosts().sendToHost(h,cargs) return 0
def find_status_by_host(self, hostname=None, domainname=None): if (hostname is not None and hostname != "" and domainname is not None and domainname != ""): h = Hosts(self._rpcurl) host_rec = h.find_by_hostname(hostname, domainname) if host_rec is not None: installstate = self._proxy.dc2.deployment.installstate.get( {"host_id": host_rec["_id"]}) if installstate is not None: return installstate return None
def doHaltMusic(cmd): hmcmd = { 'cmd' : 'HaltMusic', 'args' : [""] } hscmd = { 'cmd' : 'HaltSound', 'args' : [""] } hosts = Hosts().getHostIps() for ip in hosts: music = Hosts().getAttr(ip,'music') Debug().p("Test Halt for ip %s music: %s"%(ip,music)) if music['enabled'] and music['player']: Hosts().sendToHost(ip,hmcmd) Debug().p("Halt Player for ip %s music: %s"%(ip,music)) if music['enabled']: Debug().p("Halt Music for ip %s music: %s"%(ip,music)) Hosts().sendToHost(ip,hscmd) return 0
def doTest(args): print "Hit return to stop test" hosts = Hosts().getHosts() loop = True while loop: for h in hosts: vs = h['ip'].split(".") cmd = [] cmd.append("Phrase") cmd.append("%s"%(vs[3])) cmd.append("-r") cmd.append("0") cmd.append("-s") cmd.append("%s"%(vs[3])) stop = "Phrase -s %s"%(vs[3]) print ("host %s sub %s cmd %s"%(h['ip'],vs[3],cmd)) doPhrase(cmd) i,o,e = select.select([sys.stdin],[],[],5) cmd = [] cmd.append("Phrase") cmd.append("-s") cmd.append("%s"%(vs[3])) doPhrase(cmd) if len(i): loop = False input = sys.stdin.readline() break
def test_scenario2(self): '''Scenario 2.''' d=dict([ ('localhost','1.0.0.1'), ('1.0.0.2','mc02') ]) Hosts(d).write(self.emptyfile) correct = '1.0.0.1\t\t\tlocalhost\n1.0.0.2\t\t\tmc02\n' self.assertEqual(file(self.emptyfile).read(), correct)
def cmdHandler(self, cmd): Debug().p("%s handling cmd: %s" % (self.name, cmd['cmd'])) if cmd['cmd'] not in self.commandTable.keys(): return Hosts.jsonStatus( "%s: %s not implemented" % (self.name, cmd['cmd']), False) status = self.commandTable[cmd['cmd']](cmd['args']) return status
def setImageDir(self, args): rval = "ok" id = args[0] path = self.getCacheDir(id) self.queue.put(path) print("SetImageDir to %s: %s" % (path, rval)) return Hosts.jsonStatus(rval)
def test_update(self): '''Update''' h=Hosts(self.hostsfile, mc02='1.0.0.2', localhost='10.0.0.2') h.write() correct = """## # Host Database # # localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 10.0.0.2 localhost localhost.yemen # very pertinent comment 255.255.255.255 broadcasthost ::1 localhost fe80::1%lo0 localhost 1.0.0.2 mc02 """ self.assertEqual(file(self.hostsfile).read(), correct)
def __init__(self): super(MidiHandler,self).__init__() spec = Specs().s self.midiSpec = Hosts().getLocalAttr('midi') mido.set_backend(self.midiSpec['backend']) self.name = "MidiHandler" self.running = True self.queue = Queue.Queue() self.portHandlers = []
def __init__(self, modules, refresh_rate=REFRESH_RATE, debug=False): self.hosts = Hosts() self.refresh_rate = refresh_rate self.debug = debug self.modules = [(m, Client('{}.local:{}'.format(m.hostname, OPC_PORT))) for m in modules] self.active = True self.time_taken = 0.0 self.i = 0 self.update()
def test_purge_empty_records(self): with open(self.hosts_file, 'a') as f: f.write('1.2.3.4') self.assertHasHostLine('1.2.3.4') hosts = Hosts(self.hosts_file) hosts.set_one("test", "1.2.3.4") hosts.set_one("", "1.2.3.4") hosts.write(self.hosts_file) self.assertDoesNotHaveHostLine('1.2.3.4')
def rmCacheDir(args): rval = "ok" id = args[0] path = ImageHandler.getCacheDir(id) try: shutil.rmtree(path) except OSError as e: rval = "Error: %s - %s." % (e.filename, e.strerror) print("rmCacheDir: path %s %s" % (path, rval)) return Hosts.jsonStatus(rval)
def clearCache(args): path = ImageHandler.getImageCache() for f in os.listdir(path): try: r = path + "/%s" % f print("rm: %s" % r) shutil.rmtree(path) except OSError as e: rval = "Error: %s - %s." % (e.filename, e.strerror) return Hosts.jsonStatus("ok")
def __init__(self): super(iAltar, self).__init__() self.name = "iAltarPlayer" print("starting: %s" % self.name) self.searchType = Specs().s['defaultSearchType'] print("%s: default search type: %s" % (self.name, self.searchType)) Watchdog().add(self) if Hosts().getLocalAttr("hasServer"): Server().register({'Search': self.setSearchType}) self.queue = Queue.Queue()
def __init__(self,output): super(RecogAnalyzer,self).__init__() self.name = "RecogAnalyzer" self.queue = Queue() recog = Hosts().getLocalAttr("recog") self.chooseLen=recog['chooseLen'] self.chooseSize=recog['chooseSize'] self.output = output self.running = True self.choices = [] self.lastTime = time.time()
def update_status_by_host( self, hostname=None, domainname=None, status=None, progress=None): if (hostname is not None and hostname != "" and domainname is not None and domainname != ""): h = Hosts(self._rpcurl) host_rec = h.find_by_hostname(hostname, domainname) if host_rec is not None: installstate = self._proxy.dc2.deployment.installstate.get( {"host_id": host_rec["_id"]}) if installstate is not None: result = self._update_status( installstate, status, progress) return result return None
def test_append(self): '''Append''' eq=self.assertEqual h=Hosts() h['mc']='10.0.0.1' h.append('10.0.0.1','localhost') eq(h['10.0.0.1'],'mc localhost') h.append('localhost', 'localhost.yemen') eq(h['10.0.0.1'],'mc localhost localhost.yemen') h.append('localhost', 'mc') eq(h['10.0.0.1'],'mc localhost localhost.yemen') self.assertRaises(KeyError, h.append, 'tata', '192.168.0.1')
def runTest( self ): root = Hosts( 'hosts0' ) root.process( Event( 'AddUser', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print root.process( Event( 'AddDialog', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print root.process( Event( '1xx', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print root.process( Event( '200', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print root.process( Event( 'BYE', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print root.process( Event( 'Dump', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print root.process( Event( 'RemoveDialog', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print root.process( Event( 'RemoveUser', { Host.KEY:'12.1.1.1', User.KEY:'riley', Dialog.KEY:'c2' } ) ) print assert 1
def setUp(self): fh, self.hosts_file = tempfile.mkstemp() self.hosts = Hosts(self.hosts_file)
__author__ = 'M' from hosts import Hosts hosts_file_1 = """ # comment # comment with space before # line after blank line 100.1.1.1 hundred-one-one-one 100.1.1.2 hundred-one-one-two 100.1.1.1 hundred-one-one-one 100.1.1.10 hundred-one-one-ten """ hosts_file_path = 'tmp_hosts' with open(hosts_file_path, 'w') as fpw: fpw.write(hosts_file_1) obj = Hosts(hosts_path=hosts_file_path) print(obj._lines) obj.save()
class HostManipulationTestCase(unittest.TestCase): def setUp(self): fh, self.hosts_file = tempfile.mkstemp() self.hosts = Hosts(self.hosts_file) def tearDown(self): os.unlink(self.hosts_file) def assertHasHostLine(self, host_line): if not has_host_line(self.hosts_file, host_line): raise AssertionError("Line not present: {0}".format(host_line)) def assertDoesNotHaveHostLine(self, host_line): if has_host_line(self.hosts_file, host_line): raise AssertionError("Line is present: {0}".format(host_line)) def test_set_one(self): self.hosts.set_one("test", "1.2.3.4") self.hosts.write(self.hosts_file) self.assertHasHostLine("1.2.3.4 test") def test_set_all(self): self.hosts.set_all(["test", "alias"], "1.2.3.4") self.hosts.write(self.hosts_file) self.assertHasHostLine("1.2.3.4 test") self.assertHasHostLine("1.2.3.4 alias") def test_remove_one(self): self.hosts.set_one("test", "1.2.3.4") self.hosts.write(self.hosts_file) self.hosts = Hosts(self.hosts_file) self.hosts.remove_one("test") self.hosts.write(self.hosts_file) self.assertDoesNotHaveHostLine("1.2.3.4 test") def test_remove_no_raise(self): self.assertRaises(KeyError, self.hosts.remove_one, "test") self.hosts.remove_one("test", False) def test_purge_empty_records(self): with open(self.hosts_file, 'a') as f: f.write('1.2.3.4') self.assertHasHostLine('1.2.3.4') hosts = Hosts(self.hosts_file) hosts.set_one("test", "1.2.3.4") hosts.set_one("", "1.2.3.4") hosts.write(self.hosts_file) self.assertDoesNotHaveHostLine('1.2.3.4')