diff --git a/tools/crm.in b/tools/crm.in index 7be886e56c..cd1d74fc57 100644 --- a/tools/crm.in +++ b/tools/crm.in @@ -1,3999 +1,3999 @@ #!/usr/bin/env python # # Copyright (C) 2008 Dejan Muhamedagic # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # import shlex import os from tempfile import mkstemp import subprocess import sys import time import readline import copy import xml.dom.minidom import signal import re class ErrorBuffer(object): ''' Show error messages either immediately or buffered. ''' def __init__(self): self.msg_list = [] self.mode = "immediate" def buffer(self): self.mode = "keep" def release(self): if self.msg_list: print '\n'.join(self.msg_list) if interactive: raw_input("Press enter to continue... ") self.msg_list = [] self.mode = "immediate" def writemsg(self,msg): if self.mode == "immediate": print msg else: self.msg_list.append(msg) def error(self,s): self.writemsg("ERROR: %s" % s) def warning(self,s): self.writemsg("WARNING: %s" % s) def info(self,s): self.writemsg("INFO: %s" % s) def common_err(s): err_buf.error(s) def common_warn(s): err_buf.warning(s) def common_info(s): err_buf.info(s) def no_prog_err(name): err_buf.error("%s not available, check your installation"%name) def missing_prog_warn(name): err_buf.warning("could not find any %s on the system"%name) def no_attribute_err(attr,obj_type): err_buf.error("required attribute %s not found in %s"%(attr,obj_type)) def bad_def_err(what,msg): err_buf.error("bad %s definition: %s"%(what,msg)) def unsupported_err(name): err_buf.error("%s is not supported"%name) def no_such_obj_err(name): err_buf.error("%s object is not supported"%name) def obj_cli_err(name): err_buf.error("object %s cannot be represented in the CLI notation"%name) def missing_obj_err(node): err_buf.error("object %s:%s missing (shouldn't have happened)"% \ (node.tagName,node.getAttribute("id"))) def constraint_norefobj_err(constraint_id,obj_id): err_buf.error("constraint %s references a resource %s which doesn't exist"% \ (constraint_id,obj_id)) def obj_exists_err(name): err_buf.error("object %s already exists"%name) def no_object_err(name): err_buf.error("object %s does not exist"%name) def invalid_id_err(obj_id): err_buf.error("%s: invalid object id"%obj_id) def id_used_err(node_id): err_buf.error("%s: id is already in use"%node_id) def skill_err(s): err_buf.error("%s: this command is not allowed at this skill level"%' '.join(s)) def syntax_err(s,token = '',context = ''): pfx = "syntax" if context: pfx = "%s in %s" %(pfx,context) if type(s) == type(''): err_buf.error("%s near <%s>"%(pfx,s)) elif token: err_buf.error("%s near <%s>: %s"%(pfx,token,' '.join(s))) else: err_buf.error("%s: %s"%(pfx,' '.join(s))) def bad_attr_usage(cmd,args): err_buf.error("bad usage: %s %s"%(cmd,args)) def cib_parse_err(msg): err_buf.error("%s"%msg) def cib_no_elem_err(el_name): err_buf.error("CIB contains no '%s' element!"%el_name) def cib_ver_unsupported_err(validator,rel): err_buf.error("CIB not supported: validator '%s', release '%s'"% (validator,rel)) err_buf.error("You may try the upgrade command") def update_err(obj_id,cibadm_opt,node): if cibadm_opt == '-C': task = "create" elif cibadm_opt == '-D': task = "delete" else: task = "update" err_buf.error("could not %s %s"%(task,obj_id)) err_buf.info("offending xml: %s" % node.toprettyxml()) def not_impl_info(s): err_buf.info("%s is not implemented yet" % s) def ask(msg): ans = raw_input(msg + ' ') if not ans: return False return ans[0].lower() == 'y' from UserDict import DictMixin class odict(DictMixin): def __init__(self, data=None, **kwdata): self._keys = [] self._data = {} def __setitem__(self, key, value): if key not in self._data: self._keys.append(key) self._data[key] = value def __getitem__(self, key): return self._data[key] def __delitem__(self, key): del self._data[key] self._keys.remove(key) def keys(self): return list(self._keys) def copy(self): copyDict = odict() copyDict._data = self._data.copy() copyDict._keys = self._keys[:] return copyDict def cmd_end(cmd): "Go up one level." levels.droplevel() def cmd_exit(cmd): "Quit" cmd_end(cmd) if interactive: print "bye" try: readline.write_history_file(hist_file) except: pass for f in tmpfiles: os.unlink(f) sys.exit() def dump_short_desc(help_tab): for topic in help_tab: if topic == '.': continue shortdesc = help_tab[topic][0] # with odict, for whatever reason, python parses differently: # help_tab["..."] = ("...","...") and # help_tab["..."] = ("...",""" # ...""") # a parser bug? if type(help_tab[topic][0]) == type(()): shortdesc = help_tab[topic][0][0] print "\t",topic.ljust(16),shortdesc def cmd_help(help_tab,topic = ''): "help!" # help_tab is a dict: topic: (short_desc,long_desc) # '.' is a special entry for the top level if not topic: print "" print help_tab['.'][1] print "" print "Available commands:" print "" dump_short_desc(help_tab) print "" return if topic not in help_tab: print "There is no help for topic %s" % topic return if type(help_tab[topic][0]) == type(()): print help_tab[topic][0][1] else: print help_tab[topic][1] def add_sudo(cmd): if user_prefs.crm_user: return "sudo -E -u %s %s"%(user_prefs.crm_user,cmd) return cmd def pipe_string(cmd,s): cmd = add_sudo(cmd) try: p = os.popen(cmd,'w') p.write(s) return p.close() except IOError, msg: common_err(msg) return -1 def xml2doc(cmd): cmd = add_sudo(cmd) try: p = os.popen(cmd,'r') except IOError, msg: common_err(msg) return None try: doc = xml.dom.minidom.parse(p) except xml.parsers.expat.ExpatError,msg: common_err("cannot parse output of %s: %s"%(cmd,msg)) p.close() return None p.close() return doc #def pipe_string(cmd,s): # 'Run a program, collect and return stdout.' # if user_prefs.crm_user: # p = Popen3("sudo -E -u %s %s"%(user_prefs.crm_user,cmd), None) # else: # p = Popen3(cmd, None) # p.fromchild.close() # p.tochild.write(s) # p.tochild.close() # p.wait() def str2tmp(s): ''' Write the given string to a temporary file. Return the name of the file. ''' fd,tmp = mkstemp() try: f = os.fdopen(fd,"w") except IOError, msg: common_err(msg) return f.write(s) f.close() return tmp def ext_cmd(cmd): if os.system(add_sudo(cmd)) != 0: return False else: return True def is_program(prog): return os.system("which %s >/dev/null 2>&1"%prog) == 0 def find_program(envvar,*args): if envvar and os.getenv(envvar): return os.getenv(envvar) for prog in args: if is_program(prog): return prog def is_id_valid(id): """ Verify that the id follows the definition: http://www.w3.org/TR/1999/REC-xml-names-19990114/#ns-qualnames """ if not id: return False id_re = "^[A-Za-z_][\w._-]*$" return re.match(id_re,id) def check_filename(fname): """ Verify that the string is a filename. """ fname_re = "^[^/]+$" return re.match(fname_re,id) class UserPrefs(object): ''' Keep user preferences here. ''' def __init__(self): self.skill_level = 2 #TODO: set back to 0? self.editor = find_program("EDITOR","vim","vi","emacs","nano") self.pager = find_program("PAGER","less","more","pg") self.dotty = find_program("","dotty") if not self.editor: missing_prog_warn("editor") if not self.pager: missing_prog_warn("pager") self.crm_user = "" self.xmlindent = " " # two spaces def check_skill_level(self,n): return self.skill_level >= n class CliOptions(object): ''' Manage user preferences ''' skill_levels = {"operator":0, "administrator":1, "expert":2} help_table = odict() help_table["."] = ("user preferences","Various user preferences may be set here.") help_table["skill-level"] = ("set skill level", "") help_table["editor"] = ("set prefered editor program", "") help_table["pager"] = ("set prefered pager program", "") help_table["user"] = ("set the cluster user", """ If you need extra privileges to talk to the cluster (i.e. the cib process), then set this to user. Typically, that is either "root" or "hacluster". Don't forget to setup the sudoers file as well. Example: user hacluster """) help_table["help"] = ("show help", "") help_table["end"] = ("go back one level", "") def __init__(self): self.cmd_table = { "skill-level": (self.set_skill_level,(1,1),0,(skills_list,)), "editor": (self.set_editor,(1,1),0), "pager": (self.set_pager,(1,1),0), "user": (self.set_crm_user,(0,1),0), "save": (self.save_options,(0,0),0), "show": (self.show_options,(0,0),0), "help": (self.help,(0,1),0), "quit": (cmd_exit,(0,0),0), "end": (cmd_end,(0,0),0), } def set_skill_level(self,cmd,skill_level): """usage: skill-level level: operator | administrator | expert""" if skill_level in self.skill_levels: user_prefs.skill_level = self.skill_levels[skill_level] else: common_err("no %s skill level"%skill_level) return False def get_skill_level(self): for s in self.skill_levels: if user_prefs.skill_level == self.skill_levels[s]: return s def set_editor(self,cmd,prog): "usage: editor " if is_program(prog): user_prefs.editor = prog else: common_err("program %s does not exist"% prog) return False def set_pager(self,cmd,prog): "usage: pager " if is_program(prog): user_prefs.pager = prog else: common_err("program %s does not exist"% prog) return False def set_crm_user(self,cmd,user = ''): "usage: user []" user_prefs.crm_user = user def write_rc(self,f): print >>f, '%s "%s"' % ("editor",user_prefs.editor) print >>f, '%s "%s"' % ("pager",user_prefs.pager) print >>f, '%s "%s"' % ("user",user_prefs.crm_user) print >>f, '%s "%s"' % ("skill-level",self.get_skill_level()) def show_options(self,cmd): "usage: show" self.write_rc(sys.stdout) def save_options(self,cmd): "usage: save" try: f = open(rc_file,"w") except os.error,msg: common_err("open: %s"%msg) return print >>f, 'options' self.write_rc(f) print >>f, 'end' f.close() def help(self,cmd,topic = ''): "usage: help []" cmd_help(self.help_table,topic) cib_dump = "cibadmin -Ql" cib_piped = "cibadmin -p" cib_upgrade = "cibadmin --upgrade --force" cib_verify = "crm_verify -V -p" class WCache(object): "Cache stuff. A naive implementation." def __init__(self): self.lists = {} self.stamp = time.time() self.max_cache_age = 60 # seconds def is_cached(self,name): if time.time() - self.stamp > self.max_cache_age: self.stamp = time.time() self.clear() return name in self.lists def store(self,name,lst): self.lists[name] = lst return lst def retrieve(self,name): if self.is_cached(name): return self.lists[name] else: return None def clear(self): self.lists = {} class CibShadow(object): ''' CIB shadow management class ''' help_table = odict() help_table["."] = ("",""" CIB shadow management. See the crm_shadow program. """) help_table["new"] = ("create a new shadow CIB", "") help_table["delete"] = ("delete a shadow CIB", "") help_table["reset"] = ("copy live cib to a shadow CIB", "") help_table["commit"] = ("copy a shadow CIB to the cluster", "") help_table["use"] = ("change working CIB", ''' Choose a shadow CIB for further changes. If the name provided is empty, then the live (cluster) CIB is used. ''') help_table["diff"] = ("diff between the shadow CIB and the live CIB", "") help_table["list"] = ("list all shadow CIBs", "") help_table["quit"] = ("exit the program", "") help_table["help"] = ("show help", "") help_table["end"] = ("go back one level", "") envvar = "CIB_shadow" extcmd = ">/dev/null &1" % self.extcmd) except os.error: no_prog_err(self.extcmd) return False return True def new(self,cmd,name,force = ''): "usage: new [force]" new_cmd = "%s -c '%s'" % (self.extcmd,name) if force: if force == "force" or force == "--force": new_cmd = "%s --force" % new_cmd else: syntax_err((new_cmd,force), context = 'new') return False if ext_cmd(new_cmd): common_info("%s shadow CIB created"%name) self.use("use",name) def delete(self,cmd,name): "usage: delete " if cib_in_use == name: common_err("%s shadow CIB is in use"%name) return False if ext_cmd("%s -D '%s' --force" % (self.extcmd,name)): common_info("%s shadow CIB deleted"%name) else: common_err("failed to delete %s shadow CIB"%name) return False def reset(self,cmd,name): "usage: reset " if ext_cmd("%s -r '%s'" % (self.extcmd,name)): common_info("copied live CIB to %s"%name) else: common_err("failed to copy live CIB to %s"%name) return False def commit(self,cmd,name): "usage: commit " if ext_cmd("%s -C '%s' --force" % (self.extcmd,name)): common_info("commited '%s' shadow CIB to the cluster"%name) else: common_err("failed to commit the %s shadow CIB"%name) return False def diff(self,cmd): "usage: diff" return ext_cmd("%s -d" % self.extcmd) def list(self,cmd): "usage: list" return ext_cmd("ls @HA_VARLIBDIR@/heartbeat/crm | fgrep shadow. | sed 's/^shadow\.//'") def use(self,cmd,name = ''): "usage: use []" # Choose a shadow cib for further changes. If the name # provided is empty, then choose the live (cluster) cib. # FIXME: should we check name's sanity? global cib_in_use if not name or name == "live": name = "" os.unsetenv(self.envvar) else: if not ext_cmd("test -r '@HA_VARLIBDIR@/heartbeat/crm/shadow.%s'"%name): common_err("%s: no such shadow CIB"%name) return False os.putenv(self.envvar,name) cib_in_use = name def help(self,cmd,topic = ''): cmd_help(self.help_table,topic) def manage_attr(cmd,attr_ext_commands,*args): if len(args) < 3: bad_attr_usage(cmd,' '.join(args)) return False attr_cmd = None try: attr_cmd = attr_ext_commands[args[1]] except KeyError: bad_attr_usage(cmd,' '.join(args)) return False if not attr_cmd: bad_attr_usage(cmd,' '.join(args)) return False if args[1] == 'set': if len(args) == 4: return ext_cmd(attr_cmd%(args[0],args[2],args[3])) else: bad_attr_usage(cmd,' '.join(args)) return False elif args[1] in ('delete','show'): if len(args) == 3: return ext_cmd(attr_cmd%(args[0],args[2])) else: bad_attr_usage(cmd,' '.join(args)) return False else: bad_attr_usage(cmd,' '.join(args)) return False def is_rsc_running(id): if not id: return False proc = subprocess.Popen(RscMgmt.rsc_status % id, \ shell=True, stdout=subprocess.PIPE) outp = proc.communicate()[0] return outp.find("running") > 0 and outp.find("NOT") == -1 def is_process(s): proc = subprocess.Popen("ps -e -o pid,command | grep -qs '%s'" % s, \ shell=True, stdout=subprocess.PIPE) proc.wait() return proc.returncode == 0 def cluster_stack(): if is_process("heartbeat:.[m]aster"): return "heartbeat" elif is_process("[a]isexec"): return "openais" return "" class RscMgmt(object): ''' Resources management class ''' rsc_status_all = "crm_resource -L" rsc_status = "crm_resource -W -r '%s'" rsc_startstop = "crm_resource --meta -r '%s' -p target-role -v '%s'" rsc_manage = "crm_resource --meta -r '%s' -p is-managed -v '%s'" rsc_migrate = "crm_resource -M -r '%s'" rsc_migrateto = "crm_resource -M -r '%s' -H '%s'" rsc_unmigrate = "crm_resource -U -r '%s'" rsc_cleanup = "crm_resource -C -r '%s' -H '%s'" rsc_param = { 'set': "crm_resource -r '%s' -p '%s' -v '%s'", 'delete': "crm_resource -r '%s' -d '%s'", 'show': "crm_resource -r '%s' -g '%s'", } rsc_meta = { 'set': "crm_resource --meta -r '%s' -p '%s' -v '%s'", 'delete': "crm_resource --meta -r '%s' -d '%s'", 'show': "crm_resource --meta -r '%s' -g '%s'", } rsc_failcount = { 'set': "crm_failcount -r '%s' -U '%s' -v '%s'", 'delete': "crm_failcount -r '%s' -U '%s' -D", 'show': "crm_failcount -r '%s' -U '%s' -G", } rsc_refresh = "crm_resource -R" rsc_refresh_node = "crm_resource -R -H '%s'" rsc_reprobe = "crm_resource -P" rsc_reprobe_node = "crm_resource -P -H '%s'" help_table = odict() help_table["."] = ("","Resource management.") help_table["status"] = ("show status of resources", "") help_table["start"] = ("start a resource", "") help_table["stop"] = ("stop a resource", "") help_table["manage"] = ("put a resource into managed mode", "") help_table["unmanage"] = ("put a resource into unmanaged mode", "") help_table["migrate"] = ("migrate a resource to another node", "") help_table["unmigrate"] = ("migrate a resource to its prefered node", "") help_table["param"] = ("manage a parameter of a resource",""" Manage or display a parameter of a resource (also known as an instance_attribute). Usage: param set param delete param show Example: param ip_0 show ip """) help_table["meta"] = ("manage a meta attribute",""" Show/edit/delete a meta attribute of a resource. Currently, all meta attributes of a resource may be managed with other commands such as 'resource stop'. Usage: meta set meta delete meta show Example: meta ip_0 set target-role stopped """) help_table["failcount"] = ("manage failcounts", """ Show/edit/delete the failcount of a resource. Usage: failcount set failcount delete failcount show Example: failcount fs_0 delete node2 """) help_table["cleanup"] = ("cleanup resource status","") help_table["refresh"] = ("refresh CIB from the LRM status","") help_table["reprobe"] = ("probe for resources not started by the CRM","") help_table["quit"] = ("exit the program", "") help_table["help"] = ("show help", "") help_table["end"] = ("go back one level", "") def __init__(self): self.cmd_table = { "status": (self.status,(0,1),0,(rsc_list,)), "start": (self.start,(1,1),0,(rsc_list,)), "stop": (self.stop,(1,1),0,(rsc_list,)), "manage": (self.manage,(1,1),0,(rsc_list,)), "unmanage": (self.unmanage,(1,1),0,(rsc_list,)), "migrate": (self.migrate,(1,2),0,(rsc_list,listnodes)), "unmigrate": (self.unmigrate,(1,1),0,(rsc_list,)), "param": (self.param,(3,4),1,(rsc_list,attr_cmds)), "meta": (self.meta,(3,4),1,(rsc_list,attr_cmds)), "failcount": (self.failcount,(3,4),0,(rsc_list,attr_cmds,listnodes)), "cleanup": (self.cleanup,(1,2),1,(rsc_list,listnodes)), "refresh": (self.refresh,(0,1),0,(listnodes,)), "reprobe": (self.reprobe,(0,1),0,(listnodes,)), "help": (self.help,(0,1),0), "quit": (cmd_exit,(0,0),0), "end": (cmd_end,(0,0),0), } def status(self,cmd,rsc = None): "usage: status []" if rsc: return ext_cmd(self.rsc_status % rsc) else: return ext_cmd(self.rsc_status_all) def start(self,cmd,rsc): "usage: start " return ext_cmd(self.rsc_startstop%(rsc,"Started")) def stop(self,cmd,rsc): "usage: stop " return ext_cmd(self.rsc_startstop%(rsc,"Stopped")) def manage(self,cmd,rsc): "usage: manage " return ext_cmd(self.rsc_manage%(rsc,"true")) def unmanage(self,cmd,rsc): "usage: unmanage " return ext_cmd(self.rsc_manage%(rsc,"false")) def migrate(self,cmd,*args): """usage: migrate []""" if len(args) == 1: return ext_cmd(self.rsc_migrate%args[0]) else: return ext_cmd(self.rsc_migrateto%(args[0],args[1])) def unmigrate(self,cmd,rsc): "usage: unmigrate " return ext_cmd(self.rsc_unmigrate%rsc) def cleanup(self,cmd,*args): "usage: cleanup " # Cleanup a resource on a node. Omit node to cleanup on # all live nodes. if len(args) == 2: # remove return ext_cmd(self.rsc_cleanup%(args[0],args[1])) else: rv = True for n in listnodes(): if not ext_cmd(self.rsc_cleanup%(args[0],n)): rv = False return rv def failcount(self,cmd,*args): """usage: failcount set failcount delete failcount show """ d = lambda: manage_attr(cmd,self.rsc_failcount,*args) return d() def param(self,cmd,*args): """usage: param set param delete param show """ d = lambda: manage_attr(cmd,self.rsc_param,*args) return d() def meta(self,cmd,*args): """usage: meta set meta delete meta show """ d = lambda: manage_attr(cmd,self.rsc_meta,*args) return d() def refresh(self,cmd,*args): 'usage: refresh []' if len(args) == 1: return ext_cmd(self.rsc_refresh_node%args[0]) else: return ext_cmd(self.rsc_refresh) def reprobe(self,cmd,*args): 'usage: reprobe []' if len(args) == 1: return ext_cmd(self.rsc_reprobe_node%args[0]) else: return ext_cmd(self.rsc_reprobe) def help(self,cmd,topic = ''): cmd_help(self.help_table,topic) def print_node(uname,id,type,other,inst_attr): """ Try to pretty print a node from the cib. Sth like: uname(id): type attr1: v1 attr2: v2 """ if uname == id: print "%s: %s" % (uname,type) else: print "%s(%s): %s" % (uname,id,type) for a in other: print "\t%s: %s" % (a,other[a]) for a,v in inst_attr: print "\t%s: %s" % (a,v) class NodeMgmt(object): ''' Nodes management class ''' node_standby = "crm_standby -U '%s' -v '%s'" node_delete = "cibadmin -D -o nodes -X ''" hb_delnode = "@hb_libdir@/hb_delnode '%s'" dc = "crmadmin -D" node_attr = { 'set': "crm_attribute -t nodes -U '%s' -n '%s' -v '%s'", 'delete': "crm_attribute -D -t nodes -U '%s' -n '%s'", 'show': "crm_attribute -G -t nodes -U '%s' -n '%s'", } node_status = { 'set': "crm_attribute -t status -U '%s' -n '%s' -v '%s'", 'delete': "crm_attribute -D -t status -U '%s' -n '%s'", 'show': "crm_attribute -G -t status -U '%s' -n '%s'", } help_table = odict() help_table["."] = ("","Nodes management.") help_table["show"] = ("show node", "") help_table["standby"] = ("put node into standby", "") help_table["online"] = ("bring node online", "") help_table["delete"] = ("delete node", "") help_table["attribute"] = ("manage attributes", """ Edit node attributes. This kind of attribute should refer to relatively static properties, such as memory size. Usage: attribute set attribute delete attribute show Example: attribute node_1 set memory_size 4096 """) help_table["status-attr"] = ("manage status attributes", """ Edit node attributes which are in the CIB status section, i.e. attributes which hold properties of a more volatile nature. One typical example is attribute generated by the 'pingd' utility. Usage: ............... status-attr set status-attr delete status-attr show ............... Example: ............... status-attr node_1 show pingd """) help_table["quit"] = ("exit the program", "") help_table["help"] = ("show help", "") help_table["end"] = ("go back one level", "") def __init__(self): self.cmd_table = { "status": (self.status,(0,1),0,(listnodes,)), "show": (self.show,(0,1),0,(listnodes,)), "standby": (self.standby,(1,1),0,(listnodes,)), "online": (self.online,(1,1),0,(listnodes,)), "delete": (self.delete,(1,1),0,(listnodes,)), "attribute": (self.attribute,(3,4),0,(listnodes,attr_cmds)), "status-attr": (self.status_attr,(3,4),0,(listnodes,attr_cmds)), "help": (self.help,(0,1),0), "quit": (cmd_exit,(0,0),0), "end": (cmd_end,(0,0),0), } def status(self,cmd,node = None): 'usage: status []' return ext_cmd("%s -o nodes"%cib_dump) def show(self,cmd,node = None): 'usage: show []' doc = xml2doc("%s -o nodes"%cib_dump) if not doc: return False nodes_node = get_cib_elem(doc, "nodes") if not nodes_node: return False for c in nodes_node.childNodes: if not is_element(c) or c.tagName != "node": continue if node and c.getAttribute("uname") != node: continue type = uname = id = "" other = inst_attr = [] for attr in c.attributes.keys(): v = c.getAttribute(attr) if attr == "type": type = v elif attr == "uname": uname = v elif attr == "id": id = v else: other[attr] = v for c2 in c.childNodes: if not is_element(c2): continue if c2.tagName == "instance_attributes": inst_attr = nvpairs2list(c2) print_node(uname,id,type,other,inst_attr) def standby(self,cmd,node): 'usage: standby ' return ext_cmd(self.node_standby%(node,"on")) def online(self,cmd,node): 'usage: online ' return ext_cmd(self.node_standby%(node,"off")) def delete(self,cmd,node): 'usage: delete ' rv = True if cluster_stack() == "heartbeat": rv = ext_cmd(self.hb_delnode%node) if rv: rv = ext_cmd(self.node_delete%node) return rv def attribute(self,cmd,*args): """usage: - attribute set - attribute delete - attribute show """ + attribute set + attribute delete + attribute show """ d = lambda: manage_attr(cmd,self.node_attr,*args) return d() def status_attr(self,cmd,*args): """usage: - status-attr set - status-attr delete - status-attr show """ + status-attr set + status-attr delete + status-attr show """ d = lambda: manage_attr(cmd,self.node_status,*args) return d() def help(self,cmd,topic = ''): cmd_help(self.help_table,topic) def edit_file(fname): 'Edit a file.' if not fname: return if not user_prefs.editor: return return os.system("%s %s" % (user_prefs.editor,fname)) def page_string(s): 'Write string through a pager.' if not s: return if not user_prefs.pager or not interactive: print s else: pipe_string(user_prefs.pager,s) def lines2cli(s): ''' Convert a string into a list of lines. Replace continuation characters. Strip white space, left and right. Drop empty lines. ''' cl = [] l = s.split('\n') cum = [] for p in l: p = p.strip() if p.endswith('\\'): p = p.rstrip('\\') cum.append(p) else: cum.append(p) cl.append(''.join(cum).strip()) cum = [] if cum: # in case s ends with backslash cl.append(''.join(cum)) return [x for x in cl if x] class CibConfig(object): ''' The configuration class ''' help_table = odict() help_table["."] = ("","CIB configuration.") help_table["verify"] = ("verify the CIB before commit", "Verify the CIB (before commit)") help_table["erase"] = ("erase the CIB", "Erase the CIB (careful!).") help_table["ptest"] = ("show cluster actions if changes were committed", """ Show PE (policy engine) motions using ptest. A CIB is constructed using the current user edited version and the status from the current CIB. This CIB is run through ptest to show changes. If you have graphviz installed and X11 session, dotty is run to display the changes graphically. """) help_table["refresh"] = ("refresh from CIB", """ Load the CIB from scratch. All changes are lost. The user is asked for confirmation beforehand """) help_table["show"] = ("display CIB objects", """ The `show` command displays objects. It may display all objects or a set of objects. Specify 'changed' to see what changed. Usage: ............... show [xml] [ ...] show [xml] changed ............... """) help_table["edit"] = ("edit CIB objects", """ This command invokes the editor with the object description. As with the `show` command, the user may choose to edit all objects or a set of objects. If the user insists, he or she may edit the XML edition of the object. Usage: ............... edit [xml] [ ...] edit [xml] changed ............... """) help_table["delete"] = ("delete CIB objects", """ The user may delete one or more objects by specifying a list of ids. If the object to be deleted belongs to a container object, such as group, and it is the only resource in that container, then the container is deleted as well. Usage: ............... delete [ ...] ............... """) help_table["rename"] = ("rename a CIB object", """ Rename an object. It is recommended to use this command to rename a resource, because it will take care of updating all related constraints. Changing ids with the edit command won't have the same effect. If you want to rename a resource, it must be stopped. Usage: ............... rename ............... """) help_table["save"] = ("save the CIB to a file", """ Save the configuration to a file. Optionally, as XML. Usage: ............... save [xml] ............... Example: ............... save myfirstcib.txt ............... """) help_table["load"] = ("import the CIB from a file", """ Load a part of configuration (or all of it) from a local file or a network URL. The `replace` method replaces the current configuration with the one from the source. The `update` tries to import the contents into the current configuration. The file may be a CLI file or an XML file. Usage: ............... load [xml] method URL method :: replace | update ............... Example: ............... load xml replace myfirstcib.xml load xml replace http://storage.big.com/cibs/bigcib.xml ............... """) help_table["template"] = ("edit and import a configuration from a template", """ The specified template is loaded into the editor. It's up to the user to make a good CRM configuration out of it. Usage: ............... template [xml] url ............... Example: ............... template two-apaches.txt ............... """) help_table["enter"] = ("enter the interactive configuration mode", """ Those who prefer more typing, or in case the definition of a resource is rather long, the 'enter' command offers configuration in small steps. Usage: ............... enter ............... Example: ............... enter primitive ip_1 ............... """) help_table["commit"] = ("commit the changes to the CIB", """ The changes at the configure level are not immediately applied to the CIB, but by this command or on exiting the configure level. Sometimes, the program will refuse to apply the changes, usually for good reason. If you know what you're doing, you may say 'commit force' to force the changes. """) help_table["upgrade"] = ("upgrade the CIB to version 1.0", """ If you get the "CIB not supported" error, which typically means that the current CIB version is coming from the older release, you may try to upgrade it to the latest revision. The command used is: cibadmin --upgrade --force If we don't recognize the current CIB as the old one, but you're sure that it is, you may force the command. Usage: ............... upgrade [force] ............... """) help_table["primitive"] = ("define a resource", """ The primitive command describes a resource. Usage: ............... primitive [:[:]] [params = [=...]] [meta = [=...]] [operations id_spec [op op_type [=...] ...]] id_spec :: $id= | $id-ref= op_type :: start | stop | monitor ............... Example: ............... primitive apcfence stonith:apcsmart \\ params ttydev=/dev/ttyS0 hostlist="node1 node2" \\ op start timeout=60s \\ op monitor interval=30m timeout=60s primitive www8 apache \\ params configfile=/etc/apache/www8.conf \\ operations $id-ref=apache_ops ............... """) help_table["group"] = ("define a group", """ The `group` command creates a group of resources. Usage: ............... group [...] [params = [=...]] [meta = [=...]] ............... Example: ............... group internal_www disk0 fs0 internal_ip apache \\ meta target-role=stopped ............... """) help_table["clone"] = ("define a clone", """ The `clone` command creates a resource clone. It may contain a single primitive resource or one group of resources. Usage: ............... clone [params = [=...]] [meta = [=...]] ............... Example: ............... clone cl_fence apc_1 \\ meta clone-node-max=1 globally-unique=false ............... """) help_table["ms"] = ("define a master-slave resource", """ The `ms` command creates a master/slave resource type. It may contain a single primitive resource or one group of resources. Usage: ............... ms [params = [=...]] [meta = [=...]] ............... Example: ............... ms disk1 drbd1 \\ meta notify=true globally-unique=false ............... """) help_table["location"] = ("a location preference", """ `location` defines the preference of nodes for the given resource. The location constraints consist of one or more rules which specify a score to be awarded if the rule matches. Usage: ............... location {node_pref|rules} node_pref :: : rules :: rule [id_spec] [$role=] : [rule [id_spec] [$role=] : ...] id_spec :: $id= | $id-ref= score :: | | [-]inf expression :: [bool_op ...] | bool_op :: or | and single_exp :: [type:] | type :: string | version | number binary_op :: lt | gt | lte | gte | eq | ne unary_op :: defined | not_defined date_expr :: date_op [] (TBD) ............... Examples: ............... location conn_1 internal_www 100: node1 location conn_1 internal_www \\ rule 100: #uname eq node1 \\ rule pingd: defined pingd location conn_2 dummy_float \\ rule -inf: not_defined pingd or pingd lte 0 ............... """) help_table["colocation"] = ("colocate resources", """ This constraint expresses the placement relation between two resources. Usage: ............... colocation : [:] [:] ............... Example: ............... colocation dummy_and_apache -inf: apache dummy ............... """) help_table["order"] = ("order resources", """ This constraint expresses the order of actions on two resources. Usage: ............... order score-type: [:] [:] [symmetrical=] score-type :: advisory | mandatory | ............... Example: ............... order c_apache_1 mandatory: apache:start ip_1 ............... """) help_table["property"] = ("set a cluster property", """ Set the cluster (`crm_config`) options. Usage: ............... property [$id=]