def writecfg(self, cfg): ConfigFile(self.config_path).write(cfg) r_chmod(self.config_path, "o-rwx") r_chmod(self.config_path, "g+rw") if os.getuid() == 0: r_chgrp(self.config_path, KARESANSUI_GROUP)
def _pre_write_conf(self, conf_arr={}): # Change permission to be able to read/write data kss group. if os.path.exists(COLLECTD_DATA_DIR): if os.getuid() == 0: r_chgrp(COLLECTD_DATA_DIR, KARESANSUI_GROUP) r_chmod(COLLECTD_DATA_DIR, "g+rwx") r_chmod(COLLECTD_DATA_DIR, "o-rwx") dop = DictOp() dop.addconf("__", conf_arr) if dop.isset("__", ["python"]) is True: dop.cdp_unset("__", ["python", "Plugin", "python", "@ORDERS"], multiple_file=True) orders = [] orders.append(['Encoding']) orders.append(['LogTraces']) orders.append(['Interactive']) orders.append(['ModulePath']) orders.append(['Import']) orders.append(['Module']) dop.cdp_set("__", ["python", "Plugin", "python", "@ORDERS"], orders, is_opt_multi=True, multiple_file=True) return dop.getconf("__")
def iptables_lint_contents(contents, webobj=None, machine=None): from karesansui.lib.file.configfile import ConfigFile if not os.path.exists(CONF_TMP_DIR): os.makedirs(CONF_TMP_DIR) r_chmod(CONF_TMP_DIR, 0770) r_chown(CONF_TMP_DIR, KARESANSUI_USER) r_chgrp(CONF_TMP_DIR, KARESANSUI_GROUP) seconds = 10 * 60 for _old in glob.glob("%s/iptables-save.*" % (CONF_TMP_DIR, )): mtime = os.stat(_old).st_mtime if int(time.time()) > (mtime + seconds): os.unlink(_old) serial = time.strftime("%Y%m%d%H%M%S", time.localtime()) filename = "%s/iptables-save.%s" % ( CONF_TMP_DIR, serial, ) ConfigFile(filename).write(contents) r_chmod(filename, 0660) r_chown(filename, KARESANSUI_USER) r_chgrp(filename, KARESANSUI_GROUP) return iptables_lint(filename, webobj, machine, delete=True)
def createSnapshot(self, domain=None, xmlDesc=None): retval = False if domain is not None: parent_snapshot_name = self.getCurrentSnapshotName(domain) if xmlDesc is None: xml = "<domainsnapshot/>" else: # validate xml file try: doc = XMLParse(xmlDesc) name = XMLXpath(doc, '/domainsnapshot/name/text()') if name is not None: xml = xmlDesc except: pass try: xml guest = self.kvc.search_guests(domain)[0] snapshot = libvirtmod.virDomainSnapshotCreateXML(guest._o,xml,0) if snapshot is not False: retval = libvirtmod.virDomainSnapshotGetXMLDesc(snapshot, 0) except: pass if retval is not False: kvg_guest = self.kvc.search_kvg_guests(domain)[0] id = self.getCurrentSnapshotName(domain) kvg_guest.set_current_snapshot(id) # ここにsnapshotのxmlファイルに親のsnapshotの情報を書き込む処理 try: xml_path = self.getSnapshotXMLPath(id) # <parent/>が設定されてない場合 # かつ、snapshot実行前に<currentSnapshot/>が設定されていた場合 if self.getParentName(id) is None and parent_snapshot_name is not None: if os.path.exists(xml_path): doc = XMLParse(xml_path) parent = doc.createElement("parent") name = doc.createElement("name") txt = doc.createTextNode(str(parent_snapshot_name)) name.appendChild(txt) parent.appendChild(name) doc.childNodes[0].appendChild(parent) xmlDesc = self.generateXML(doc) ConfigFile(xml_path).write(xmlDesc) if os.path.exists(xml_path): if os.getuid() == 0: r_chgrp(xml_path,KARESANSUI_GROUP) r_chmod(xml_path,"g+rw") r_chmod(xml_path,"o-rwx") except: pass return retval
def create(self): if not os.path.exists(self.path): self.db = self._open("c") from karesansui.lib.utils import r_chmod, r_chgrp r_chgrp(self.path,KARESANSUI_GROUP) r_chmod(self.path,"g+rw") else: self.db = self._open("c") pass
def writecfg(self,cfg, config_dir=None): if config_dir is None: config_dir = self.config_dir filename = "%s/%s" %(config_dir, self.config.get_domain_name()) ConfigFile(filename).write(cfg) r_chmod(filename,"o-rwx") r_chmod(filename,"g+rw") if os.getuid() == 0: r_chgrp(filename,KARESANSUI_GROUP)
def copycfg(self,src_dir): src_filename = "%s/%s" %(src_dir, self.config.get_domain_name()) filename = "%s/%s" %(self.config_dir, self.config.get_domain_name()) shutil.copy(src_filename, filename) r_chmod(filename,"o-rwx") r_chmod(filename,"g+rw") if os.getuid() == 0: r_chgrp(filename,KARESANSUI_GROUP)
def _pre_write_conf(self,conf_arr={}): # Change permission to be able to read/write data kss group. if os.path.exists(COLLECTD_DATA_DIR): if os.getuid() == 0: r_chgrp(COLLECTD_DATA_DIR,KARESANSUI_GROUP) r_chmod(COLLECTD_DATA_DIR,"g+rwx") r_chmod(COLLECTD_DATA_DIR,"o-rwx") dop = DictOp() dop.addconf("__",conf_arr) if dop.isset("__",["python"]) is True: dop.cdp_unset("__",["python","Plugin","python","@ORDERS"],multiple_file=True) orders = [] orders.append(['Encoding']) orders.append(['LogTraces']) orders.append(['Interactive']) orders.append(['ModulePath']) orders.append(['Import']) orders.append(['Module']) dop.cdp_set("__",["python","Plugin","python","@ORDERS"],orders,is_opt_multi=True,multiple_file=True) return dop.getconf("__")
def iptables_lint_contents(contents, webobj=None, machine=None): from karesansui.lib.file.configfile import ConfigFile if not os.path.exists(CONF_TMP_DIR): os.makedirs(CONF_TMP_DIR) r_chmod(CONF_TMP_DIR,0770) r_chown(CONF_TMP_DIR,KARESANSUI_USER) r_chgrp(CONF_TMP_DIR,KARESANSUI_GROUP) seconds = 10 * 60 for _old in glob.glob("%s/iptables-save.*" % (CONF_TMP_DIR,)): mtime = os.stat(_old).st_mtime if int(time.time()) > (mtime + seconds): os.unlink(_old) serial = time.strftime("%Y%m%d%H%M%S",time.localtime()) filename = "%s/iptables-save.%s" % (CONF_TMP_DIR,serial,) ConfigFile(filename).write(contents) r_chmod(filename,0660) r_chown(filename,KARESANSUI_USER) r_chgrp(filename,KARESANSUI_GROUP) return iptables_lint(filename, webobj, machine, delete=True)
class StorageXMLGenerator: def __init__(self): self.config_dir = VIRT_STORAGE_CONFIG_DIR def _create_text_node(self, tag, txt): node = self.document.createElement(tag) self._add_text(node, txt) return node def _add_text(self, node, txt): txt_n = self.document.createTextNode(txt) node.appendChild(txt_n) def generate(self, config): tree = self.generate_xml_tree(config) out = StringIO() out.write(tree.toxml()) return out.getvalue() def end_build(self): pass def writecfg(self, cfg): try: os.makedirs(self.config_dir) except OSError, (err, msg): if err != errno.EEXIST: raise OSError(err, msg) filename = "%s/%s.xml" % (self.config_dir, self.config.get_storage_name()) ConfigFile(filename).write(cfg) r_chmod(filename, "o-rwx") r_chmod(filename, "g+rw") if os.getuid() == 0: r_chgrp(filename, KARESANSUI_GROUP)
def createSnapshot(self, domain=None, xmlDesc=None): retval = False if domain is not None: parent_snapshot_name = self.getCurrentSnapshotName(domain) if xmlDesc is None: xml = "<domainsnapshot/>" else: # validate xml file try: doc = XMLParse(xmlDesc) name = XMLXpath(doc, '/domainsnapshot/name/text()') if name is not None: xml = xmlDesc except: pass try: xml guest = self.kvc.search_guests(domain)[0] snapshot = libvirtmod.virDomainSnapshotCreateXML( guest._o, xml, 0) if snapshot is not False: retval = libvirtmod.virDomainSnapshotGetXMLDesc( snapshot, 0) except: pass if retval is not False: kvg_guest = self.kvc.search_kvg_guests(domain)[0] id = self.getCurrentSnapshotName(domain) kvg_guest.set_current_snapshot(id) # ここにsnapshotのxmlファイルに親のsnapshotの情報を書き込む処理 try: xml_path = self.getSnapshotXMLPath(id) # <parent/>が設定されてない場合 # かつ、snapshot実行前に<currentSnapshot/>が設定されていた場合 if self.getParentName( id) is None and parent_snapshot_name is not None: if os.path.exists(xml_path): doc = XMLParse(xml_path) parent = doc.createElement("parent") name = doc.createElement("name") txt = doc.createTextNode(str(parent_snapshot_name)) name.appendChild(txt) parent.appendChild(name) doc.childNodes[0].appendChild(parent) xmlDesc = self.generateXML(doc) ConfigFile(xml_path).write(xmlDesc) if os.path.exists(xml_path): if os.getuid() == 0: r_chgrp(xml_path, KARESANSUI_GROUP) r_chmod(xml_path, "g+rw") r_chmod(xml_path, "o-rwx") except: pass return retval
def exec_script(script="",user="******",msg="",watch_name="",logfile="/dev/null"): retval = False func_name = sys._getframe(0).f_code.co_name append_line(logfile,"[%s] Entering function '%s'." % (func_name,func_name,)) # スクリプトの一時保存ディレクトリを作成 SCRIPT_TMP_DIR = "%s/tmp/.script" % (KARESANSUI_DATA_DIR,) if not os.path.exists(SCRIPT_TMP_DIR): os.makedirs(SCRIPT_TMP_DIR) r_chmod(SCRIPT_TMP_DIR,0770) r_chown(SCRIPT_TMP_DIR,KARESANSUI_USER) r_chgrp(SCRIPT_TMP_DIR,KARESANSUI_GROUP) append_line(logfile,"[%s] Create directory '%s'." % (func_name,SCRIPT_TMP_DIR,)) try: user_id = int(user) except: user_id = pwd.getpwnam(user)[2] # スクリプトファイルの生成 fname = None try: fd, fname = tempfile.mkstemp(suffix="",prefix="script_",dir=SCRIPT_TMP_DIR) append_line(logfile,"[%s] Create script '%s'." % (func_name,fname,)) fp = os.fdopen(fd,"w") fcntl.lockf(fp.fileno(), fcntl.LOCK_EX) script = re.sub("%{watch_name}",watch_name.encode('utf_8'),script) script = re.sub("%{msg}" ,msg.encode('utf_8') ,script) fp.write(script) fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() os.chmod(fname,0700) os.chown(fname,user_id,-1) except: append_line(logfile,"[%s] Error: failed to create script." % (func_name,)) if fname is not None and os.path.exists(fname): os.unlink(fname) if fname is not None and os.path.exists(fname): # マジッククッキーを調べる magic_cookie = open(fname).readline().rstrip() if magic_cookie[-8:] == "bin/perl": interpreter = "perl" elif magic_cookie[-10:] == "bin/python" or \ magic_cookie[-10:] == "env python": interpreter = "python" elif magic_cookie[-7:] == "bin/php": interpreter = "php" elif magic_cookie[-8:] == "bin/ruby": interpreter = "ruby" elif magic_cookie[-8:] == "bin/tcsh": interpreter = "tcsh" elif magic_cookie[-7:] == "bin/csh": interpreter = "csh" else: interpreter = "sh" # コマンド文字列の作成 if os.getuid() != user_id: command_args = ["su","-s", "/bin/bash", user, fname] else: command_args = [interpreter,fname] # コマンドの実行 append_line(logfile,"[%s] Execute command '%s'." % (func_name," ".join(command_args),)) (rc,res) = execute_command(command_args) new_res = [] for _aline in res: append_line(logfile,"[%s] output> %s" % (func_name,_aline,)) _aline = re.sub("^%s:[ \t]+" % fname, "", _aline) new_res.append(_aline) pass append_line(logfile,"[%s] command return value = %d" % (func_name,rc,)) os.unlink(fname) retval = [rc,new_res] else: append_line(logfile,"[%s] Error: cannot create script file." % (func_name,)) append_line(logfile,"[%s] Leaving function '%s'." % (func_name,func_name,)) return retval
class XMLConfigGenerator(XMLGenerator): def __init__(self): self.config_dir = VIRT_XML_CONFIG_DIR def generate_xml_tree(self, config): config.validate() self.config = config self.begin_build() self.build_os() self.build_features() self.build_other() self.build_devices() self.build_behavior() self.end_build() return self.document def begin_build(self): self.document = implementation.createDocument(None,None,None) self.domain = self.document.createElement("domain") self.domain.setAttribute("type", self.config.get_domain_type()) name = self._create_text_node("name", self.config.get_domain_name()) uuid = self._create_text_node("uuid", self.config.get_uuid()) self.domain.appendChild(name) self.domain.appendChild(uuid) if self.config.get_current_snapshot(): current_snapshot = self._create_text_node("currentSnapshot", self.config.get_current_snapshot()) self.domain.appendChild(current_snapshot) self.document.appendChild(self.domain) def build_os(self): doc = self.document os_elem = doc.createElement("os") if self.config.get_domain_type() == "kvm": type_n = self._create_text_node("type", "hvm") type_n.setAttribute("arch", os.uname()[4]) type_n.setAttribute("machine", "pc") else: type_n = self._create_text_node("type", "linux") os_elem.appendChild(type_n) if self.config.get_kernel(): os_elem.appendChild(self._create_text_node("kernel", self.config.get_kernel())) if self.config.get_initrd(): os_elem.appendChild(self._create_text_node("initrd", self.config.get_initrd())) os_elem.appendChild(self._create_text_node("root", "/dev/" + self.config.get_disk()[0]["target"])) if self.config.get_boot_dev(): boot_dev_n = doc.createElement("boot") boot_dev_n.setAttribute("dev", self.config.get_boot_dev()) os_elem.appendChild(boot_dev_n) # additional commandline if self.config.get_commandline(): os_elem.appendChild(self._create_text_node("cmdline", self.config.get_commandline())) self.domain.appendChild(os_elem) def build_features(self): doc = self.document if self.config.get_features_pae() is True or \ self.config.get_features_acpi() is True or \ self.config.get_features_apic() is True: features_elem = doc.createElement("features") if self.config.get_features_pae() is True: features_elem.appendChild(self._create_text_node("pae",None)) if self.config.get_features_acpi() is True: features_elem.appendChild(self._create_text_node("acpi",None)) if self.config.get_features_apic() is True: features_elem.appendChild(self._create_text_node("apic",None)) self.domain.appendChild(features_elem) def build_other(self): self.domain.appendChild(self._create_text_node("maxmem", str(self.config.get_max_memory("k")))) self.domain.appendChild(self._create_text_node("memory", str(self.config.get_memory("k")))) self.domain.appendChild(self._create_text_node("vcpu", str(self.config.get_max_vcpus()))) if self.config.get_bootloader(): self.domain.appendChild(self._create_text_node("bootloader", str(self.config.get_bootloader()))) def build_devices(self): doc = self.document devs_elem = doc.createElement("devices") # graphics if self.config.get_graphics_port(): graphics_n = doc.createElement("graphics") if self.config.get_graphics_type() == "sdl": graphics_n.setAttribute("type", "sdl") elif self.config.get_graphics_type() == "spice": graphics_n.setAttribute("type", "spice") else: graphics_n.setAttribute("type", "vnc") graphics_n.setAttribute("port", str(self.config.get_graphics_port())) graphics_n.setAttribute("autoport", str(self.config.get_graphics_autoport())) graphics_n.setAttribute("listen", str(self.config.get_graphics_listen())) if self.config.get_graphics_keymap() is not None: graphics_n.setAttribute("keymap", str(self.config.get_graphics_keymap())) if self.config.get_graphics_passwd() is not None: graphics_n.setAttribute("passwd", str(self.config.get_graphics_passwd())) devs_elem.appendChild(graphics_n) # disks for disk in self.config.get_disk(): disk_n = doc.createElement("disk") if disk["disk_type"] == "file": disk_n.setAttribute("type", "file") elif disk["disk_type"] == "block": disk_n.setAttribute("type", "block") else: disk_n.setAttribute("type", "file") # default disk_n.setAttribute("device", disk["device"]) # disk -> driver driver_n = doc.createElement("driver") try: if disk["driver_name"] is not None: driver_n.setAttribute("name", disk["driver_name"]) except: pass try: if disk["driver_type"] is not None: driver_n.setAttribute("type", disk["driver_type"]) except: pass source_n = doc.createElement("source") if disk["disk_type"] == "file": source_n.setAttribute("file", disk["path"]) elif disk["disk_type"] == "block": source_n.setAttribute("dev", disk["path"]) else: source_n.setAttribute("file", disk["path"]) # default target_n = doc.createElement("target") target_n.setAttribute("dev", disk["target"]) if disk["bus"] != None: target_n.setAttribute("bus", disk["bus"]) disk_n.appendChild(driver_n) disk_n.appendChild(source_n) disk_n.appendChild(target_n) #if isset("disk['shareable']",vars=locals()) is True: # disk_n.appendChild(self._create_text_node("shareable",None)) #if isset("disk['readonly']",vars=locals()) is True: # disk_n.appendChild(self._create_text_node("readonly",None)) devs_elem.appendChild(disk_n) # network for interface in self.config.get_interface(): interface_n = doc.createElement("interface") interface_n.setAttribute("type", "bridge") source_n = doc.createElement("source") source_n.setAttribute("bridge", interface["bridge"]) mac_n = doc.createElement("mac") mac_n.setAttribute("address", interface["mac"]) interface_n.appendChild(source_n) interface_n.appendChild(mac_n) if interface["script"] != None: script_n = doc.createElement("script") script_n.setAttribute("path", interface["script"]) interface_n.appendChild(script_n) if interface["target"] != None: target_n = doc.createElement("target") target_n.setAttribute("dev", interface["target"]) interface_n.appendChild(target_n) if interface["model"] != None: model_n = doc.createElement("model") model_n.setAttribute("type", interface["model"]) interface_n.appendChild(model_n) devs_elem.appendChild(interface_n) self.domain.appendChild(devs_elem) def build_behavior(self): self.domain.appendChild(self._create_text_node("on_poweroff", self.config.get_behavior("on_poweroff"))) self.domain.appendChild(self._create_text_node("on_reboot", self.config.get_behavior("on_reboot"))) self.domain.appendChild(self._create_text_node("on_crash", self.config.get_behavior("on_crash"))) def end_build(self): pass def writecfg(self,cfg,config_dir=None): if config_dir is None: config_dir = self.config_dir try: os.makedirs(config_dir) except OSError, (err, msg): if err != errno.EEXIST: raise OSError(err,msg) filename = "%s/%s.xml" %(config_dir,self.config.get_domain_name()) ConfigFile(filename).write(cfg) r_chmod(filename,"o-rwx") r_chmod(filename,"g+rw") if os.getuid() == 0: r_chgrp(filename,KARESANSUI_GROUP)
def exec_script(script="", user="******", msg="", watch_name="", logfile="/dev/null"): retval = False func_name = sys._getframe(0).f_code.co_name append_line(logfile, "[%s] Entering function '%s'." % ( func_name, func_name, )) # スクリプトの一時保存ディレクトリを作成 SCRIPT_TMP_DIR = "%s/tmp/.script" % (KARESANSUI_DATA_DIR, ) if not os.path.exists(SCRIPT_TMP_DIR): os.makedirs(SCRIPT_TMP_DIR) r_chmod(SCRIPT_TMP_DIR, 0770) r_chown(SCRIPT_TMP_DIR, KARESANSUI_USER) r_chgrp(SCRIPT_TMP_DIR, KARESANSUI_GROUP) append_line( logfile, "[%s] Create directory '%s'." % ( func_name, SCRIPT_TMP_DIR, )) try: user_id = int(user) except: user_id = pwd.getpwnam(user)[2] # スクリプトファイルの生成 fname = None try: fd, fname = tempfile.mkstemp(suffix="", prefix="script_", dir=SCRIPT_TMP_DIR) append_line(logfile, "[%s] Create script '%s'." % ( func_name, fname, )) fp = os.fdopen(fd, "w") fcntl.lockf(fp.fileno(), fcntl.LOCK_EX) script = re.sub("%{watch_name}", watch_name.encode('utf_8'), script) script = re.sub("%{msg}", msg.encode('utf_8'), script) fp.write(script) fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() os.chmod(fname, 0700) os.chown(fname, user_id, -1) except: append_line(logfile, "[%s] Error: failed to create script." % (func_name, )) if fname is not None and os.path.exists(fname): os.unlink(fname) if fname is not None and os.path.exists(fname): # マジッククッキーを調べる magic_cookie = open(fname).readline().rstrip() if magic_cookie[-8:] == "bin/perl": interpreter = "perl" elif magic_cookie[-10:] == "bin/python" or \ magic_cookie[-10:] == "env python": interpreter = "python" elif magic_cookie[-7:] == "bin/php": interpreter = "php" elif magic_cookie[-8:] == "bin/ruby": interpreter = "ruby" elif magic_cookie[-8:] == "bin/tcsh": interpreter = "tcsh" elif magic_cookie[-7:] == "bin/csh": interpreter = "csh" else: interpreter = "sh" # コマンド文字列の作成 if os.getuid() != user_id: command_args = ["su", "-s", "/bin/bash", user, fname] else: command_args = [interpreter, fname] # コマンドの実行 append_line( logfile, "[%s] Execute command '%s'." % ( func_name, " ".join(command_args), )) (rc, res) = execute_command(command_args) new_res = [] for _aline in res: append_line(logfile, "[%s] output> %s" % ( func_name, _aline, )) _aline = re.sub("^%s:[ \t]+" % fname, "", _aline) new_res.append(_aline) pass append_line(logfile, "[%s] command return value = %d" % ( func_name, rc, )) os.unlink(fname) retval = [rc, new_res] else: append_line(logfile, "[%s] Error: cannot create script file." % (func_name, )) append_line(logfile, "[%s] Leaving function '%s'." % ( func_name, func_name, )) return retval
class NetworkXMLConfigGenerator(NetworkXMLGenerator): def __init__(self): self.config_dir = VIRT_NETWORK_CONFIG_DIR def generate_xml_tree(self, config): config.validate() self.config = config self.begin_build() self.build_bridge() self.build_forward() self.build_ip() self.end_build() return self.document def begin_build(self): self.document = implementation.createDocument(None, None, None) self.network = self.document.createElement("network") name = self._create_text_node("name", self.config.get_network_name()) uuid = self._create_text_node("uuid", self.config.get_uuid()) self.network.appendChild(name) self.network.appendChild(uuid) self.document.appendChild(self.network) def build_bridge(self): doc = self.document if self.config.get_bridge(): bridge = doc.createElement("bridge") bridge.setAttribute("name", self.config.get_bridge()) if self.config.get_bridge_stp() is not None: bridge.setAttribute("stp", self.config.get_bridge_stp()) else: bridge.setAttribute("stp", "on") if self.config.get_bridge_forwardDelay() is not None: bridge.setAttribute("forwardDelay", self.config.get_bridge_forwardDelay()) else: bridge.setAttribute("forwardDelay", "0") self.network.appendChild(bridge) def build_forward(self): doc = self.document if self.config.get_forward_dev() is not None or \ self.config.get_forward_mode() is not None: forward = doc.createElement("forward") if self.config.get_forward_dev() is not None: forward.setAttribute("dev", self.config.get_forward_dev()) if self.config.get_forward_mode() is not None: forward.setAttribute("mode", self.config.get_forward_mode()) self.network.appendChild(forward) def build_ip(self): doc = self.document ip = doc.createElement("ip") ip.setAttribute("netmask", self.config.get_netmask()) ip.setAttribute("address", self.config.get_ipaddr()) self.network.appendChild(ip) dhcp = doc.createElement("dhcp") range = doc.createElement("range") range.setAttribute("start", self.config.get_dhcp_start()) range.setAttribute("end", self.config.get_dhcp_end()) dhcp.appendChild(range) ip.appendChild(dhcp) def end_build(self): pass def writecfg(self, cfg): try: os.makedirs(self.config_dir) except OSError, (err, msg): if err != errno.EEXIST: raise OSError(err, msg) filename = "%s/%s.xml" % (self.config_dir, self.config.get_network_name()) ConfigFile(filename).write(cfg) r_chmod(filename, "o-rwx") r_chmod(filename, "g+rw") if os.getuid() == 0: r_chgrp(filename, KARESANSUI_GROUP)
def copycfg(self,src_dir): try: os.makedirs(self.config_dir) except OSError, (err, msg): if err != errno.EEXIST: raise OSError(err,msg) src_filename = "%s/%s.xml" %(src_dir ,self.config.get_domain_name()) filename = "%s/%s.xml" %(self.config_dir,self.config.get_domain_name()) shutil.copy(src_filename, filename) r_chmod(filename,"o-rwx") r_chmod(filename,"g+rw") if os.getuid() == 0: r_chgrp(filename,KARESANSUI_GROUP) def removecfg(self, config_dir=None): if config_dir is None: config_dir = self.config_dir filename = "%s/%s.xml" %(config_dir,self.config.get_domain_name()) if os.path.exists(filename): os.unlink(filename) def sync_config_generator(param, domname=None): domain_type = param.get_domain_type() tmp_prefix = KVM_KARESANSUI_TMP_DIR if domain_type == "xen":
def write_conf(dop, webobj=None, machine=None, modules=[], extra_args={}): """<comment-ja> @param dop: 辞書配列操作オブジェクト @param webobj: @param machine: @type dop: object dict_op @rtype: boolean @return: True or False </comment-ja> <comment-en> TODO: English Comment </comment-en> """ from karesansui.lib.file.configfile import ConfigFile if isinstance(dop,karesansui.lib.dict_op.DictOp) is False: return False if not os.path.exists(CONF_TMP_DIR): os.makedirs(CONF_TMP_DIR) r_chmod(CONF_TMP_DIR,0770) r_chown(CONF_TMP_DIR,KARESANSUI_USER) r_chgrp(CONF_TMP_DIR,KARESANSUI_GROUP) serial = time.strftime("%Y%m%d%H%M%S",time.localtime()) if len(modules) == 0: modules = dop.ModuleNames w_modules = [] w_files = [] for _module in modules: if _module in dop.ModuleNames: filename = "%s/%s.%s" % (CONF_TMP_DIR,_module,serial,) data = preprint_r(dop.getconf(_module),return_var=True) ConfigFile(filename).write(data+"\n") r_chmod(filename,0660) r_chown(filename,KARESANSUI_USER) r_chgrp(filename,KARESANSUI_GROUP) w_modules.append(_module) w_files.append(filename) if len(w_modules) == 0: return False options = { "module" : ":".join(w_modules), "input-file" : ":".join(w_files), } options["delete"] = None try: extra_args['pre-command'] options['pre-command'] = "b64:" + base64_encode(extra_args['pre-command']) except: pass try: extra_args['post-command'] options['post-command'] = "b64:" + base64_encode(extra_args['post-command']) except: pass try: options['include'] = extra_args['include'] except: pass #cmd_name = u"Write Settings - %s" % ":".join(w_modules) cmd_name = u"Write Settings" if type(webobj) == types.InstanceType: from karesansui.db.model._2pysilhouette import Job, JobGroup, \ JOBGROUP_TYPE from karesansui.db.access._2pysilhouette import jg_findby1, jg_save,corp from karesansui.db.access._2pysilhouette import save_job_collaboration from karesansui.db.access.machine2jobgroup import new as m2j_new from pysilhouette.command import dict2command _cmd = dict2command( "%s/%s" % (karesansui.config['application.bin.dir'], CONFIGURE_COMMAND_WRITE), options) _jobgroup = JobGroup(cmd_name, karesansui.sheconf['env.uniqkey']) _jobgroup.jobs.append(Job('%s command' % cmd_name, 0, _cmd)) _machine2jobgroup = m2j_new(machine=machine, jobgroup_id=-1, uniq_key=karesansui.sheconf['env.uniqkey'], created_user=webobj.me, modified_user=webobj.me, ) save_job_collaboration(webobj.orm, webobj.pysilhouette.orm, _machine2jobgroup, _jobgroup, ) """ _jobgroup.type = JOBGROUP_TYPE['PARALLEL'] if corp(webobj.orm, webobj.pysilhouette.orm,_machine2jobgroup, _jobgroup) is False: webobj.logger.debug("%s command failed. Return to timeout" % (cmd_name)) for filename in w_files: if os.path.exists(filename): os.unlink(filename) return False cmd_res = jobgroup.jobs[0].action_stdout """ else: from karesansui.lib.utils import execute_command opts_str = "" for x in options.keys(): if options[x] is None: opts_str += "--%s " % x else: opts_str += "--%s=%s " % (x, options[x]) _cmd = "%s/bin/%s %s" % (KARESANSUI_PREFIX, CONFIGURE_COMMAND_WRITE, opts_str.strip(),) command_args = _cmd.strip().split(" ") (rc,res) = execute_command(command_args) if rc != 0: for filename in w_files: if os.path.exists(filename): os.unlink(filename) return False cmd_res = "\n".join(res) """ for filename in w_files: if os.path.exists(filename): os.unlink(filename) """ return True
class KaresansuiIpTables(IptablesXMLGenerator): def __init__(self): self.iptables_conf_file = "/etc/sysconfig/iptables" self.firewall_xml_file = FIREWALL_XML_FILE self._lsmod = "/sbin/lsmod" self._iptables = "/sbin/iptables" self._iptables_save = "/sbin/iptables-save" self._iptables_init = "/etc/init.d/iptables" self.basic_targets = { 'filter': ['ACCEPT', 'DROP', 'REJECT'], 'nat': ['ACCEPT', 'DROP', 'REJECT', 'MASQUERADE', 'REDIRECT', 'DNAT'], 'mangle': ['ACCEPT', 'DROP', 'REJECT'], } self.basic_chains = { 'filter': ['INPUT', 'OUTPUT', 'FORWARD'], 'nat': ['PREROUTING', 'OUTPUT', 'POSTROUTING'], 'mangle': ['PREROUTING', 'INPUT', 'OUTPUT', 'FORWARD', 'POSTROUTING'], } self.chain_protos = ['tcp', 'udp', 'icmp', 'esp', 'ah', 'sctp'] self.ipt_original_opts = { "append|A": 1, "delete|D": 1, "insert|I": 1, "replace|R": 1, "list|L": 0, "flush|F": 0, "zero|Z": 0, "new-chain|N": 1, "delete-chain|X": 1, "rename-chain|E": 1, "policy|P": 1, "source|src|s": 1, "destination|dst|d": 1, "protocol|p": 1, "in-interface|i": 1, "jump|j": 1, "table|t": 1, "match|m": 1, "numeric|n": 0, "out-interface|o": 1, "verbose|v": 0, "exact|x": 0, "fragments|f": 0, "version|V": 0, "help|h": 0, "line-numbers|0": 0, "modprobe|M": 0, "set-counters|c": 1, "goto|g": 1, } self.ipt_udp_opts = { "source-port": 1, "sport": 1, "destination-port": 1, "dport": 1, } self.ipt_tcp_opts = { "source-port": 1, "sport": 1, "destination-port": 1, "dport": 1, "syn": 0, "tcp-flags": 1, "tcp-option": 1, } self.ipt_ext_opts = { "state": 1, # --state [INVALID|ESTABLISHED|NEW|RELATED|UNTRACKED] "reject-with": 1, "mss": 1, # --mss value[:value] } self.params = { "target": "target", "protocol": "protocol", "source": "source", "destination": "destination", "sport": "source-port", "dport": "destination-port", "inif": "in-interface", "outif": "out-interface", "option": "option", } return None def firewall_xml__to__iptables_config(self): self.firewall_xml = self.read_firewall_xml() self.set_default() self.write_iptables_config() def firewall_xml__from__iptables_config(self): self.firewall_xml = self.read_iptables_config() self.set_default() self.write_firewall_xml() def read_iptables_config(self): config = {} res = [] if is_readable(self.iptables_conf_file): res = ConfigFile(self.iptables_conf_file).read() ret = 0 if len(res) == 0: cmd = [] cmd.append(self._iptables_save) (ret, res) = execute_command(cmd) table_regex = re.compile(r"""^\*(?P<table>[a-z]+)""") policy_regex = re.compile(r"""^:(?P<chain>\S+) (?P<target>\S+)""") rule_regex = re.compile(r"""^\-A (?P<rule>\S+)""") end_regex = re.compile(r"""^COMMIT$""") if ret == 0 and len(res) > 0: for aline in res: aline = aline.rstrip() aline = aline.replace(RH_USERCHAIN, FIREWALL_USERCHAIN) m = end_regex.match(aline) if m is not None: for chain, policy in policies.iteritems(): rule = self._make_rule_arr(rules[chain]) info = {"policy": policies[chain], "rule": rule} table_info[chain] = info config[table] = table_info continue m = table_regex.match(aline) if m is not None: table = m.group("table") table_info = {} policies = {} rules = {} else: m = policy_regex.match(aline) if m is not None: chain = m.group("chain") target = m.group("target") policies[chain] = target rules[chain] = [] else: m = rule_regex.match(aline) if m is not None: rule_chain = m.group("rule") rules[rule_chain].append(aline) #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(config) return config def write_iptables_config(self): try: self.set_libvirt_rules() self.write_firewall_xml() ConfigFile(self.iptables_conf_file).write( "\n".join(self.make_save_lines()) + "\n") except: raise KaresansuiIpTablesException( "Error: Cannot write iptables configuration file.") def _make_rule_arr(self, rules): arr = [] for aline in rules: arr.append(self._rule_str_to_arr(aline)) return arr def _rule_str_to_arr(self, string, rule_id=None): #print string m_re = re.compile( r"""(^| )-{1,2}(?P<opt>\S+) ?(?P<value>(\! )?\S+)?""", flags=0) for k, v in self.params.iteritems(): exec("%s = ''" % (k, )) for itr in m_re.finditer(string): opt = itr.group('opt') value = itr.group('value') if opt == 'A' or opt == 'append': continue elif opt == 'j' or opt == 'jump': target = value elif opt == 'p' or opt == 'protocol': protocol = value elif opt == 's' or opt == 'src' or opt == 'source': source = value elif opt == 'd' or opt == 'dst' or opt == 'destination': destination = value elif opt == 'sport' or opt == 'source-port': sport = value elif opt == 'dport' or opt == 'destination-port': dport = value elif opt == 'i' or opt == 'in-interface': inif = value elif opt == 'o' or opt == 'out-interface': outif = value else: if len(opt) == 1: opt = "-%s" % opt else: opt = "--%s" % opt if option is None: option = "" option = "%s %s %s" % ( option, opt, value, ) rule_info = { "id": rule_id, "target": target, "protocol": protocol, "source": source, "destination": destination, "source-port": sport, "destination-port": dport, "in-interface": inif, "out-interface": outif, "option": option, } return rule_info def read_firewall_xml(self, path=None): config = {} if path is None: path = self.firewall_xml_file if not os.path.exists(path) or os.path.getsize(path) == 0: raise KaresansuiIpTablesException("no such file: %s" % path) document = XMLParse(path) table_num = XMLXpathNum(document, '/firewall/table') for tbl in range(1, table_num + 1): table_name = XMLXpath(document, '/firewall/table[%i]/@name' % (tbl, )) if table_name is None: table_name = 'filter' chain = {} chain_num = XMLXpathNum(document, '/firewall/table[%i]/chain' % (tbl, )) for chn in range(1, chain_num + 1): chain_name = XMLXpath( document, '/firewall/table[%i]/chain[%i]/@name' % ( tbl, chn, )) chain_policy = XMLXpath( document, '/firewall/table[%i]/chain[%i]/@policy' % ( tbl, chn, )) rule = [] rule_num = XMLXpathNum( document, '/firewall/table[%i]/chain[%i]/rule' % ( tbl, chn, )) for rl in range(1, rule_num + 1): rule_id = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/@id' % ( tbl, chn, rl, )) target = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/target/text()' % ( tbl, chn, rl, )) if target is None: target = '' else: target = target.strip() protocol = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/protocol/text()' % ( tbl, chn, rl, )) if protocol is None: protocol = '' else: protocol = protocol.strip() if protocol == "50": protocol = "esp" if protocol == "51": protocol = "ah" source = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/source/text()' % ( tbl, chn, rl, )) if source is None: source = '' else: source = source.strip() destination = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/destination/text()' % ( tbl, chn, rl, )) if destination is None: destination = '' else: destination = destination.strip() sport = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/source-port/text()' % ( tbl, chn, rl, )) if sport is None: sport = '' else: sport = sport.strip() dport = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/destination-port/text()' % ( tbl, chn, rl, )) if dport is None: dport = '' else: dport = dport.strip() inif = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/in-interface/text()' % ( tbl, chn, rl, )) if inif is None: inif = '' else: inif = inif.strip() outif = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/out-interface/text()' % ( tbl, chn, rl, )) if outif is None: outif = '' else: outif = outif.strip() option = XMLXpath( document, '/firewall/table[%i]/chain[%i]/rule[%i]/option/text()' % ( tbl, chn, rl, )) if option is None: option = '' else: option = option.strip() rule_info = { "id": rule_id, "target": target, "protocol": protocol, "source": source, "destination": destination, "source-port": sport, "destination-port": dport, "in-interface": inif, "out-interface": outif, "option": option, } rule.append(rule_info) chain_info = { "policy": chain_policy, "rule": rule, } chain[chain_name] = chain_info config[table_name] = chain return config def generate_xml_tree(self, config): self.firewall_xml = config self.begin_build() for tbl, val in self.firewall_xml.iteritems(): self.build_table(tbl) self.end_build() return self.document def begin_build(self): self.document = implementation.createDocument(None, None, None) self.firewall = self.document.createElement("firewall") self.firewall.setAttribute("type", "iptables") self.firewall.appendChild( self._create_text_node("last_modified", "%s" % time.ctime())) self.document.appendChild(self.firewall) def build_table(self, name): doc = self.document table = doc.createElement("table") table.setAttribute("name", name) chains = self.firewall_xml[name] for chain_name, val in chains.iteritems(): chain_n = doc.createElement("chain") chain_n.setAttribute("name", chain_name) try: if val['policy'] is not None: chain_n.setAttribute("policy", val['policy']) except: pass cnt = 1 for rule in val["rule"]: rule_n = doc.createElement("rule") rule_n.setAttribute("id", str(cnt)) if rule["target"] is not None: target = self._create_text_node("target", rule["target"]) rule_n.appendChild(target) try: if rule["protocol"] is not None and rule["protocol"] != "": protocol = self._create_text_node( "protocol", rule["protocol"]) rule_n.appendChild(protocol) except: pass try: if rule["source"] is not None and rule["source"] != "": source = self._create_text_node( "source", rule["source"]) rule_n.appendChild(source) except: pass try: if rule["destination"] is not None and rule[ "destination"] != "": destination = self._create_text_node( "destination", rule["destination"]) rule_n.appendChild(destination) except: pass try: if rule["source-port"] is not None and rule[ "source-port"] != "": sport = self._create_text_node("source-port", rule["source-port"]) rule_n.appendChild(sport) except: pass try: if rule["destination-port"] is not None and rule[ "destination-port"] != "": dport = self._create_text_node( "destination-port", rule["destination-port"]) rule_n.appendChild(dport) except: pass try: if rule["in-interface"] is not None and rule[ "in-interface"] != "": inif = self._create_text_node("in-interface", rule["in-interface"]) rule_n.appendChild(inif) except: pass try: if rule["out-interface"] is not None and rule[ "out-interface"] != "": outif = self._create_text_node("out-interface", rule["out-interface"]) rule_n.appendChild(outif) except: pass try: if rule["option"] is not None and rule["option"] != "": option = self._create_text_node( "option", rule["option"]) rule_n.appendChild(option) except: pass chain_n.appendChild(rule_n) cnt = cnt + 1 table.appendChild(chain_n) self.firewall.appendChild(table) def end_build(self): pass def write_firewall_xml(self, path=None): if path is None: path = self.firewall_xml_file try: pathdir = os.path.dirname(path) os.makedirs(pathdir) except OSError, (err, msg): if err != errno.EEXIST: raise OSError(err, msg) #print self.generate(self.firewall_xml) ConfigFile(path).write(self.generate(self.firewall_xml)) if os.getuid() == 0 and os.path.exists(path): r_chgrp(path, KARESANSUI_GROUP) os.chmod(path, 0664)