def startup(self): """ Linux bridge starup logic. :return: nothing """ try: subprocess.check_call([constants.BRCTL_BIN, "addbr", self.brname]) except subprocess.CalledProcessError: logger.exception("Error adding bridge") try: # turn off spanning tree protocol and forwarding delay subprocess.check_call( [constants.BRCTL_BIN, "stp", self.brname, "off"]) subprocess.check_call( [constants.BRCTL_BIN, "setfd", self.brname, "0"]) subprocess.check_call( [constants.IP_BIN, "link", "set", self.brname, "up"]) # create a new ebtables chain for this bridge ebtablescmds(subprocess.check_call, [ [constants.EBTABLES_BIN, "-N", self.brname, "-P", self.policy], [ constants.EBTABLES_BIN, "-A", "FORWARD", "--logical-in", self.brname, "-j", self.brname ] ]) # turn off multicast snooping so mcast forwarding occurs w/o IGMP joins snoop = "/sys/devices/virtual/net/%s/bridge/multicast_snooping" % self.brname if os.path.exists(snoop): open(snoop, "w").write("0") except subprocess.CalledProcessError: logger.exception("Error setting bridge parameters") self.up = True
def update_control_interface_hosts(self, net_index=0, remove=False): """ Add the IP addresses of control interfaces to the /etc/hosts file. :param int net_index: network index to update :param bool remove: flag to check if it should be removed :return: nothing """ if not self.options.get_config_bool("update_etc_hosts", default=False): return try: control_net = self.get_control_net_object(net_index) except KeyError: logger.exception("error retrieving control net object") return header = "CORE session %s host entries" % self.session_id if remove: logger.info("Removing /etc/hosts file entries.") utils.file_demunge("/etc/hosts", header) return entries = [] for interface in control_net.netifs(): name = interface.node.name for address in interface.addrlist: entries.append("%s %s" % (address.split("/")[0], name)) logger.info("Adding %d /etc/hosts file entries." % len(entries)) utils.file_munge("/etc/hosts", header, "\n".join(entries) + "\n")
def startup(self): """ Start running the script if autostart is enabled. Move node to initial positions when any autostart time is specified. Ignore the script if autostart is an empty string (can still be started via GUI controls). :return: nothing """ if self.autostart == '': logger.info("not auto-starting ns-2 script for %s" % self.wlan.name) return try: t = float(self.autostart) except ValueError: logger.exception( "Invalid auto-start seconds specified '%s' for %s", self.autostart, self.wlan.name) return self.movenodesinitial() logger.info("scheduling ns-2 script for %s autostart at %s" % (self.wlan.name, t)) self.state = self.STATE_RUNNING self.session.event_loop.add_event(t, self.run)
def addNetworks(self): """ Add networks in the session to the scenPlan. """ for net in self.coreSession.objects.itervalues(): if not isinstance(net, coreobj.PyCoreNet): continue if nodeutils.is_node(net, NodeTypes.CONTROL_NET): continue # Do not add switches and hubs that belong to another network if nodeutils.is_node(net, (NodeTypes.SWITCH, NodeTypes.HUB)): if in_other_network(net): continue try: NetworkElement(self, self, net) except: logger.exception("error adding node") if hasattr(net, "name") and net.name: logger.warn('Unsupported net name: %s, class: %s, type: %s', net.name, net.__class__.__name__, net.type) else: logger.warn('Unsupported net class: %s', net.__class__.__name__)
def ebcommit(self, wlan): """ Perform ebtables atomic commit using commands built in the self.cmds list. :return: nothing """ # save kernel ebtables snapshot to a file args = self.ebatomiccmd([ "--atomic-save", ]) utils.check_cmd(args) # modify the table file using queued ebtables commands for c in self.cmds: args = self.ebatomiccmd(c) utils.check_cmd(args) self.cmds = [] # commit the table file to the kernel args = self.ebatomiccmd([ "--atomic-commit", ]) utils.check_cmd(args) try: os.unlink(self.atomic_file) except OSError: logger.exception("error removing atomic file: %s", self.atomic_file)
def getgeo(self, x, y, z): """ Given (x, y, z) Cartesian coordinates, convert them to latitude, longitude, and altitude based on the configured reference point and scale. :param x: x value :param y: y value :param z: z value :return: lat, lon, alt values for provided coordinates :rtype: tuple """ # shift (x,y,z) over to reference point (x,y,z) x -= self.refxyz[0] y = -(y - self.refxyz[1]) if z is None: z = self.refxyz[2] else: z -= self.refxyz[2] # use UTM coordinates since unit is meters zone = self.refutm[0] if zone == "": raise ValueError("reference point not configured") e = self.refutm[1] + self.px2m(x) n = self.refutm[2] + self.px2m(y) alt = self.refutm[3] + self.px2m(z) (e, n, zone) = self.getutmzoneshift(e, n) try: lat, lon = utm.to_latlon(e, n, zone[0], zone[1]) except utm.OutOfRangeError: logger.exception("UTM out of range error for n=%s zone=%s xyz=(%s,%s,%s)", n, zone, x, y, z) lat, lon = self.refgeo[:2] # self.info("getgeo(%s,%s,%s) e=%s n=%s zone=%s lat,lon,alt=" \ # "%.3f,%.3f,%.3f" % (x, y, z, e, n, zone, lat, lon, alt)) return lat, lon, alt
def shutdown(self): """ Linux bridge shutdown logic. :return: nothing """ if not self.up: return ebq.stopupdateloop(self) try: utils.check_cmd([constants.IP_BIN, "link", "set", self.brname, "down"]) utils.check_cmd([constants.BRCTL_BIN, "delbr", self.brname]) ebtablescmds(utils.check_cmd, [ [constants.EBTABLES_BIN, "-D", "FORWARD", "--logical-in", self.brname, "-j", self.brname], [constants.EBTABLES_BIN, "-X", self.brname] ]) except CoreCommandError: logger.exception("error during shutdown") # removes veth pairs used for bridge-to-bridge connections for netif in self.netifs(): netif.shutdown() self._netif.clear() self._linked.clear() del self.session self.up = False
def addNetworks(self): """ Add networks in the session to the scenPlan. """ for net in self.coreSession.objects.itervalues(): if not isinstance(net, coreobj.PyCoreNet): continue if nodeutils.is_node(net, NodeTypes.CONTROL_NET): continue # Do not add switches and hubs that belong to another network if nodeutils.is_node(net, (NodeTypes.SWITCH, NodeTypes.HUB)): if in_other_network(net): continue try: NetworkElement(self, self, net) except: logger.exception("error adding node") if hasattr(net, "name") and net.name: logger.warn( 'Unsupported net name: %s, class: %s, type: %s', net.name, net.__class__.__name__, net.type) else: logger.warn('Unsupported net class: %s', net.__class__.__name__)
def shutdown(self): """ Linux bridge shutdown logic. :return: nothing """ if not self.up: return ebq.stopupdateloop(self) try: utils.check_cmd( [constants.IP_BIN, "link", "set", self.brname, "down"]) utils.check_cmd([constants.BRCTL_BIN, "delbr", self.brname]) ebtablescmds(utils.check_cmd, [[ constants.EBTABLES_BIN, "-D", "FORWARD", "--logical-in", self.brname, "-j", self.brname ], [constants.EBTABLES_BIN, "-X", self.brname]]) except CoreCommandError: logger.exception("error during shutdown") # removes veth pairs used for bridge-to-bridge connections for netif in self.netifs(): netif.shutdown() self._netif.clear() self._linked.clear() del self.session self.up = False
def initeventservice(self, filename=None, shutdown=False): """ Re-initialize the EMANE Event service. The multicast group and/or port may be configured. """ self.deleteeventservice() if shutdown: return # Get the control network to be used for events group, port = self.get_config("eventservicegroup").split(":") self.event_device = self.get_config("eventservicedevice") eventnetidx = self.session.get_control_net_index(self.event_device) if eventnetidx < 0: logger.error("invalid emane event service device provided: %s", self.event_device) return False # make sure the event control network is in place eventnet = self.session.add_remove_control_net(net_index=eventnetidx, remove=False, conf_required=False) if eventnet is not None: # direct EMANE events towards control net bridge self.event_device = eventnet.brname eventchannel = (group, int(port), self.event_device) # disabled otachannel for event service # only needed for e.g. antennaprofile events xmit by models logger.info("using %s for event service traffic", self.event_device) try: self.service = EventService(eventchannel=eventchannel, otachannel=None) except EventServiceException: logger.exception("error instantiating emane EventService") return True
def validatenodeservice(self, node, service, services): """ Run the validation command(s) for a service. :param core.netns.vnode.LxcNode node: node to validate service for :param CoreService service: service to validate :param list services: services for node :return: service validation status :rtype: int """ logger.info("validating service for node (%s): %s (%s)", node.name, service._name, service._startindex) if service._custom: validate_cmds = service._validate else: validate_cmds = service.getvalidate(node, services) status = 0 # has validate commands if validate_cmds: for args in validate_cmds: logger.info("validating service %s using: %s", service._name, args) try: node.check_cmd(args) except CoreCommandError: logger.exception("validate command failed") status = -1 return status
def shutdown(self): if not self.up: logger.info("exiting shutdown, object is not up") return ebtables_queue.stopupdateloop(self) try: utils.check_cmd([constants.IP_BIN, "link", "set", self.bridge_name, "down"]) utils.check_cmd([constants.OVS_BIN, "del-br", self.bridge_name]) ebtables_commands(utils.check_cmd, [ [constants.EBTABLES_BIN, "-D", "FORWARD", "--logical-in", self.bridge_name, "-j", self.bridge_name], [constants.EBTABLES_BIN, "-X", self.bridge_name] ]) except CoreCommandError: logger.exception("error bringing bridge down and removing it") # removes veth pairs used for bridge-to-bridge connections for interface in self.netifs(): interface.shutdown() self._netif.clear() self._linked.clear() del self.session self.up = False
def buildeventservicexml(self): """ Build the libemaneeventservice.xml file if event service options were changed in the global config. """ need_xml = False default_values = self.emane_config.default_values() for name in ["eventservicegroup", "eventservicedevice"]: a = default_values[name] b = self.get_config(name) if a != b: need_xml = True if not need_xml: # reset to using default config self.initeventservice() return try: group, port = self.get_config("eventservicegroup").split(":") except ValueError: logger.exception("invalid eventservicegroup in EMANE config") return dev = self.get_config("eventservicedevice") emanexml.create_event_service_xml(group, port, dev, self.session.session_dir)
def pendingFile(filepath, filesize=0): logger.info('pendingFile........') from os.path import getsize newsize = getsize(filepath) logger.info('{filepath} size is {size}'.format( filepath=filepath, size=newsize)) if newsize == filesize and newsize > 0: try: logger.info('This is is watch file?') f = FileRoute(filepath) transtype, ftpname, dest_path, filename = f.routeInfo() return True except TypeError: logger.info('{filepath} is not watch file'.format( filepath=filepath)) return False except: logger.exception('pendingFile') return False logger.info('File is not Ok,pending {pendingtime} seconds'.format( pendingtime=conf.PENDING_TIME)) time.sleep(conf.PENDING_TIME) return pendingFile(filepath, newsize)
def value_to_params(doc, name, value): """ Helper to convert a parameter to a paramlist. Returns an XML paramlist, or None if the value does not expand to multiple values. :param xml.dom.minidom.Document doc: xml document :param name: name of element for params :param str value: value string to convert to tuple :return: xml document with added params or None, when an invalid value has been provided """ try: values = utils.make_tuple_fromstr(value, str) except SyntaxError: logger.exception("error in value string to param list") return None if not hasattr(values, "__iter__"): return None if len(values) < 2: return None return xmlutils.add_param_list_to_parent(doc, parent=None, name=name, values=values)
def validatenodeservice(self, node, service, services): """ Run the validation command(s) for a service. :param core.netns.nodes.CoreNode node: node to validate service for :param CoreService service: service to validate :param list services: services for node :return: service validation status :rtype: int """ logger.info("validating service for node (%s - %s): %s (%s)", node.objid, node.name, service._name, service._startindex) if service._custom: validate_cmds = service._validate else: validate_cmds = service.getvalidate(node, services) status = 0 # has validate commands if len(validate_cmds) > 0: for cmd in validate_cmds: logger.info("validating service %s using: %s", service._name, cmd) try: status, result = node.cmdresult(shlex.split(cmd)) if status != 0: raise ValueError("non-zero exit status") except: logger.exception("validate command failed: %s", cmd) status = -1 return status
def create_service_files(self, node, service): """ Creates node service files. :param PyCoreNode node: node to reconfigure service for :param CoreService service: service to reconfigure :return: nothing """ logger.info("node(%s) service(%s) creating config files", node.name, service.name) # get values depending on if custom or not config_files = service.configs if not service.custom: config_files = service.get_configs(node) for file_name in config_files: logger.debug("generating service config: %s", file_name) if service.custom: cfg = service.config_data.get(file_name) if cfg is None: cfg = service.generate_config(node, file_name) # cfg may have a file:/// url for copying from a file try: if self.copy_service_file(node, file_name, cfg): continue except IOError: logger.exception("error copying service file: %s", file_name) continue else: cfg = service.generate_config(node, file_name) node.nodefile(file_name, cfg)
def startup_service(self, node, service, wait=False): """ Startup a node service. :param PyCoreNode node: node to reconfigure service for :param CoreService service: service to reconfigure :param bool wait: determines if we should wait to validate startup :return: status of startup :rtype: int """ cmds = service.startup if not service.custom: cmds = service.get_startup(node) status = 0 for cmd in cmds: try: if wait: node.check_cmd(cmd) else: node.cmd(cmd, wait=False) except CoreCommandError: logger.exception("error starting command") status = -1 return status
def writeservers(self): """ Write the server list to a text file in the session directory upon startup: /tmp/pycore.nnnnn/servers :return: nothing """ servers = self.getservers() filename = os.path.join(self.session.session_dir, "servers") master = self.session_id_master if master is None: master = self.session.session_id try: with open(filename, "w") as f: f.write("master=%s\n" % master) for server in servers: if server.name == "localhost": continue lhost, lport = None, None if server.sock: lhost, lport = server.sock.getsockname() f.write("%s %s %s %s %s\n" % (server.name, server.host, server.port, lhost, lport)) except IOError: logger.exception("error writing server list to the file: %s", filename)
def addserver(self, name, host, port): """ Add a new server, and try to connect to it. If we"re already connected to this (host, port), then leave it alone. When host,port is None, do not try to connect. :param str name: name of server :param str host: server address :param int port: server port :return: nothing """ with self.servers_lock: server = self.servers.get(name) if server is not None: if host == server.host and port == server.port and server.sock is not None: # leave this socket connected return logger.info("closing connection with %s @ %s:%s", name, server.host, server.port) server.close() del self.servers[name] logger.info("adding broker server(%s): %s:%s", name, host, port) server = CoreDistributedServer(name, host, port) if host is not None and port is not None: try: server.connect() except IOError: logger.exception("error connecting to server(%s): %s:%s", name, host, port) if server.sock is not None: self.startrecvloop() self.servers[name] = server
def shutdown(self): """ Interface shutdown logic. :return: nothing """ if not self.up: return if self.node: try: self.node.check_cmd([ constants.IP_BIN, "-6", "addr", "flush", "dev", self.name ]) except CoreCommandError: logger.exception("error shutting down interface") if self.localname: try: utils.check_cmd( [constants.IP_BIN, "link", "delete", self.localname]) except CoreCommandError: logger.exception("error deleting link") self.up = False
def startup(self): if self.detectoldbridge(): return OvsNet.startup(self) if self.hostid: addr = self.prefix.addr(self.hostid) else: addr = self.prefix.max_addr() message = "Added control network bridge: %s %s" % (self.bridge_name, self.prefix) addresses = ["%s/%s" % (addr, self.prefix.prefixlen)] if self.assign_address: self.addrconfig(addresses=addresses) message += " address %s" % addr logger.info(message) if self.updown_script: logger.info("interface %s updown script %s startup called" % (self.bridge_name, self.updown_script)) subprocess.check_call([self.updown_script, self.bridge_name, "startup"]) if self.serverintf: try: subprocess.check_call([constants.OVS_BIN, "add-port", self.bridge_name, self.serverintf]) subprocess.check_call([constants.IP_BIN, "link", "set", self.serverintf, "up"]) except subprocess.CalledProcessError: logger.exception("error joining server interface %s to controlnet bridge %s", self.serverintf, self.bridge_name)
def emane_version(): """ Return the locally installed EMANE version identifier and string. """ global VERSION global VERSIONSTR cmd = ("emane", "--version") try: status, result = utils.cmdresult(cmd) except (OSError, subprocess.CalledProcessError): logger.exception("error checking emane version") status = -1 result = "" VERSION = EMANEUNK if status == 0: if result.startswith("0.7.4"): VERSION = EMANE074 elif result.startswith("0.8.1"): VERSION = EMANE081 elif result.startswith("0.9.1"): VERSION = EMANE091 elif result.startswith("0.9.2"): VERSION = EMANE092 elif result.startswith("0.9.3"): VERSION = EMANE093 elif result.startswith("1.0.1"): VERSION = EMANE101 elif result.startswith("1.2.1"): VERSION = EMANE121 VERSIONSTR = result.strip()
def savestate(self): """ Save the addresses and other interface state before using the interface for emulation purposes. TODO: save/restore the PROMISC flag :return: nothing """ self.old_up = False self.old_addrs = [] cmd = [constants.IP_BIN, "addr", "show", "dev", self.localname] try: tmp = subprocess.Popen(cmd, stdout=subprocess.PIPE) except OSError: logger.exception("Failed to run %s command: %s", constants.IP_BIN, cmd) if tmp.wait(): logger.warn("Command failed: %s", cmd) return lines = tmp.stdout.read() tmp.stdout.close() for l in lines.split("\n"): items = l.split() if len(items) < 2: continue if items[1] == "%s:" % self.localname: flags = items[2][1:-1].split(",") if "UP" in flags: self.old_up = True elif items[0] == "inet": self.old_addrs.append((items[1], items[3])) elif items[0] == "inet6": if items[1][:4] == "fe80": continue self.old_addrs.append((items[1], None))
def startup(self): """ Startup functionality for the control network. :return: nothing """ if self.detectoldbridge(): return LxBrNet.startup(self) if self.hostid: addr = self.prefix.addr(self.hostid) else: addr = self.prefix.max_addr() msg = "Added control network bridge: %s %s" % (self.brname, self.prefix) addrlist = ["%s/%s" % (addr, self.prefix.prefixlen)] if self.assign_address: self.addrconfig(addrlist=addrlist) msg += " address %s" % addr logger.info(msg) if self.updown_script is not None: logger.info("interface %s updown script (%s startup) called", self.brname, self.updown_script) subprocess.check_call([self.updown_script, self.brname, "startup"]) if self.serverintf is not None: try: subprocess.check_call([constants.BRCTL_BIN, "addif", self.brname, self.serverintf]) subprocess.check_call([constants.IP_BIN, "link", "set", self.serverintf, "up"]) except subprocess.CalledProcessError: logger.exception("Error joining server interface %s to controlnet bridge %s", self.serverintf, self.brname)
def validate_service(self, node, service): """ Run the validation command(s) for a service. :param core.netns.vnode.LxcNode node: node to validate service for :param CoreService service: service to validate :return: service validation status :rtype: int """ logger.info("validating node(%s) service(%s)", node.name, service.name) cmds = service.validate if not service.custom: cmds = service.get_validate(node) status = 0 for cmd in cmds: logger.debug("validating service(%s) using: %s", service.name, cmd) try: node.check_cmd(cmd) except CoreCommandError: logger.exception( "node(%s) service(%s) validate command failed", node.name, service.name) status = -1 return status
def install(self): """ Install this TAP into its namespace. This is not done from the startup() method but called at a later time when a userspace program (running on the host) has had a chance to open the socket end of the TAP. :return: nothing """ self.waitfordevicelocal() netns = str(self.node.pid) try: subprocess.check_call([ constants.IP_BIN, "link", "set", self.localname, "netns", netns ]) except subprocess.CalledProcessError: msg = "error installing TAP interface %s, command:" % self.localname msg += "ip link set %s netns %s" % (self.localname, netns) logger.exception(msg) return self.node.cmd([ constants.IP_BIN, "link", "set", self.localname, "name", self.name ]) self.node.cmd([constants.IP_BIN, "link", "set", self.name, "up"])
def shutdown(self): """ Control network shutdown. :return: nothing """ if self.serverintf is not None: try: utils.check_cmd([ constants.BRCTL_BIN, "delif", self.brname, self.serverintf ]) except CoreCommandError: logger.exception( "error deleting server interface %s from bridge %s", self.serverintf, self.brname) if self.updown_script is not None: try: logger.info("interface %s updown script (%s shutdown) called", self.brname, self.updown_script) utils.check_cmd([self.updown_script, self.brname, "shutdown"]) except CoreCommandError: logger.exception("error issuing shutdown script shutdown") LxBrNet.shutdown(self)
def writenodeserver(self, nodestr, server): """ Creates a /tmp/pycore.nnnnn/nX.conf/server file having the node and server info. This may be used by scripts for accessing nodes on other machines, much like local nodes may be accessed via the VnodeClient class. :param str nodestr: node string :param CoreDistributedServer server: core server :return: nothing """ serverstr = "%s %s %s" % (server.name, server.host, server.port) name = nodestr.split()[1] dirname = os.path.join(self.session.session_dir, name + ".conf") filename = os.path.join(dirname, "server") try: os.makedirs(dirname) except OSError: # directory may already exist from previous distributed run logger.exception("error creating directory: %s", dirname) try: with open(filename, "w") as f: f.write("%s\n%s\n" % (serverstr, nodestr)) except IOError: logger.exception("error writing server file %s for node %s", filename, name)
def addChannelReference(self): """ Add a reference to the channel that uses this interface """ try: cm = self.scenPlan.all_channel_members[self.id] if cm is not None: ch = cm.base_element.parentNode if ch is not None: net = ch.parentNode if net is not None: MemberElement(self.scenPlan, self, referenced_type=MembType.CHANNEL, referenced_id=ch.getAttribute("id"), index=int(cm.getAttribute("index"))) MemberElement(self.scenPlan, self, referenced_type=MembType.NETWORK, referenced_id=net.getAttribute("id")) except KeyError: # Not an error. This occurs when an interface belongs to a switch # or a hub within a network and the channel is yet to be defined logger.exception( "noted as not an error, add channel reference error")
def shutdown(self): if not self.up: logger.info("exiting shutdown, object is not up") return ebtables_queue.stopupdateloop(self) try: utils.check_cmd( [constants.IP_BIN, "link", "set", self.bridge_name, "down"]) utils.check_cmd([constants.OVS_BIN, "del-br", self.bridge_name]) ebtables_commands(utils.check_cmd, [[ constants.EBTABLES_BIN, "-D", "FORWARD", "--logical-in", self.bridge_name, "-j", self.bridge_name ], [constants.EBTABLES_BIN, "-X", self.bridge_name]]) except CoreCommandError: logger.exception("error bringing bridge down and removing it") # removes veth pairs used for bridge-to-bridge connections for interface in self.netifs(): interface.shutdown() self._netif.clear() self._linked.clear() del self.session self.up = False
def generate_config(cls, node, filename): """ Returns config.boot configuration file text. Other services that depend on this will have generatexorpconfig() hooks that are invoked here. Filename currently ignored. """ cfg = "interfaces {\n" for ifc in node.netifs(): cfg += " interface %s {\n" % ifc.name cfg += "\tvif %s {\n" % ifc.name cfg += "".join(map(cls.addrstr, ifc.addrlist)) cfg += cls.lladdrstr(ifc) cfg += "\t}\n" cfg += " }\n" cfg += "}\n\n" for s in node.services: try: s.dependencies.index(cls.name) cfg += s.generatexorpconfig(node) except ValueError: logger.exception("error getting value from service: %s", cls.name) return cfg
def deladdr(self, ifindex, addr): try: self._netif[ifindex].deladdr(addr) except ValueError: logger.exception("trying to delete unknown address: %s", addr) if self.up: pass
def detach(self, interface): if self.up: try: subprocess.check_call([constants.OVS_BIN, "del-port", self.bridge_name, interface.localname]) except subprocess.CalledProcessError: logger.exception("error removing interface %s from bridge %s", interface.localname, self.bridge_name) return PyCoreNet.detach(self, interface)
def startup(self): self.lock.acquire() try: self.makenodedir() # self.privatedir("/var/run") # self.privatedir("/var/log") except OSError: logger.exception("startup error") finally: self.lock.release()
def deladdr(self, ifindex, addr): """ same as SimpleLxcNode.deladdr() """ try: self._netif[ifindex].deladdr(addr) except ValueError: logger.exception("trying to delete unknown address: %s", addr) if self.up: self.check_cmd([constants.IP_BIN, "addr", "del", str(addr), "dev", self.ifname(ifindex)])
def UploadFile(filepath): # import shutil from tools.ftptools import ( FTPInfo, StandardFTPFactory ) q = DogQueue() q.doing(filepath) pendingFile(filepath) f = FileRoute(filepath) try: logger.info('Send file to route') transtype, ftpname, dest_path, filename = f.routeInfo() logger.info('Copy file {filepath} Begin'.format(filepath=filepath)) info = FTPInfo().get_info(ftpname) host = info.get('host', None) port = info.get('port', 22) username = info.get('username', None) password = info.get('password', None) key = info.get('key', None) f = StandardFTPFactory.get_factory(transtype) c = f.get_client(host, port, username, password, key) local = filepath if dest_path is None: dest_path = '' remote = os.path.join(dest_path, filename) temp = os.path.join(dest_path, filename + '.transfering') c.put(local, temp) c.rename(temp, remote) c.close() os.remove(filepath) # shutil.copyfile(filepath, os.path.join(dest_path, filename)) q.done(filepath) except TypeError: q.done(filepath) logger.info('{filepath} is not our file'.format(filepath=filepath)) return False except: logger.exception('UploadFile') return False else: logger.info('Copy file {filepath} Success'.format(filepath=filepath)) return True
def runthread(): ns.core.Simulator.Stop(ns.core.Seconds(self.duration)) logger.info("running ns-3 simulation for %d seconds", self.duration) if vis: try: import visualizer except ImportError: logger.exception("visualizer is not available") ns.core.Simulator.Run() else: visualizer.start() else: ns.core.Simulator.Run()
def write_state(self, state): """ Write the current state to a state file in the session dir. :param int state: state to write to file :return: nothing """ try: state_file = open(self._state_file, "w") state_file.write("%d %s\n" % (state, coreapi.state_name(state))) state_file.close() except IOError: logger.exception("error writing state file: %s", state)
def generate_config(cls, node, filename): """ Return the firewall rule examples to GUI for user customization. """ cfg = "#!/bin/sh\n" cfg += "# custom node firewall rules for service (security.py)\n" fname = "%s/examples/services/sampleFirewall" % constants.CORE_DATA_DIR try: cfg += open(fname, "rb").read() except IOError: logger.exception("Error opening Firewall configuration template (%s)", fname) return cfg
def generate_config(cls, node, filename): """ Return the client.conf and vpnclient.sh file contents to """ cfg = "#!/bin/sh\n" cfg += "# custom VPN Client configuration for service (security.py)\n" fname = "%s/examples/services/sampleVPNClient" % constants.CORE_DATA_DIR try: cfg += open(fname, "rb").read() except IOError: logger.exception("Error opening VPN client configuration template (%s)", fname) return cfg
def run_state_hooks(self, state): """ Run state hooks. :param int state: state to run hooks for :return: nothing """ for hook in self._state_hooks.get(state, []): try: hook(state) except: message = "exception occured when running %s state hook: %s" % (coreapi.state_name(state), hook) logger.exception(message) self.exception(ExceptionLevels.ERROR, "Session.run_state_hooks", None, message)
def write_objects(self): """ Write objects to a 'nodes' file in the session dir. The 'nodes' file lists: number, name, api-type, class-type """ try: nodes_file = open(os.path.join(self.session_dir, "nodes"), "w") with self._objects_lock: for object_id in sorted(self.objects.keys()): obj = self.objects[object_id] nodes_file.write("%s %s %s %s\n" % (object_id, obj.name, obj.apitype, type(obj))) nodes_file.close() except IOError: logger.exception("error writing nodes file")
def DogQueueConsumer(): logger.info('DogQueue consumer begin') q = DogQueue() try: rs = q.getAll() for r in rs: if not q.isConsuming(r): UploadFile.apply_async(args=[r]) logger.info('DogQueue consuming {filepath}'.format(filepath=r)) except: logger.exception('DogQueueConsumer') else: logger.info('DogQueue consumer end')
def update(self, moved, moved_netifs): """ Invoked from MobilityModel when nodes are moved; this causes emane location events to be generated for the nodes in the moved list, making EmaneModels compatible with Ns2ScriptedMobility. :param bool moved: were nodes moved :param list moved_netifs: interfaces that were moved :return: """ try: wlan = self.session.get_object(self.object_id) wlan.setnempositions(moved_netifs) except KeyError: logger.exception("error during update")
def _start_boot_paths(self, node, boot_path): """ Start all service boot paths found, based on dependencies. :param core.netns.vnode.LxcNode node: node to start services on :param list[CoreService] boot_path: service to start in dependent order :return: nothing """ logger.info("booting node services: %s", " -> ".join([x.name for x in boot_path])) for service in boot_path: try: self.boot_service(node, service) except: logger.exception("exception booting service: %s", service.name) raise
def generate_config(cls, node, filename): """ Return the ipsec.conf and racoon.conf file contents to GUI for user customization. """ cfg = "#!/bin/sh\n" cfg += "# set up static tunnel mode security assocation for service " cfg += "(security.py)\n" fname = "%s/examples/services/sampleIPsec" % constants.CORE_DATA_DIR try: cfg += open(fname, "rb").read() except IOError: logger.exception("Error opening IPsec configuration template (%s)", fname) return cfg
def deladdr(self, ifindex, addr): """ Delete address from an interface. :param int ifindex: index of interface to delete address from :param str addr: address to delete from interface :return: nothing :raises CoreCommandError: when a non-zero exit status occurs """ try: self._netif[ifindex].deladdr(addr) except ValueError: logger.exception("trying to delete unknown address: %s" % addr) if self.up: self.check_cmd([constants.IP_BIN, "addr", "del", str(addr), "dev", self.ifname(ifindex)])
def physnodeupdateposition(self, message): """ Snoop node messages belonging to physical nodes. The dummy object in self.phys[] records the node position. :param message: message to handle :return: nothing """ nodenum = message.node_numbers()[0] try: dummy = self.phys[nodenum] nodexpos = message.get_tlv(NodeTlvs.X_POSITION.value) nodeypos = message.get_tlv(NodeTlvs.Y_POSITION.value) dummy.setposition(nodexpos, nodeypos, None) except KeyError: logger.exception("error retrieving physical node: %s", nodenum)
def fromvaluelist(cls, service, values): """ Convert list of values into properties for this instantiated (customized) service. :param CoreService service: service to get value list for :param dict values: value list to set properties from :return: nothing """ # TODO: support empty value? e.g. override default meta with '' for key in cls.keys: try: cls.setvalue(service, key, values[cls.keys.index(key)]) except IndexError: # old config does not need to have new keys logger.exception("error indexing into key")
def shutdown(self): """ Shutdown logic for the node. :return: nothing """ if not self.up: return with self.lock: try: super(LxcNode, self).shutdown() except OSError: logger.exception("error during shutdown") finally: self.rmnodedir()
def shutdown(self): if self.serverintf: try: utils.check_cmd([constants.OVS_BIN, "del-port", self.bridge_name, self.serverintf]) except CoreCommandError: logger.exception("error deleting server interface %s to controlnet bridge %s", self.serverintf, self.bridge_name) if self.updown_script: try: logger.info("interface %s updown script (%s shutdown) called", self.bridge_name, self.updown_script) utils.check_cmd([self.updown_script, self.bridge_name, "shutdown"]) except CoreCommandError: logger.exception("error during updown script shutdown") OvsNet.shutdown(self)