def killForm(): k = maxFailTime while not Port.isExist(prot) and k > 0: time.sleep(1) k -= 1 if Port.isExist(prot): print("kill httpd.exe") Port.simplekillByName(prot, method)
def __init__(self, inputs, outputs, handlerFunc, name='UnnamedFunction'): self.inputs = [Port(self, True, 0, objType) for objType in inputs] self.outputs = [Port(self, False, 0, objType) for objType in outputs] self.handler = handlerFunc self.inputGroups = [[]] * len(inputs) self.name = name self.__temp = None for i in range(len(self.inputs)): self.inputs[i].index = i for i in range(len(self.outputs)): self.outputs[i].index = i
def evaluateConnection(self): for port in self.portsIn: if port.dirty: if port.isConnected(): port.edges[0].node.evaluate() port.value = port.edges[0].value port.dirty = False
def setConfigParamPorts(self, ports): print('setConfigParamsPorts --->') print(ports) for port_core in ports: if self.needConfigPorts(port_core): new_port = Port.ViewPortConfig(self) new_port.setPortCore(port_core) port_core.setView(new_port) self.cfgVars.append(new_port) # Put config ports just above input ports """ for port in self.cfgVars: y = self.height() - port.height() port.move(30,y-10) if self.isOpened: port.show() else: port.hide() """ if self.isOpened: num_var = len(self.cfgVars) width = self.width() interval = width / num_var x = interval / 2 for port in self.cfgVars: y = self.height() - port.height() port.move(x, y - 30) x += interval port.show()
def isConnected(self): """ Checks all ports to see if any are connected, if a connection is found, then returns true """ for port in self.portsIn + self.portsOut: if port.isConnected(): return True return False
def all_ports(self): ports = [] for port_node in self.host_node.getElementsByTagName('port'): p = Port.Port(port_node) ports.append(p) return ports
def run(self): while self._running and (not Port.is_port_used('127.0.0.1', self.local_port)): print("SSH tunnel has not been set up, please wait.") time.sleep(1) if self._running: print("SSH tunnel has been set up successfully") else: print("SSH tunnel has been set up unsuccessfully")
def setInputPorts(self, ports): for port_core in ports: if self.needInputPortView(port_core): new_port = Port.ViewPortIn(self) new_port.setPortCore(port_core) port_core.setView(new_port) self.inPorts.append(new_port) self.inputLayout.addWidget(new_port) self.inputLayout.addStretch()
def __init__(self, name, inports=[], outports=[], inoutports=[]): """Overloaded constructor, takes the port names from the input lists. name: name of the entity inports: list of names for the in ports outports: list of names for the out ports inoutports: list of names for the inout ports """ self.name = name self.IN = [] self.OUT = [] self.INOUT = [] for p in inports: self.IN.append(Port.Port(p, Port.IN, None)) for p in outports: self.OUT.append(Port.Port(p, Port.OUT, None)) for p in inoutports: self.INOUT.append(Port.Port(p, Port.INOUT, None))
def createNewPort(self, wherex, wherey, screenCoordinates=1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode = self.IDLEMODE return new_semantic_obj = Port(self) res = new_semantic_obj.preCondition(ASGNode.CREATE) if res: return self.constraintViolation(res) new_semantic_obj.preAction(ASGNode.CREATE) ne = len(self.ASGroot.listNodes["Port"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue( new_semantic_obj.keyword_.toString() + str(ne)) if screenCoordinates: new_obj = graph_Port(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_Port(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("Port", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode = self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode = self.IDLEMODE return new_semantic_obj.postAction(ASGNode.CREATE) self.mode = self.IDLEMODE if self.editGGLabel: self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj
def createNewPort(self, wherex, wherey, screenCoordinates = 1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return new_semantic_obj = Port(self) ne = len(self.ASGroot.listNodes["Port"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue(new_semantic_obj.keyword_.toString()+str(ne)) if screenCoordinates: new_obj = graph_Port(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_Port(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("Port", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode=self.IDLEMODE return self.mode=self.IDLEMODE if self.editGGLabel : self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj
def addInputPort(self, name, value=0.0): """ Creates a new input port on the node Args: name(str): The name of the port value(float): The value of the port Returns: Port: The newly created port """ newPort = port.Port(name, self, value) self.portsIn.append(newPort) return newPort
def reset(self, file_path): # vncserver -localhost no :1 # vncserver -kill :1 # vncserver -list print('ResetVNC Clicked!') username = self.ui.lineEdit.text() local_addr = '127.0.0.1' local_port = 12345 while Port.is_port_used(local_addr, local_port): local_port += 1 # reset_ssh_cmd = f"vncserver -kill :1; vncserver -localhost no :1" reset_ssh_cmd = f"vncserver -kill :1; vncserver -localhost no :1" if self.target_platform == 'openstack': if self.instance_selected is None: print("Please select the machine that you want to reset") else: InstanceNameList = ProcessTag.getTagAttributeValue( self.document, 'Machine', 'name') usernameList = ProcessTag.getTagAttributeValue( self.document, 'Machine', 'username') ProviderIPList = ProcessTag.getTagAttributeValueWithCondition( self.document, 'Adapter', 'IP', 'name', 'provider') for index, value in enumerate(InstanceNameList): if value == self.instance_selected: provider_ip = ProviderIPList[index] ssh_user = usernameList[index] ssh_thread = OpenStackTunnelThread( local_port, provider_ip, 22, username) ssh_thread.start() check_port_thread = CheckPortThread(local_port) check_port_thread.start() check_port_thread.join(timeout=5) check_port_thread.terminate() ssh_resetvnc_cmd = f"ssh -p {local_port} {ssh_user}@127.0.0.1 {reset_ssh_cmd}" print(ssh_resetvnc_cmd) subprocess.run(ssh_resetvnc_cmd.split()) # process = subprocess.Popen(ssh_resetvnc_cmd, shell=True, stdout=subprocess.PIPE) # process.wait() # print(f"return code:{process.returncode}") break elif self.target_platform == 'deter': pass
def new_port(self, portAttr): portAttr["module"] = self port = Port.Port(portAttr) self.__ports[port.name] = port return port
def __init__(self, core=None, parent=None, inputPortNum=None, outputPorts=None, instName='', typeName=''): QFrame.__init__(self, parent) self.beingConnected = False self.parent = parent self.popupActions = [ ] # list of dictionary, Key :"title","desc","method" self.inPorts = [] self.outPorts = [] self.cfgVars = [] self.setFrameStyle(QFrame.StyledPanel | QFrame.Plain) self.setLineWidth(2) self.setStyleSheet( "background-color: rgb(230,230,230); border: 1px solid black;") self.setContentsMargins(1, 1, 1, 1) self.instName = instName self.core = core self.isOpened = False self.beginningPort = None self.selectedBox = None self.penStart = QPen(QColor(255, 0, 0)) self.penStart.setWidth(3) self.penEnd = QPen(QColor(0, 0, 0)) self.penEnd.setWidth(1) self.brushEnd = QBrush(QColor(0, 0, 0, 255)) self.layout = QVBoxLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.inputLayout = QHBoxLayout() self.inputLayout.addStretch() for port_core in inputPortNum: new_port = Port.ViewPortIn(self) new_port.setPortCore(port_core) port_core.setView(new_port) self.inPorts.append(new_port) self.inputLayout.addWidget(new_port) self.inputLayout.addStretch() self.outputLayout = QHBoxLayout() self.outputLayout.addStretch() for port_core in outputPorts: new_port = Port.ViewPortOut(self) new_port.setPortCore(port_core) port_core.setView(new_port) self.outPorts.append(new_port) self.outputLayout.addWidget(new_port) self.outputLayout.addStretch() self.layout.addLayout(self.outputLayout) self.layout.addStretch() self.instName = QLabel(instName) self.instName.setStyleSheet("border: 0px") self.instName.setAlignment(Qt.AlignCenter) self.layout.addWidget(self.instName) self.typeName = QLabel('(%s)' % typeName) self.typeName.setStyleSheet("border: 0px") self.typeName.setAlignment(Qt.AlignCenter) self.layout.addWidget(self.typeName) self.layout.addStretch() self.layout.addLayout(self.inputLayout) self.setLayout(self.layout) self.resize(self.sizeHint()) self.show()
def doubleclick(self, item): username = self.ui.lineEdit.text() local_addr = '127.0.0.1' local_port = 12345 while Port.is_port_used(local_addr, local_port): local_port += 1 # self.target_platform = ProcessTag.getRootElementAttributeValue(self.document, 'platform') # deter if self.target_platform == 'deter': # machine doubleclick if item.parent(): print('You double-click the Machine') node_name = item.parent().text(0) machine_name = item.text(0) exp_name = item.text(1) team_name = item.text(2) if (self.connection == 'Console'): # VM VRDE Console remoteDisplayEnabled = ProcessTag.getTagAttributeValue( self.document, 'RemoteDisplay', 'enabled') remoteDisplayPort = ProcessTag.getTagAttributeValueWithCondition( self.document, 'Property', 'value', 'name', 'TCP/Ports') for index, enabled in enumerate(remoteDisplayEnabled): if enabled == 'false': remoteDisplayPort[index] = None machine_name_list = ProcessTag.getTagAttributeValue( self.document, 'Machine', 'name') for index, name in enumerate(machine_name_list): if name == machine_name: rdp_port = remoteDisplayPort[index] break if not rdp_port: print("This Machine's rdesktop port hasn't been set!") else: ''' -f: Go to background -N: Do not execute a remote command. This is useful for just forwarding ports -T: Disable pseudo-tty allocation ''' ssh_thread = DeterTunnelThread(local_port, node_name, exp_name, team_name, rdp_port, username) ssh_thread.start() check_port_thread = CheckPortThread(local_port) check_port_thread.start() check_port_thread.join(timeout=5) check_port_thread.terminate() if self.platform == 'MacOS': rdesktop_cmd = "open rdp://127.0.0.1:" + str( local_port) elif self.platform == 'Linux': rdesktop_cmd = "rdesktop -a 16 127.0.0.1:" + str( local_port) elif self.platform == 'Win': rdesktop_cmd = "rdesktop -a 16 127.0.0.1:" + str( local_port) subprocess.run(rdesktop_cmd.split()) if (self.connection == 'SSH'): # VM SSH hostport = None guestport = None # NATNode = ProcessTag.getTagAttributeValue(self.document, 'NAT', 'enabled') ForwardingNum = ProcessTag.getTextNodeValue( self.document, 'ForwardingNum') # for index, value in enumerate(NATNode): # if value == 'false': # ForwardingNum[index] = 0 # ForwardingName = ProcessTag.getTagAttributeValue(self.document, 'Forwarding', 'name') Forwardinghostport = ProcessTag.getTagAttributeValue( self.document, 'Forwarding', 'hostport') Forwardingguestport = ProcessTag.getTagAttributeValue( self.document, 'Forwarding', 'guestport') print(ForwardingNum) # print(ForwardingName) print(Forwardinghostport) print(Forwardingguestport) AllForwardings = [] for index in range(len(Forwardinghostport)): AllForwardings.append((Forwardinghostport[index], Forwardingguestport[index])) print(AllForwardings) Forwarding = [] start = 0 end = 0 for num in ForwardingNum: if num != 0: end = end + int(num) Forwarding.append(AllForwardings[start:end]) start = end else: Forwarding.append([]) print(Forwarding) machine_name_list = ProcessTag.getTagAttributeValue( self.document, 'Machine', 'name') usernameList = ProcessTag.getTagAttributeValue( self.document, 'Machine', 'username') passwordList = ProcessTag.getTagAttributeValue( self.document, 'Machine', 'password') for index, name in enumerate(machine_name_list): if name == machine_name: for forwarding_entry in Forwarding[index]: if forwarding_entry[1] == '22': hostport = forwarding_entry[0] guestport = forwarding_entry[1] break break if not hostport or not guestport: print("This VM's SSH port hasn't been port forwarded!") else: ssh_thread = DeterTunnelThread(local_port, node_name, exp_name, team_name, hostport, username) ssh_thread.start() check_port_thread = CheckPortThread(local_port) check_port_thread.start() check_port_thread.join(timeout=5) check_port_thread.terminate() ssh_user = usernameList[index] ssh_password = passwordList[index] ssh_password_bytes = ssh_password.encode('utf-8') ssh_password_base64_bytes = base64.b64encode( ssh_password_bytes) ssh_password_base64 = ssh_password_base64_bytes.decode( 'utf') wssh_port = 8001 while Port.is_port_used(local_addr, wssh_port): wssh_port += 1 wssh_thread = WSSH_Thread(wssh_port) wssh_thread.start() check_port_thread = CheckPortThread(wssh_port) check_port_thread.start() check_port_thread.join(timeout=5) check_port_thread.terminate() print( f"http://*****:*****@localhost" # print(ssh_cmd) # subprocess.run(ssh_cmd.split()) break else: # project doubleclick print(f"You've double click the project")
self.IN.append(Port.Port(p, Port.IN, None)) for p in outports: self.OUT.append(Port.Port(p, Port.OUT, None)) for p in inoutports: self.INOUT.append(Port.Port(p, Port.INOUT, None)) def __str__(self): s = "<Entity: %s, %d ports" % (self.name, len(self.IN)) i = 0 for p in self.IN: i += 1 s += "\n%d. %s" % (i, p) for p in self.OUT: i += 1 s += "\n%d. %s" % (i, p) for p in self.INOUT: i += 1 s += "\n%d. %s" % (i, p) s += ">" return s if __name__ == "__main__": a = Port.Port("a", Port.IN, None) b = Port.Port("b", Port.IN, None) c = Port.Port("c", Port.OUT, None) d = Entity("d", ["1", "2"], ["3"], ["4"]) max = Entity("max", [a, b, c]) print max, d
import Port import subprocess import time print("start memcached ...") prot = 11211 cmd = "D:/memcached.exe" if Port.isExist(prot): Port.kill(prot); time.sleep(3) proc = subprocess.Popen(cmd, shell=True) print("memcached ok !") print("start resin ...") prot = 8082 # cmd = "D:/pdlib-resin-3.0.14/httpd -Xmn256m -Xms512m -Xmx1024m -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001 -conf conf/resin-product.conf" cmd = "D:/pdlib-resin-3.0.14/httpd -Xmn256m -Xms512m -Xmx1024m -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8001 -conf conf/resin-product-svn.conf" method = "httpd" maxFailTime = 60 if Port.isExist(prot): Port.kill(prot); time.sleep(3) proc = subprocess.Popen(cmd, shell=True) print("resin ok !")
def main(): # These variables can be changed to fit simulation needs STATION_TOTAL_POWER = 40 # kW PORT_MAX_POWER = 30 #kW STATION_PORTS = 4 x = 0 time = np.arange(6., 20., 0.25) # time sampling array total_power_line = [STATION_TOTAL_POWER] * len(time) pause_time = 0 if ADD_CAR: pause_time = float(input("Enter time to pause simulation (6 - 20): ")) print("Pause time is", pause_time ) # ------------ initialize the day of vehicles for simulation ------------ # # init vehicle arrays (packCapacity, arrival, departure, requestedCharge, maxChargeRate, initialSOC, time) vehicles_port0 = [Vehicle(40., 7.5, 11.5, 32., 16., 20., time), # 7:30 am - 11:30 am Vehicle(50., 13.25, 17., 40., 16., 15., time), # 1:15 pm - 5 pm Vehicle(23., 17.5, 18., 15., 50., 14., time)] # 5:30 pm - 6 pm vehicles_port1 = [Vehicle(35., 7.75, 14.5, 30., 16., 10., time), # 7:45 am - 2:30 pm Vehicle(40., 14.75, 17., 25., 16., 20., time), # 2:45 pm - 5 pm Vehicle(50., 17.25, 18., 40., 50., 30., time)] # 5:15 pm - 6 pm vehicles_port2 = [Vehicle(40., 7.5, 11.5, 32., 16., 30., time), # 7:30 am - 11:30 am Vehicle(50., 11.5, 17., 40., 16., 2., time), # 11:30 am - 5 pm Vehicle(50., 17.5, 18., 40., 50., 37., time)] # 5:30 pm - 6 pm vehicles_port3 = [Vehicle(50., 7.75, 13.5, 50., 20., 34., time), # 7:45 am - 1:30 pm Vehicle(40., 13.5, 17., 30., 19., 20., time), # 1:30 pm - 5 pm #Vehicle(30., 17.5 , 18., 15., 30., 10., time)] # 5:30 pm - 6 pm None] # Where vehicle from app interaction goes # init ports station_ports = [Port(vehicles_port0, PORT_MAX_POWER, time), Port(vehicles_port1, PORT_MAX_POWER, time), Port(vehicles_port2, PORT_MAX_POWER, time), Port(vehicles_port3, PORT_MAX_POWER, time)] # init station station = Station(station_ports, STATION_TOTAL_POWER, time) # ----------------------------------------------------------------------- # # run the algorithm stationAlg(station, time, pause_time) # print out if vehicles were satisfied y=0 for port in station.ports: print("At Port %d:" % y) x=0 y+=1 for vehicle in port.vehicles: if (vehicle != None): if (vehicle.finalCharge >= vehicle.requestedCharge): print(" Vehicle ", x, " - SATISFIED: %.2f" % vehicle.finalCharge, "/%.2f kWh" % vehicle.requestedCharge, sep="", end="\n") else: print(" Vehicle ", x, " - UNSATISFIED: %.2f" % vehicle.finalCharge, "/%.2f kWh" % vehicle.requestedCharge, sep="", end="\n") x+=1 # ---------------------- plot all simulation data ----------------------- # plt.figure(1) # subplot for port 0 delivered power plt.subplot(2, 2, 1) plt.plot(time, station.ports[0].delivered_power, 'bo-') plt.xlabel('Time of Day (6 am - 8 pm)') plt.ylabel('Plug Power (kW)') plt.title('Port 0 Delivered Power') plt.grid(True) # subplot for port 1 delivered power plt.subplot(2, 2, 2) plt.plot(time, station.ports[1].delivered_power, 'bo-') plt.xlabel('Time of Day (6 am - 8 pm)') plt.ylabel('Plug Power (kW)') plt.title('Port 1 Delivered Power') plt.grid(True) # subplot for port 2 delivered power plt.subplot(2, 2, 3) plt.plot(time, station.ports[2].delivered_power, 'bo-') plt.xlabel('Time of Day (6 am - 8 pm)') plt.ylabel('Plug Power (kW)') plt.title('Port 2 Delivered Power') plt.grid(True) # subplot for port 3 delivered power plt.subplot(2, 2, 4) plt.plot(time, station.ports[3].delivered_power, 'bo-') plt.xlabel('Time of Day (6 am - 8 pm)') plt.ylabel('Plug Power (kW)') plt.title('Port 3 Delivered Power') plt.grid(True) # plot of station total delivered power plt.figure(2) plt.plot(time, station.delivered_power, 'bo-', time, total_power_line, 'r-') plt.ylim(0,station.total_power+10) plt.annotate('Total Station Power Available', xy=(10, station.total_power), xytext=(10.5, station.total_power+5), arrowprops=dict(facecolor='black', width=1, headwidth=5, headlength=5), ) plt.xlabel('Time of Day (6 am - 8 pm)') plt.ylabel('Station Power (kW)') plt.title('Station Delivered Power') plt.grid(True) plt.show()
#coding=GBK import subprocess import sys import Port def isExist(port): proc = subprocess.Popen("netstat -aon|findstr "+str(port), shell=True, stdout=subprocess.PIPE) out = str(proc.stdout.read()) index = out.find(":"+str(port)) if index == -1: return False else: return True if len(sys.argv)>1: if sys.argv[1].isdigit(): status = Port.kill(sys.argv[1]) print(status) else: print("parameters error!") else: print("No parameters!")
def createSocket(self, port): #pOuvre un port socket = Socket(self.IPadress, Port(name=port)) self.sockets[port] = socket self.availableSockets.append(socket)
def addInputPort(self, name, value=0.0): newPort = port.ContainerPort(name, self, value) self.portsIn.append(newPort) return newPort
def addOutputPort(self, name): newPort = port.ContainerPort(name, self) self.portsOut.append(newPort) return newPort
def clean(): k = maxFailTime while not Port.isExist(prot) and k > 0: time.sleep(1) k -= 1 Proc.killByName(method)
def killForm(): k = maxFailTime while not Port.isExist(prot) and k > 0: time.sleep(1) k -= 1 Port.simplekillByName(prot, method)
import time import socket hostName = socket.gethostname() if hostName == 'lym' : prot = 83 cmd = "D:/resin-3.1.9/httpd -conf conf/struts1_core_test.conf" else: prot = 81 cmd = "C:/command/resin-3.1.9/httpd -conf conf/struts1_core_test.conf" method = "httpd" maxFailTime = 6000 def killForm(): k = maxFailTime while not Port.isExist(prot) and k > 0: time.sleep(1) k -= 1 if Port.isExist(prot): print("kill httpd.exe") Port.simplekillByName(prot, method) Port.simplekillByName(prot, method) Port.kill(prot) threading.Thread(target=killForm).start() proc = subprocess.Popen(cmd, shell=True)