def main(): type_ = sys.argv[1] quadruples, constants = None, None if type_ == "examples": quadruples, constants = parse(test) else: # Convert diagram to vip code. converted_diagram = convert_diagram(type_=type_) # Generate Object code. quadruples, constants = parse(converted_diagram) if len(sys.argv) > 2: if sys.argv[2] == "1": # Print png diagram and vip converted code. print_diagram(type_) if len(sys.argv) == 4: if sys.argv[3] == "1": # Print quadruples and address table content. print("Quadruples:") for i, q in enumerate(quadruples): print(i, q) print("Constants:") for key, value in constants.items(): print(key, value) print("Virtual Machine output: ") vm = VirtualMachine(quadruples, constants) vm.run()
def p_program(p): '''program : pre_variables functions main | functions main | pre_variables main | main''' generator.export() # debug(generator.printeame()) # debug(functions_directory.printeame()) vm = VirtualMachine(functions_directory) vm.run()
def main(): sys.tracebacklimit = 0 filepath = str(sys.argv[1]) input_stream = FileStream(filepath) lexer = LilaLexer(input_stream) lexer._listeners = [CustomErrorListener()] stream = CommonTokenStream(lexer) parser = LilaParser(stream) parser._listeners = [CustomErrorListener()] obj = parser.programa() vm = VirtualMachine(obj) vm.quadruples_handler()
def main(argv): fileName = argv[1] preprocess(fileName) input = FileStream(fileName) lexer = Objective_JSLexer(input) lexer.removeErrorListeners() lexer._listeners = [Objective_JS_ErrorListener(fileName)] stream = CommonTokenStream(lexer) parser = Objective_JSParser(stream) parser._listeners = [Objective_JS_ErrorListener(fileName)] tree = parser.inicio() listener = Objective_JSListener(fileName) walker = ParseTreeWalker() if os.path.exists('Tests/original_copy.Objective_JS'): with open('Tests/original_copy.Objective_JS','r') as input, open(fileName, 'w+') as output: output.write(input.read()) if os.path.exists('Tests/original_copy.Objective_JS'): os.remove('Tests/original_copy.Objective_JS') walker.walk(listener, tree) quadruples = listener.getQuadruples() for quadruple in quadruples: quadruple.setOperator(codes[str(quadruple.getOperator())]) with open ('archivo.obj', 'w') as file: for quadruple in quadruples: file.write(str(quadruple.getId()) + "," + str(quadruple.getOperator()) + "," + str(quadruple.getOperand1()) + "," + str(quadruple.getOperand2()) + "," + str(quadruple.getResult()) + "\n") VirtualMachine() toc = time.clock()
def __init__(self, uri='mongodb://mongo:27017', max_conn=1): # if max_connid null or is not 1-200 exception if not max_conn or not isinstance(max_conn, int) or max_conn > 200 or max_conn < 1: raise MongoPoolInitException(errorMsg='max_conn not is {}'.format(max_conn)) Resource.__init__(self) self.__max_conn = max_conn self.__uri = uri self.idle = max_conn self.busy = 0 config = Config(DB_CFG).config dbname = 'vmmgr' dbinfo = { "name": config.get(dbname, 'name'), "user": config.get(dbname, 'user'), "pwd": config.get(dbname, 'pwd') } self.name = dbinfo['name'] self.user = dbinfo['user'] self.pwd = dbinfo['pwd'] self.pool = ConnectPool(self.idle,self.busy) self.__prepare_conn() self.version = config.get('global', 'version') self.putChild("", self) self.putChild("virtualmachine", VirtualMachine(self.pool)) self.putChild("host", Host(self.pool)) self.putChild("adaccount", AdAccount(self.pool))
def addVirtualMachine(self, configurations): newVM = VirtualMachine(configurations) if (newVM in HardwareManager.vmSet): return False else: HardwareManager.vmSet.add(newVM) return True
def get_list_of_all_vms(Hypervisors): vmList = Parallel(LOG) vmList.hosts = [hv.hostname for hv in Hypervisors] vm_tables = (vmList.start("nova hypervisor-servers")) all_vms = [] index = 0 for vm_table in vm_tables: vms = [] lines = vm_table['stdout'].split('\n') # Logic to return if no VMs on the hypervisor if len(lines) > 5: for line in lines[3:len(lines) - 2]: uuid = line.split(" ")[1] vm = VirtualMachine(uuid) # Fetch all the information about the VM from nova vm.preprocess() vms.append(vm) Hypervisors[index].vms = vms all_vms.extend(vms) index = index + 1 return all_vms
def main(argv): input_stream = FileStream(argv[1]) lexer = CovidLexer(input_stream) stream = CommonTokenStream(lexer) parser = CovidParser(stream) tree = parser.start() if parser.getNumberOfSyntaxErrors() != 0: print("Compilation unsuccessful: Syntax Error(s)") sys.exit() # Create DirFunc using tree walkers dir_func = DirFunc() walker = ParseTreeWalker() walker.walk(dir_func, tree) # Generate list of quads quad_list = QuadrupleList(dir_func) walker = ParseTreeWalker() walker.walk(quad_list, tree) # Instantiate virtual machine virtual_machine = VirtualMachine(dir_func.func_table, quad_list.quad_list, quad_list.cte_address_dir, quad_list.pointer_mem, dir_func.global_address_dir) # Debug flags if len(argv) >= 3: if '-q' in argv: # prints quadruples print(quad_list) if '-d' in argv: # prints dir func print(dir_func) # If no errors and successful compilation, run VM if parser.getNumberOfSyntaxErrors() == 0: print("Successful compilation!") virtual_machine.run()
def load_config(self, filename): with open(filename) as f: config = json.load(f) self.snapshot_time = config[ 'snapshot_time'] #устанавливаем время для снапшотов = времени в конфиге for node in config['nodes']: try: with paramiko.SSHClient() as client: client.set_missing_host_key_policy( paramiko.AutoAddPolicy()) client.connect( node['hostname'], username=node['username'], password=node['password'], timeout=30 ) #здесь есть таймаут на случай если мы не можем подключится test_result = self._test_node( client ) #подключимся к каждой ноде и проверим что на ней установлен proxmox ve и zfs if test_result != 0: print('Node', node['hostname'], 'testing unsuccessful' ) #не установлены утилиты proxmox/zfs else: print('Added new node:', node['hostname']) for vm in node[ 'vms']: #сохраним объекты VM, которые будем снапшотить в массив if not 'type' in vm: vm['type'] = 'status' #по умолчанию смотрим что запущена VM if not 'attribute' in vm: vm['attribute'] = None vm = VirtualMachine(node, vm['id'], vm['type'], vm['attribute']) if vm.is_available: #на подключенной ноде есть vm с этим id self.vms.append(vm) print(vm.name, '(', vm.vmid, ') loaded') else: print('ERROR: Failed to load VM with id', vm['id']) except: traceback.print_exc() print('Node', node['hostname'], 'connection unsuccessful') #ошибка соединения/ssh
def run(): if (compile()): clean_canvas() virtual = VirtualMachine(drawCompiler.quad, drawCompiler.memory_manager, drawCompiler.dir_func, canvas)
import virtualbox from time import sleep from VirtualMachine import VirtualMachine vmname = "vmTest" vrdp = {'ip': "172.19.156.75", 'port': 8000} networkAdapter = "testAdapter" host = "172.19.156.75" config = {"vmname": vmname, "vrdp": vrdp, "networkAdapter": networkAdapter, "host":host} vm = VirtualMachine(config) #sleep(5) #vm.startVM() sleep(5) #vm.pauseVM() #sleep(5) newClones = vm.clone(3)
def main(argv): a = VirtualMachine() a.run(argv[1])
import Library # Must prefix function calls with "Library." from VirtualMachine import VirtualMachine #Instantiate the VirtualMachine myVM = VirtualMachine() #Load the VM with the code from the FXP sourcefile = "helloworld.fxp" progfile = open(sourcefile, "rb") ## rb = Readonly Binary mode progfile.seek(0x4e) #from beginning of file (0) code_area_size = Library.read_unsigned_short(progfile) myVM.code = progfile.read(code_area_size) #Close the FXP progfile.close() myVM.interpret()
for i in range(1, number_nodes): public_ip_object = PublicIP(network_client, Location, Group_Name, node_ip=node_ip + str(i)) nic_object = CreateNIC(network_client, Location, Group_Name, node_ip=node_ip + str(i), node_nic=node_nic + str(i)) if i == 1: vm_object = VirtualMachine(network_client, compute_client, Location, Group_Name, user_name, password, node_nic=node_nic + str(i), vm_name="wrfmaster") else: vm_object = VirtualMachine(network_client, compute_client, Location, Group_Name, user_name, password, node_nic=node_nic + str(i), vm_name=vm_name + str(i)) public_ip_object.create_public_ip_address() nic_object.create_nic() if i == 1:
def machines(self): """Return array of machine objects registered within this VirtualBox instance.""" from VirtualMachine import VirtualMachine return [VirtualMachine(vm) for vm in self._getArray('machines')]
from VirtualMachine import VirtualMachine import time import random #Create a VM with port number and the frequency of ticks #TODO: change 0.1 to random time ticks VM3 =VirtualMachine(2003, random.randint(1, 6), 'VM3') #connect to the other 2 VMs time.sleep(5) # wait until other VMs have started VM3.connect_to(2001) VM3.wait_for_connection(2002) time.sleep(2) VM3.connect_to(2002) VM3.wait_for_connection(2001) VM3.runVM(60)
parser = c_parser.parser drawCompiler = c_parser.drawCompiler #a = input("direccion: ") a = "mini_prueba.draws" if ( os.path.exists (a)): f = open(a) data = f.read() f.close() parser.parse(data) for key, value in drawCompiler.dir_func.items() : print(str(key) + " : " + str(value)) print("Cuadruplos") i = 0 for quad in drawCompiler.quad : print(str(i) + " " + str(quad)) i += 1 #print(drawCompiler.pilaO) #print(drawCompiler.pType) #print(drawCompiler.pOper) #print(drawCompiler.memoria) virtual = VirtualMachine(drawCompiler.quad, drawCompiler.memory_manager) print(virtual.memory.mem_local.var_int) print(virtual.memory.mem_local.var_float) print(virtual.memory.mem_local.var_boolean) else: print("El archivo no existe")
def main(argv): global stackOperands global stackOperators global stackJumps global queueQuads global executionSource # to indicate if "Section" block is being called from a condition or loop global executionSourceReturn # to indicate if the execution source is function return global qCount # quadruple count global pCount # parameter count (for functions) # Memory address global functionDirectory global constantTable global varTable global constIntAddr global constBoolAddr global varIntAddr global varBoolAddr global varCharAddr global tempVarIntAddr global tempVarBoolAddr global tempVarCharAddr global parameterIntAddr global parameterBoolAddr global parameterCharAddr qCount = 0 pCount = 0 stackOperands = [] stackOperators = [] stackJumps = [] queueQuads = [] executionSource = "" executionSourceReturn = False # Memory address constIntAddr = 0 constBoolAddr = 0 varIntAddr = 0 varBoolAddr = 0 varCharAddr = 0 tempVarIntAddr = 0 tempVarBoolAddr = 0 tempVarCharAddr = 0 parameterIntAddr = 0 parameterBoolAddr = 0 parameterCharAddr = 0 functionDirectory = FunctionDirectory() constantTable = ConstantTable({}) varTable = VariableTable({}, [ "int", "void", "bool", "char", "if", "else", "while", "print", "read", "return", "function", "id" ]) lexer = CharmsLexer(FileStream( argv[1])) # Read input file as a command-line argument stream = CommonTokenStream(lexer) parser = CharmsParser(stream) printer = CharmsPrintListener() walker = ParseTreeWalker() tree = parser.program() walker.walk(printer, tree) virtualMachine = VirtualMachine(queueQuads, functionDirectory, constantTable, varTable)
import sys from VirtualMachine import VirtualMachine if len(sys.argv) < 2: print("You must specify the name of the program you want to run") exit() vm = VirtualMachine(sys.argv[1]) vm.execute()
from VirtualMachine import VirtualMachine import time import random #Create a VM with port number and the frequency of ticks VM2 =VirtualMachine(2002, random.randint(1, 6), 'VM2') #connect to the other 2 VMs time.sleep(5) # wait until other VMs have started VM2.connect_to(2003) VM2.wait_for_connection(2001) time.sleep(2) VM2.connect_to(2001) VM2.wait_for_connection(2003) VM2.runVM(60)
def exec_code_object(code, env): vm = VirtualMachine() vm.run_code(code, f_globals=env)
def getAllVMsOnHost(hostname, username, password): osname = WMIHelper.getMachineProperty(hostname, username, password, 'OSName') virtualnamespace = WMIHelper.getVirtualizationNamespace(osname) # this query only return VMs in running # wql = "SELECT Name, Elementname FROM Msvm_ComputerSystem where EnabledState=2 and Caption='Virtual Machine'" # this query return all VMs including turned off VMs wql = "SELECT Name, Elementname FROM Msvm_ComputerSystem where Caption='Virtual Machine'" vms = [] try: from VirtualMachine import VirtualMachine dt = WMIHelper.executeWMIQuery(hostname, username, password, virtualnamespace, wql) for idt in dt: vm = VirtualMachine() vm.vmid = idt.Name print(vm.vmid) vm.machineName = idt.ElementName print(vm.machineName) vm.hostName = hostname print(vm.hostName) vms.append(vm) except Exception as e: LogHelper.append(' '.join(['getAllVMsOnHost error:', str(e)])) print(len(vms)) # initialize VM properties try: wql = "SELECT SystemName, GuestIntrinsicExchangeItems FROM Msvm_KvpExchangeComponent" dt = WMIHelper.executeWMIQuery(hostname, username, password, virtualnamespace, wql) for idt in dt: for index, vm in enumerate(vms): if vm.vmid != idt.SystemName: continue # print(vm.vmid) # print(idt.SystemName) property_dict = {} propertyxml = idt.GuestIntrinsicExchangeItems #print(idt) for eachpro in propertyxml: eachprodict = XMLHelper.parsexmltodict(eachpro) property_dict.update(eachprodict) try: print("trying get IP address...") ips = property_dict.get('RDPAddressIPv4') iparray = ips.split(';') for ip in iparray: if IPHelper.available(ip): vms[index].ip = ip break except Exception as e: LogHelper.append(' '.join( [r'getAllVMsOnHost get ip error:', str(e)])) print(str(e)) try: print("trying get OS Name...") vms[index].osName = property_dict.get('OSName') vms[index].osVersion = property_dict.get('OSVersion') except Exception as e: print("get os name error") LogHelper.append(' '.join( [r'getAllVMsOnHost get OS Name error:', str(e)])) try: print("trying get domain name...") vms[index].fullyQualifiedDomainName = property_dict.get( 'FullyQualifiedDomainName') vms[index].domainName = vms[ index].fullyQualifiedDomainName.split('.')[1] except Exception as e: print("get OS domain name error") LogHelper.append(' '.join([ r'getAllVMsOnHost get domain name error:', str(e) ])) try: print("trying get OSVersion...") vms[index].osVersion = property_dict.get('OSVersion') except Exception as e: print("get os Version error") LogHelper.append(' '.join( [r'getAllVMsOnHost get osversion error:', str(e)])) except Exception as e: LogHelper.append(' '.join( [r'getAllVMsOnHost Initialize VM property error:', str(e)])) for vm in vms: print(vm.machineName) print(vm.vmid) print(vm.ip) print(vm.osName) print(vm.osVersion) print(vm.domainName) return vms
# Generated from VisionScript.g4 by ANTLR 4.7.2 from antlr4 import * from io import StringIO from typing.io import TextIO import sys from Compiler import Compiler from VirtualMachine import VirtualMachine compiler = Compiler() vm = VirtualMachine() def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\65") buf.write("\u0199\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7") buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r") buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23") buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30") buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36") buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%") buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.") buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64") buf.write("\t\64\4\65\t\65\4\66\t\66\4\67\t\67\3\2\3\2\3\3\3\3\3") buf.write("\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7\3\b\3\b\3\t\3\t\3\n\3\n") buf.write("\3\13\3\13\3\f\3\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r") buf.write("\3\16\3\16\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\17") buf.write("\3\17\3\17\3\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\22") buf.write("\3\22\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\23\3\23") buf.write("\3\24\3\24\3\24\3\24\3\24\3\25\3\25\3\25\3\25\3\25\3\25") buf.write("\3\26\3\26\3\26\3\26\3\26\3\27\3\27\3\27\3\27\3\30\3\30")
import time from VirtualMachine import VirtualMachine vm = VirtualMachine() while True: vm.execute_cycle() time.sleep(0.5)