diff --git a/shell/modules/cibconfig.py b/shell/modules/cibconfig.py index 3f5f0f1e05..25daf41412 100644 --- a/shell/modules/cibconfig.py +++ b/shell/modules/cibconfig.py @@ -1,2241 +1,2269 @@ # 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 sys import subprocess import copy import xml.dom.minidom import re from singletonmixin import Singleton from userprefs import Options, UserPrefs from vars import Vars from cliformat import * from utils import * from xmlutil import * from msg import * from parse import CliParser from clidisplay import CliDisplay from cibstatus import CibStatus from idmgmt import IdMgmt def show_unrecognized_elems(doc): try: conf = doc.getElementsByTagName("configuration")[0] except: common_warn("CIB has no configuration element") return for topnode in conf.childNodes: if not is_element(topnode): continue if is_defaults(topnode): continue if not topnode.tagName in cib_topnodes: common_warn("unrecognized CIB element %s" % c.tagName) continue for c in topnode.childNodes: if not is_element(c): continue if not c.tagName in cib_object_map: common_warn("unrecognized CIB element %s" % c.tagName) # # object sets (enables operations on sets of elements) # def mkset_obj(*args): if args and args[0] == "xml": obj = lambda: CibObjectSetRaw(*args[1:]) else: obj = lambda: CibObjectSetCli(*args) return obj() class CibObjectSet(object): ''' Edit or display a set of cib objects. repr() for objects representation and save() used to store objects into internal structures are defined in subclasses. ''' def __init__(self, *args): self.obj_list = [] def _open_url(self,src): import urllib try: return urllib.urlopen(src) except: pass if src == "-": return sys.stdin try: return open(src) except: pass common_err("could not open %s" % src) return False def init_aux_lists(self): ''' Before edit, initialize two auxiliary lists which will hold a list of objects to be removed and a list of objects which were created. Then, we can create a new object list which will match the current state of affairs, i.e. the object set after the last edit. ''' self.remove_objs = copy.copy(self.obj_list) self.add_objs = [] def recreate_obj_list(self): ''' Recreate obj_list: remove deleted objects and add created objects ''' for obj in self.remove_objs: self.obj_list.remove(obj) self.obj_list += self.add_objs rmlist = [] for obj in self.obj_list: if obj.invalid: rmlist.append(obj) for obj in rmlist: self.obj_list.remove(obj) def edit_save(self,s,erase = False): ''' Save string s to a tmp file. Invoke editor to edit it. Parse/save the resulting file. In case of syntax error, allow user to reedit. If erase is True, erase the CIB first. If no changes are done, return silently. ''' tmp = str2tmp(s) if not tmp: return False filehash = hash(s) rc = False while True: if edit_file(tmp) != 0: break try: f = open(tmp,'r') except IOError, msg: common_err(msg) break s = ''.join(f) f.close() if hash(s) == filehash: # file unchanged rc = True break if erase: cib_factory.erase() if not self.save(s): if ask("Do you want to edit again?"): continue rc = True break try: os.unlink(tmp) except: pass return rc def edit(self): if options.batch: common_info("edit not allowed in batch mode") return False cli_display.set_no_pretty() s = self.repr() cli_display.reset_no_pretty() return self.edit_save(s) def save_to_file(self,fname): if fname == "-": f = sys.stdout else: if not options.batch and os.access(fname,os.F_OK): if not ask("File %s exists. Do you want to overwrite it?"%fname): return False try: f = open(fname,"w") except IOError, msg: common_err(msg) return False rc = True cli_display.set_no_pretty() s = self.repr() cli_display.reset_no_pretty() if s: f.write(s) f.write('\n') elif self.obj_list: rc = False if f != sys.stdout: f.close() return rc def show(self): s = self.repr() if not s: if self.obj_list: # objects could not be displayed return False else: return True page_string(s) def import_file(self,method,fname): if not cib_factory.is_cib_sane(): return False if method == "replace": if options.interactive and cib_factory.has_cib_changed(): if not ask("This operation will erase all changes. Do you want to proceed?"): return False cib_factory.erase() f = self._open_url(fname) if not f: return False s = ''.join(f) if f != sys.stdin: f.close() return self.save(s) def repr(self): ''' Return a string with objects's representations (either CLI or XML). ''' return '' def save(self,s): ''' For each object: - try to find a corresponding object in obj_list - if not found: create new - if found: replace the object in the obj_list with the new object See below for specific implementations. ''' pass def verify2(self): ''' Test objects for sanity. This is about semantics. ''' rc = 0 for obj in self.obj_list: rc |= obj.check_sanity() return rc def lookup_cli(self,cli_list): for obj in self.obj_list: if obj.matchcli(cli_list): return obj def lookup(self,xml_obj_type,obj_id): for obj in self.obj_list: if obj.match(xml_obj_type,obj_id): return obj def drop_remaining(self): 'Any remaining objects in obj_list are deleted.' l = [x.obj_id for x in self.remove_objs] return cib_factory.delete(*l) def get_comments(cli_list): if not cli_list: return [] last = cli_list[len(cli_list)-1] try: if last[0] == "comments": cli_list.pop() return last[1] except: pass return [] class CibObjectSetCli(CibObjectSet): ''' Edit or display a set of cib objects (using cli notation). ''' def __init__(self, *args): CibObjectSet.__init__(self, *args) self.obj_list = cib_factory.mkobj_list("cli",*args) def repr(self): "Return a string containing cli format of all objects." if not self.obj_list: return '' return '\n'.join(obj.repr_cli() \ for obj in processing_sort_cli(self.obj_list)) def process(self,cli_list): ''' Create new objects or update existing ones. ''' comments = get_comments(cli_list) obj = self.lookup_cli(cli_list) if obj: rc = obj.update_from_cli(cli_list) != False self.remove_objs.remove(obj) else: obj = cib_factory.create_from_cli(cli_list) rc = obj != None if rc: self.add_objs.append(obj) if rc: obj.set_comment(comments) return rc def save(self,s): ''' Save a user supplied cli format configuration. On errors user is typically asked to review the configuration (for instance on editting). On syntax error (return code 1), no changes are done, but on semantic errors (return code 2), some changes did take place so object list must be updated properly. Finally, once syntax check passed, there's no way back, all changes are applied to the current configuration. TODO: Implement undo configuration changes. ''' l = [] rc = True err_buf.start_tmp_lineno() cp = CliParser() for cli_text in lines2cli(s): err_buf.incr_lineno() cli_list = cp.parse(cli_text) if cli_list: l.append(cli_list) elif cli_list == False: rc = False err_buf.stop_tmp_lineno() # we can't proceed if there was a syntax error, but we # can ask the user to fix problems if not rc: return rc self.init_aux_lists() if l: for cli_list in processing_sort_cli(l): if self.process(cli_list) == False: rc = False if not self.drop_remaining(): # this is tricky, we don't know what was removed! # it could happen that the user dropped a resource # which was running and therefore couldn't be removed rc = False self.recreate_obj_list() return rc cib_verify = "crm_verify -V -p" class CibObjectSetRaw(CibObjectSet): ''' Edit or display one or more CIB objects (XML). ''' def __init__(self, *args): CibObjectSet.__init__(self, *args) self.obj_list = cib_factory.mkobj_list("xml",*args) def repr(self): "Return a string containing xml of all objects." doc = cib_factory.objlist2doc(self.obj_list) s = doc.toprettyxml(user_prefs.xmlindent) doc.unlink() return s def repr_configure(self): ''' Return a string containing xml of configure and its children. ''' doc = cib_factory.objlist2doc(self.obj_list) conf_node = doc.getElementsByTagName("configuration")[0] s = conf_node.toprettyxml(user_prefs.xmlindent) doc.unlink() return s def process(self,node): if not cib_factory.is_cib_sane(): return False obj = self.lookup(node.tagName,node.getAttribute("id")) if obj: rc = obj.update_from_node(node) self.remove_objs.remove(obj) else: new_obj = cib_factory.create_from_node(node) rc = new_obj != None if rc: self.add_objs.append(new_obj) return rc def save(self,s): try: doc = xml.dom.minidom.parseString(s) except xml.parsers.expat.ExpatError,msg: cib_parse_err(msg,s) return False rc = True sanitize_cib(doc) show_unrecognized_elems(doc) newnodes = get_interesting_nodes(doc,[]) self.init_aux_lists() if newnodes: for node in processing_sort(newnodes): if not self.process(node): rc = False if not self.drop_remaining(): rc = False doc.unlink() self.recreate_obj_list() return rc def verify(self): if not self.obj_list: return True cli_display.set_no_pretty() rc = pipe_string(cib_verify,self.repr()) cli_display.reset_no_pretty() return rc in (0,1) def ptest(self, nograph, scores, verbosity): if not cib_factory.is_cib_sane(): return False ptest = "ptest -X -%s" % verbosity.upper() if scores: ptest = "%s -s" % ptest if user_prefs.dotty and not nograph: fd,tmpfile = mkstemp() ptest = "%s -D %s" % (ptest,tmpfile) else: tmpfile = None doc = cib_factory.objlist2doc(self.obj_list) cib = doc.childNodes[0] status = cib_status.get_status() if not status: common_err("no status section found") return False cib.appendChild(doc.importNode(status,1)) pipe_string(ptest,doc.toprettyxml()) doc.unlink() if tmpfile: p = subprocess.Popen("%s %s" % (user_prefs.dotty,tmpfile), shell=True, bufsize=0, stdin=None, stdout=None, stderr=None, close_fds=True) common_info("starting %s to show transition graph"%user_prefs.dotty) vars.tmpfiles.append(tmpfile) else: if not nograph: common_info("install graphviz to see a transition graph") return True # # XML generate utilities # def set_id(node,oldnode,id_hint,id_required = True): ''' Set the id attribute for the node. Procedure: - if the node already contains "id", keep it - if the old node contains "id", copy that - if neither is true, then create a new one using id_hint (exception: if not id_required, then no new id is generated) Finally, save the new id in id_store. ''' old_id = None new_id = node.getAttribute("id") if oldnode and oldnode.getAttribute("id"): old_id = oldnode.getAttribute("id") if not new_id: new_id = old_id if not new_id: if id_required: new_id = id_store.new(node,id_hint) else: id_store.save(new_id) if new_id: node.setAttribute("id",new_id) if oldnode and old_id == new_id: set_id_used_attr(oldnode) def mkxmlsimple(e,oldnode,id_hint): ''' Create an xml node from the (name,dict) pair. The name is the name of the element. The dict contains a set of attributes. ''' node = cib_factory.createElement(e[0]) for n,v in e[1]: if n == "$children": # this one's skipped continue if n == "operation": v = v.lower() if n.startswith('$'): n = n.lstrip('$') if (type(v) != type('') and type(v) != type(u'')) \ or v: # skip empty strings node.setAttribute(n,v) id_ref = node.getAttribute("id-ref") if id_ref: id_ref_2 = cib_factory.resolve_id_ref(e[0],id_ref) node.setAttribute("id-ref",id_ref_2) else: set_id(node,lookup_node(node,oldnode),id_hint) return node def mkxmlnvpairs(e,oldnode,id_hint): ''' Create xml from the (name,dict) pair. The name is the name of the element. The dict contains a set of nvpairs. Stuff such as instance_attributes. NB: Other tags not containing nvpairs are fine if the dict is empty. ''' node = cib_factory.createElement(e[0]) match_node = lookup_node(node,oldnode) #if match_node: #print "found nvpairs set:",match_node.tagName,match_node.getAttribute("id") id_ref = find_value(e[1],"$id-ref") if id_ref: id_ref_2 = cib_factory.resolve_id_ref(e[0],id_ref) node.setAttribute("id-ref",id_ref_2) if e[0] != "operations": return node # id_ref is the only attribute (if not operations) e[1].remove(["$id-ref",id_ref]) v = find_value(e[1],"$id") if v: node.setAttribute("id",v) e[1].remove(["$id",v]) else: if e[0] == "operations": # operations don't need no id set_id(node,match_node,id_hint,id_required = False) else: set_id(node,match_node,id_hint) try: subpfx = vars.subpfx_list[e[0]] except: subpfx = '' subpfx = subpfx and "%s_%s" % (id_hint,subpfx) or id_hint nvpair_pfx = node.getAttribute("id") or subpfx for n,v in e[1]: nvpair = cib_factory.createElement("nvpair") node.appendChild(nvpair) nvpair.setAttribute("name",n) if v != None: nvpair.setAttribute("value",v) set_id(nvpair,lookup_node(nvpair,match_node),nvpair_pfx) return node def mkxmlop(e,oldnode,id_hint): ''' Create an operation xml from the (name,dict) pair. ''' node = cib_factory.createElement(e[0]) inst_attr = [] for n,v in e[1]: if n in olist(vars.req_op_attributes + vars.op_attributes): node.setAttribute(n,v) else: inst_attr.append([n,v]) tmp = cib_factory.createElement("operations") oldops = lookup_node(tmp,oldnode) # first find old operations oldop = lookup_node(node,oldops) set_id(node,oldop,id_hint) if inst_attr: e = ["instance_attributes",inst_attr] nia = mkxmlnvpairs(e,oldop,node.getAttribute("id")) node.appendChild(nia) return node def mkxmldate(e,oldnode,id_hint): ''' Create a date_expression xml from the (name,dict) pair. ''' node = cib_factory.createElement(e[0]) operation = find_value(e[1],"operation").lower() node.setAttribute("operation", operation) old_date = lookup_node(node,oldnode) # first find old date element set_id(node,old_date,id_hint) date_spec_attr = [] for n,v in e[1]: if n in olist(vars.date_ops) or n == "operation": continue elif n in vars.in_range_attrs: node.setAttribute(n,v) else: date_spec_attr.append([n,v]) if not date_spec_attr: return node elem = operation == "date_spec" and "date_spec" or "duration" tmp = cib_factory.createElement(elem) old_date_spec = lookup_node(tmp,old_date) # first find old date element set_id(tmp,old_date_spec,id_hint) for n,v in date_spec_attr: tmp.setAttribute(n,v) node.appendChild(tmp) return node def mkxmlrsc_set(e,oldnode,id_hint): ''' Create a resource_set xml from the (name,dict) pair. ''' node = cib_factory.createElement(e[0]) old_rsc_set = lookup_node(node,oldnode) # first find old date element set_id(node,old_rsc_set,id_hint) for ref in e[1]: if ref[0] == "resource_ref": ref_node = cib_factory.createElement(ref[0]) ref_node.setAttribute(ref[1][0],ref[1][1]) node.appendChild(ref_node) elif ref[0] in ("sequential", "action", "role"): node.setAttribute(ref[0], ref[1]) return node conv_list = { "params": "instance_attributes", "meta": "meta_attributes", "property": "cluster_property_set", "rsc_defaults": "meta_attributes", "op_defaults": "meta_attributes", "attributes": "instance_attributes", "operations": "operations", "op": "op", } def mkxmlnode(e,oldnode,id_hint): ''' Create xml from the (name,dict) pair. The name is the name of the element. The dict contains either a set of nvpairs or a set of attributes. The id is either generated or copied if found in the provided xml. Stuff such as instance_attributes. ''' if e[0] in conv_list: e[0] = conv_list[e[0]] if e[0] in ("instance_attributes","meta_attributes","operations","cluster_property_set"): return mkxmlnvpairs(e,oldnode,id_hint) elif e[0] == "op": return mkxmlop(e,oldnode,id_hint) elif e[0] == "date_expression": return mkxmldate(e,oldnode,id_hint) elif e[0] == "resource_set": return mkxmlrsc_set(e,oldnode,id_hint) else: return mkxmlsimple(e,oldnode,id_hint) def set_nvpair(set_node,name,value): n_id = set_node.getAttribute("id") for c in set_node.childNodes: if is_element(c) and c.getAttribute("name") == name: c.setAttribute("value",value) return np = cib_factory.createElement("nvpair") np.setAttribute("name",name) np.setAttribute("value",value) new_id = id_store.new(np,n_id) np.setAttribute("id",new_id) set_node.appendChild(np) # # cib element classes (CibObject the parent class) # class CibObject(object): ''' The top level object of the CIB. Resources and constraints. ''' state_fmt = "%16s %-8s%-8s%-8s%-8s%-8s%-4s" set_names = {} def __init__(self,xml_obj_type,obj_id = None): if not xml_obj_type in cib_object_map: unsupported_err(xml_obj_type) return self.obj_type = cib_object_map[xml_obj_type][0] self.parent_type = cib_object_map[xml_obj_type][2] self.xml_obj_type = xml_obj_type self.origin = "" # where did it originally come from? self.nocli = False # we don't support this one + self.nocli_warn = True # don't issue warnings all the time self.updated = False # was the object updated self.invalid = False # the object has been invalidated (removed) self.moved = False # the object has been moved (from/to a container) self.recreate = False # constraints to be recreated self.comment = '' # comment as text self.parent = None # object superior (group/clone/ms) self.children = [] # objects inferior if obj_id: if not self.mknode(obj_id): self = None # won't do :( else: self.obj_id = None self.node = None def dump_state(self): 'Print object status' print self.state_fmt % \ (self.obj_id,self.origin,self.updated,self.moved,self.invalid, \ self.parent and self.parent.obj_id or "", \ len(self.children)) + def repr_cli_xml(self,node,format): + h = cli_display.keyword("xml") + l = node.toprettyxml('\t').split('\n') + l = [x for x in l if x] # drop empty lines + if format > 0: + return "%s %s" % (h,' \\\n'.join(l)) + else: + return "%s %s" % (h,''.join(l)) def repr_cli(self,node = None,format = 1): ''' CLI representation for the node. repr_cli_head and repr_cli_child in subclasess. ''' if not node: node = self.node + if self.nocli: + return self.repr_cli_xml(node,format) l = [] l.append(self.repr_cli_head(node)) cli_add_description(node,l) for c in node.childNodes: if not is_element(c): continue s = self.repr_cli_child(c,format) if s: l.append(s) return self.cli_format(l,format) def repr_cli_child(self,c,format): if c.tagName in self.set_names: return "%s %s" % \ (cli_display.keyword(self.set_names[c.tagName]), \ cli_pairs(nvpairs2list(c))) def cli2node(self,cli,oldnode = None): ''' Convert CLI representation to a DOM node. Defined in subclasses. ''' cli_list = mk_cli_list(cli) if not cli_list: return None if not oldnode: if self.obj_type == "property": oldnode = cib_factory.topnode[cib_object_map[self.xml_obj_type][2]] else: oldnode = self.node return self.cli_list2node(cli_list,oldnode) def cli_format(self,l,format): ''' Format and add comment (if any). ''' s = cli_format(l,format) return (self.comment and format >=0) and '\n'.join([self.comment,s]) or s def set_comment(self,l): s = '\n'.join(l) if self.comment != s: self.comment = s self.modified = True def pull_comments(self): ''' Collect comments from within this node. Remove them from the parent and stuff them in self.comments as an array. ''' l = [] cnodes = [x for x in self.node.childNodes if is_comment(x)] for n in cnodes: l.append(n.data) n.parentNode.removeChild(n) # convert comments from XML node to text. Multiple comments # are concatenated with '\n'. if not l: self.comment = '' return s = '\n'.join(l) l = s.split('\n') for i in range(len(l)): if not l[i].startswith('#'): l[i] = '#%s' % l[i] self.comment = '\n'.join(l) def mknode(self,obj_id): if not cib_factory.is_cib_sane(): return False if id_store.id_in_use(obj_id): return False if self.xml_obj_type in vars.defaults_tags: tag = "meta_attributes" else: tag = self.xml_obj_type self.node = cib_factory.createElement(tag) self.obj_id = obj_id self.node.setAttribute("id",self.obj_id) self.origin = "user" return True def mkcopy(self): ''' Create a new object with the same obj_id and obj_type (for the purpose of CibFactory.delete_objects) ''' obj_copy = CibObject(self.xml_obj_type) obj_copy.obj_id = self.obj_id obj_copy.obj_type = self.obj_type return obj_copy def can_be_renamed(self): ''' Return False if this object can't be renamed. ''' if is_rsc_running(self.obj_id): common_err("cannot rename a running resource (%s)" % self.obj_id) return False if not is_live_cib() and self.node.tagName == "node": common_err("cannot rename nodes") return False return True def attr_exists(self,attr): if not attr in self.node.attributes.keys(): no_attribute_err(attr,self.obj_id) return False return True def cli_use_validate(self): ''' Check validity of the object, as we know it. It may happen that we don't recognize a construct, but that the object is still valid for the CRM. In that case, the object is marked as "CLI read only", i.e. we will neither convert it to CLI nor try to edit it in that format. The validation procedure: we convert xml to cli and then back to xml. If the two xml representations match then we can understand the xml. ''' if not self.node: return True if not self.attr_exists("id"): return False cli_display.set_no_pretty() cli_text = self.repr_cli(format = -1) cli_display.reset_no_pretty() if not cli_text: return False xml2 = self.cli2node(cli_text) if not xml2: return False rc = xml_cmp(self.node, xml2, show = True) xml2.unlink() return rc def check_sanity(self): ''' Right now, this is only for primitives. ''' return 0 def matchcli(self,cli_list): head = cli_list[0] return self.obj_type == head[0] \ and self.obj_id == find_value(head[1],"id") def match(self,xml_obj_type,obj_id): return self.xml_obj_type == xml_obj_type and self.obj_id == obj_id def obj_string(self): return "%s:%s" % (self.obj_type,self.obj_id) def reset_updated(self): self.updated = False self.moved = False self.recreate = False for child in self.children: child.reset_updated() def propagate_updated(self): if self.parent: self.parent.updated = self.updated self.parent.propagate_updated() def update_links(self): ''' Update the structure links for the object (self.children, self.parent). Update also the dom nodes, if necessary. ''' self.children = [] if self.obj_type not in vars.container_tags: return for c in self.node.childNodes: if is_child_rsc(c): child = cib_factory.find_object_for_node(c) if not child: missing_obj_err(c) continue child.parent = self self.children.append(child) if not c.isSameNode(child.node): rmnode(child.node) child.node = c def update_from_cli(self,cli_list): 'Update ourselves from the cli intermediate.' + if len(cli_list) >= 2 and cli_list[1][0] == "raw": + doc = xml.dom.minidom.parseString(cli_list[1][1]) + return self.update_element(doc.childNodes[0]) return self.update_element(self.cli2node(cli_list)) def update_from_node(self,node): 'Update ourselves from a doc node.' return self.update_element(node) def update_element(self,newnode): 'Update ourselves from a doc node.' if not newnode: return False if not cib_factory.is_cib_sane(): return False oldnode = self.node if xml_cmp(oldnode,newnode): newnode.unlink() return True # the new and the old versions are equal obj.node = node if not cib_factory.test_element(self,newnode) or \ not id_store.replace_xml(oldnode,newnode): obj.node = oldnode newnode.unlink() return False self.node = cib_factory.replaceNode(newnode,oldnode) + self.nocli = False # try again after update + if not self.cli_use_validate(): + self.nocli = True + self.nocli_warn = True + else: + self.nocli = False cib_factory.adjust_children(self) oldnode.unlink() self.updated = True self.propagate_updated() return True def top_parent(self): '''Return the top parent or self''' if self.parent: return self.parent.top_parent() else: return self def find_child_in_node(self,child): for c in self.node.childNodes: if not is_element(c): continue if c.tagName == child.obj_type and \ c.getAttribute("id") == child.obj_id: return c return None def filter(self,*args): "Filter objects." if not args: return True if args[0] == "NOOBJ": return False if args[0] == "changed": return self.updated or self.origin == "user" return self.obj_id in args def mk_cli_list(cli): 'Sometimes we get a string and sometimes a list.' if type(cli) == type('') or type(cli) == type(u''): return CliParser().parse(cli) else: return cli class CibNode(CibObject): ''' Node and node's attributes. ''' set_names = { "instance_attributes": "attributes", } def repr_cli_head(self,node): obj_type = vars.cib_cli_map[node.tagName] node_id = node.getAttribute("id") uname = node.getAttribute("uname") s = cli_display.keyword(obj_type) if node_id != uname: s = '%s $id="%s"' % (s, node_id) s = '%s %s' % (s, cli_display.id(uname)) type = node.getAttribute("type") if type != vars.node_default_type: s = '%s:%s' % (s, type) return s def cli_list2node(self,cli_list,oldnode): head = copy.copy(cli_list[0]) head[0] = backtrans[head[0]] obj_id = find_value(head[1],"$id") if not obj_id: obj_id = find_value(head[1],"uname") if not obj_id: return None type = find_value(head[1],"type") if not type: type = vars.node_default_type head[1].append(["type",type]) headnode = mkxmlsimple(head,cib_factory.topnode[cib_object_map[self.xml_obj_type][2]],'node') id_hint = headnode.getAttribute("id") for e in cli_list[1:]: n = mkxmlnode(e,oldnode,id_hint) headnode.appendChild(n) remove_id_used_attributes(cib_factory.topnode[cib_object_map[self.xml_obj_type][2]]) return headnode class CibPrimitive(CibObject): ''' Primitives. ''' set_names = { "instance_attributes": "params", "meta_attributes": "meta", } def repr_cli_head(self,node): obj_type = vars.cib_cli_map[node.tagName] node_id = node.getAttribute("id") ra_type = node.getAttribute("type") ra_class = node.getAttribute("class") ra_provider = node.getAttribute("provider") s1 = s2 = '' if ra_class: s1 = "%s:"%ra_class if ra_provider: s2 = "%s:"%ra_provider s = cli_display.keyword(obj_type) id = cli_display.id(node_id) return "%s %s %s" % (s, id, ''.join((s1,s2,ra_type))) def repr_cli_child(self,c,format): if c.tagName in self.set_names: return "%s %s" % \ (cli_display.keyword(self.set_names[c.tagName]), \ cli_pairs(nvpairs2list(c))) elif c.tagName == "operations": return cli_operations(c,format) def cli_list2node(self,cli_list,oldnode): ''' Convert a CLI description to DOM node. Try to preserve as many ids as possible in case there's an old XML version. ''' head = copy.copy(cli_list[0]) head[0] = backtrans[head[0]] headnode = mkxmlsimple(head,oldnode,'rsc') id_hint = headnode.getAttribute("id") operations = None for e in cli_list[1:]: n = mkxmlnode(e,oldnode,id_hint) if keyword_cmp(e[0], "operations"): operations = n if not keyword_cmp(e[0], "op"): headnode.appendChild(n) else: if not operations: operations = mkxmlnode(["operations",{}],oldnode,id_hint) headnode.appendChild(operations) operations.appendChild(n) remove_id_used_attributes(oldnode) return headnode def check_sanity(self): ''' Check operation timeouts and if all required parameters are defined. ''' if not self.node: # eh? common_err("%s: no xml (strange)" % self.obj_id) return user_prefs.get_check_rc() from ra import RAInfo ra_type = self.node.getAttribute("type") ra_class = self.node.getAttribute("class") ra_provider = self.node.getAttribute("provider") ra = RAInfo(ra_class,ra_type,ra_provider) if not ra.mk_ra_node(): # no RA found? ra.error("no such resource agent") return user_prefs.get_check_rc() params = [] for c in self.node.childNodes: if not is_element(c): continue if c.tagName == "instance_attributes": params += nvpairs2list(c) rc1 = ra.sanity_check_params(self.obj_id, params) actions = {} for c in self.node.childNodes: if not is_element(c): continue if c.tagName == "operations": for c2 in c.childNodes: if is_element(c2) and c2.tagName == "op": op,pl = op2list(c2) if op: actions[op] = pl rc2 = ra.sanity_check_ops(self.obj_id, actions) return rc1 | rc2 class CibContainer(CibObject): ''' Groups and clones and ms. ''' set_names = { "instance_attributes": "params", "meta_attributes": "meta", } def repr_cli_head(self,node): obj_type = vars.cib_cli_map[node.tagName] node_id = node.getAttribute("id") children = [] for c in node.childNodes: if not is_element(c): continue if (obj_type == "group" and is_primitive(c)) or \ is_child_rsc(c): children.append(cli_display.rscref(c.getAttribute("id"))) elif obj_type in vars.clonems_tags and is_child_rsc(c): children.append(cli_display.rscref(c.getAttribute("id"))) s = cli_display.keyword(obj_type) id = cli_display.id(node_id) return "%s %s %s" % (s, id, ' '.join(children)) def cli_list2node(self,cli_list,oldnode): head = copy.copy(cli_list[0]) head[0] = backtrans[head[0]] headnode = mkxmlsimple(head,oldnode,'grp') id_hint = headnode.getAttribute("id") for e in cli_list[1:]: n = mkxmlnode(e,oldnode,id_hint) headnode.appendChild(n) v = find_value(head[1],"$children") if v: for child_id in v: obj = cib_factory.find_object(child_id) if obj: n = obj.node.cloneNode(1) headnode.appendChild(n) else: no_object_err(child_id) remove_id_used_attributes(oldnode) return headnode class CibLocation(CibObject): ''' Location constraint. ''' def repr_cli_head(self,node): obj_type = vars.cib_cli_map[node.tagName] node_id = node.getAttribute("id") rsc = cli_display.rscref(node.getAttribute("rsc")) s = cli_display.keyword(obj_type) id = cli_display.id(node_id) s = "%s %s %s"%(s,id,rsc) pref_node = node.getAttribute("node") score = cli_display.score(get_score(node)) if pref_node: return "%s %s %s" % (s,score,pref_node) else: return s def repr_cli_child(self,c,format): if c.tagName == "rule": return "%s %s" % \ (cli_display.keyword("rule"), cli_rule(c)) def cli_list2node(self,cli_list,oldnode): head = copy.copy(cli_list[0]) head[0] = backtrans[head[0]] headnode = mkxmlsimple(head,oldnode,'location') id_hint = headnode.getAttribute("id") oldrule = None for e in cli_list[1:]: if e[0] in ("expression","date_expression"): n = mkxmlnode(e,oldrule,id_hint) else: n = mkxmlnode(e,oldnode,id_hint) if keyword_cmp(e[0], "rule"): add_missing_attr(n) rule = n headnode.appendChild(n) oldrule = lookup_node(rule,oldnode,location_only=True) else: rule.appendChild(n) remove_id_used_attributes(oldnode) return headnode class CibSimpleConstraint(CibObject): ''' Colocation and order constraints. ''' def repr_cli_head(self,node): obj_type = vars.cib_cli_map[node.tagName] node_id = node.getAttribute("id") s = cli_display.keyword(obj_type) id = cli_display.id(node_id) score = cli_display.score(get_score(node)) if node.getElementsByTagName("resource_set"): col = rsc_set_constraint(node,obj_type) else: col = two_rsc_constraint(node,obj_type) symm = node.getAttribute("symmetrical") if symm: col.append("symmetrical=%s"%symm) return "%s %s %s %s" % (s,id,score,' '.join(col)) def repr_cli_child(self,c,format): pass # no children here def cli_list2node(self,cli_list,oldnode): head = copy.copy(cli_list[0]) head[0] = backtrans[head[0]] headnode = mkxmlsimple(head,oldnode,'') id_hint = headnode.getAttribute("id") for e in cli_list[1:]: # if more than one element, it's a resource set n = mkxmlnode(e,oldnode,id_hint) headnode.appendChild(n) remove_id_used_attributes(oldnode) return headnode class CibProperty(CibObject): ''' Cluster properties. ''' def repr_cli_head(self,node): return '%s $id="%s"' % \ (cli_display.keyword(self.obj_type), node.getAttribute("id")) def repr_cli_child(self,c,format): name = c.getAttribute("name") if "value" in c.attributes.keys(): value = c.getAttribute("value") else: value = None return nvpair_format(name,value) def cli_list2node(self,cli_list,oldnode): head = copy.copy(cli_list[0]) head[0] = backtrans[head[0]] obj_id = find_value(head[1],"$id") if not obj_id: obj_id = cib_object_map[self.xml_obj_type][3] headnode = mkxmlnode(head,oldnode,obj_id) remove_id_used_attributes(oldnode) return headnode def matchcli(self,cli_list): head = cli_list[0] return self.obj_type == head[0] \ and self.obj_id == find_value(head[1],"$id") # ################################################################ # # cib update interface (cibadmin) # cib_piped = "cibadmin -p" def cib_delete_element(obj): 'Remove one element from the CIB.' if obj.xml_obj_type in vars.defaults_tags: node = cib_factory.createElement("meta_attributes") else: node = cib_factory.createElement(obj.xml_obj_type) node.setAttribute("id",obj.obj_id) rc = pipe_string("%s -D" % cib_piped, node.toxml()) if rc != 0: update_err(obj.obj_id,'-D',node.toprettyxml()) node.unlink() return rc def cib_update_elements(upd_list): 'Update a set of objects in the CIB.' l = [x.obj_id for x in upd_list] o = CibObjectSetRaw(*l) xml = o.repr_configure() rc = pipe_string("%s -U" % cib_piped, xml) if rc != 0: update_err(' '.join(l),'-U',xml) return rc def cib_replace_element(obj): comm_node = None if obj.comment: comm_node = cib_factory.createComment(s) if obj.node.hasChildNodes(): obj.node.insertBefore(comm_node, obj.node.firstChild) else: obj.node.appendChild(comm_node) rc = pipe_string("%s -R -o %s" % \ (cib_piped, obj.parent_type), obj.node.toxml()) if rc != 0: update_err(obj.obj_id,'-R',obj.node.toprettyxml()) if comm_node: rmnode(comm_node) return rc def cib_delete_moved_children(obj): for c in obj.children: if c.origin == "cib" and c.moved: cib_delete_element(c) def get_cib_default(property): if cib_factory.is_cib_sane(): return cib_factory.get_property(property) # xml -> cli translations (and classes) cib_object_map = { "node": ( "node", CibNode, "nodes" ), "primitive": ( "primitive", CibPrimitive, "resources" ), "group": ( "group", CibContainer, "resources" ), "clone": ( "clone", CibContainer, "resources" ), "master": ( "ms", CibContainer, "resources" ), "rsc_location": ( "location", CibLocation, "constraints" ), "rsc_colocation": ( "colocation", CibSimpleConstraint, "constraints" ), "rsc_order": ( "order", CibSimpleConstraint, "constraints" ), "cluster_property_set": ( "property", CibProperty, "crm_config", "cib-bootstrap-options" ), "rsc_defaults": ( "rsc_defaults", CibProperty, "rsc_defaults", "rsc-options" ), "op_defaults": ( "op_defaults", CibProperty, "op_defaults", "op-options" ), } backtrans = odict() # generate a translation cli -> tag for key in cib_object_map: backtrans[cib_object_map[key][0]] = key cib_topnodes = [] # get a list of parents for key in cib_object_map: if not cib_object_map[key][2] in cib_topnodes: cib_topnodes.append(cib_object_map[key][2]) cib_upgrade = "cibadmin --upgrade --force" class CibFactory(Singleton): ''' Juggle with CIB objects. See check_structure below for details on the internal cib representation. ''' shadowcmd = ">/dev/null 1: common_warn("%s contains more than one %s, using first" % \ (obj.obj_id,attr_list_type)) id = node_l[0].getAttribute("id") if not id: common_err("%s reference not found" % id_ref) return id_ref # hope that user will fix that return id # verify if id_ref exists node_l = self.doc.getElementsByTagName(attr_list_type) for node in node_l: if node.getAttribute("id") == id_ref: return id_ref common_err("%s reference not found" % id_ref) return id_ref # hope that user will fix that def get_property(self,property): ''' Get the value of the given cluster property. ''' for obj in self.cib_objects: if obj.obj_type == "property" and obj.node: pl = nvpairs2list(obj.node) v = find_value(pl, property) if v: return v return None def new_object(self,obj_type,obj_id): "Create a new object of type obj_type." if id_store.id_in_use(obj_id): return None for xml_obj_type,v in cib_object_map.items(): if v[0] == obj_type: obj = v[1](xml_obj_type,obj_id) if obj.obj_id: return obj else: return None return None def mkobj_list(self,mode,*args): obj_list = [] for obj in self.cib_objects: f = lambda: obj.filter(*args) if not f(): continue - if mode == "cli" and obj.nocli: - obj_cli_err(obj.obj_id) - continue + if mode == "cli" and obj.nocli and obj.nocli_warn: + obj.nocli_warn = False + obj_cli_warn(obj.obj_id) obj_list.append(obj) return obj_list def has_cib_changed(self): return self.mkobj_list("xml","changed") or self.remove_queue def verify_constraints(self,node): ''' Check if all resources referenced in a constraint exist ''' rc = True constraint_id = node.getAttribute("id") for obj_id in referenced_resources(node): if not self.find_object(obj_id): constraint_norefobj_err(constraint_id,obj_id) rc = False return rc def verify_rsc_children(self,node): ''' Check prerequisites: a) all children must exist b) no child may have other parent than me (or should we steal children?) c) there may not be duplicate children ''' obj_id = node.getAttribute("id") if not obj_id: common_err("element %s has no id" % node.tagName) return False try: obj_type = cib_object_map[node.tagName][0] except: common_err("element %s (%s) not recognized"%(node.tagName,obj_id)) return False c_ids = get_rsc_children_ids(node) if not c_ids: return True rc = True c_dict = {} for child_id in c_ids: if not self.verify_child(child_id,obj_type,obj_id): rc = False if child_id in c_dict: common_err("in group %s child %s listed more than once"%(obj_id,child_id)) rc = False c_dict[child_id] = 1 return rc def verify_child(self,child_id,obj_type,obj_id): 'Check if child exists and obj_id is (or may become) its parent.' child = self.find_object(child_id) if not child: no_object_err(child_id) return False if child.parent and child.parent.obj_id != obj_id: common_err("%s already in use at %s"%(child_id,child.parent.obj_id)) return False if obj_type == "group" and child.obj_type != "primitive": common_err("a group may contain only primitives; %s is %s"%(child_id,child.obj_type)) return False if not child.obj_type in vars.children_tags: common_err("%s may contain a primitive or a group; %s is %s"%(obj_type,child_id,child.obj_type)) return False return True def verify_element(self,node): ''' Can we create this object given its CLI representation. This is not about syntax, we're past that, but about semantics. Right now we check if the children, if any, are fit for the parent. And if this is a constraint, if all referenced resources are present. ''' rc = True if not self.verify_rsc_children(node): rc = False if not self.verify_constraints(node): rc = False return rc def create_object(self,*args): return self.create_from_cli(CliParser().parse(list(args))) != None def set_property_cli(self,cli_list): head_pl = cli_list[0] obj_type = head_pl[0].lower() pset_id = find_value(head_pl[1],"$id") if pset_id: head_pl[1].remove(["$id",pset_id]) else: pset_id = cib_object_map[backtrans[obj_type]][3] obj = self.find_object(pset_id) if not obj: if not is_id_valid(pset_id): invalid_id_err(pset_id) return None obj = self.new_object(obj_type,pset_id) if not obj: return None self.topnode[obj.parent_type].appendChild(obj.node) obj.origin = "user" self.cib_objects.append(obj) for n,v in head_pl[1]: set_nvpair(obj.node,n,v) obj.updated = True return obj def add_op(self,cli_list): '''Add an op to a primitive.''' head = cli_list[0] # does the referenced primitive exist rsc_id = find_value(head[1],"rsc") rsc_obj = cib_factory.find_object(rsc_id) if not rsc_obj: no_object_err(rsc_id) return None if rsc_obj.obj_type != "primitive": common_err("%s is not a primitive" % rsc_id) return None # check if there is already an op with the same interval name = find_value(head[1], "name") interval = find_value(head[1], "interval") if find_operation(rsc_obj.node,name,interval): common_err("%s already has a %s op with interval %s" % \ (rsc_id, name, interval)) return None # drop the rsc attribute head[1].remove(["rsc",rsc_id]) # create an xml node mon_node = mkxmlsimple(head, None, rsc_id) # get the place to append it to try: op_node = rsc_obj.node.getElementsByTagName("operations")[0] except: op_node = self.createElement("operations") rsc_obj.node.appendChild(op_node) op_node.appendChild(mon_node) # the resource is updated rsc_obj.updated = True rsc_obj.propagate_updated() return rsc_obj def create_from_cli(self,cli): 'Create a new cib object from the cli representation.' cli_list = mk_cli_list(cli) if not cli_list: return None head = cli_list[0] obj_type = head[0].lower() obj_id = find_value(head[1],"id") if obj_id and not is_id_valid(obj_id): invalid_id_err(obj_id) return None + if len(cli_list) >= 2 and cli_list[1][0] == "raw": + doc = xml.dom.minidom.parseString(cli_list[1][1]) + return self.create_from_node(doc.childNodes[0]) if obj_type in olist(vars.nvset_cli_names): return self.set_property_cli(cli_list) if obj_type == "op": return self.add_op(cli_list) obj = self.new_object(obj_type,obj_id) if not obj: return None node = obj.cli2node(cli_list) obj.node = node obj.obj_id = obj_id if not node: return None if not self.test_element(obj, node): id_store.remove_xml(node) node.unlink() return None self.add_element(obj, node) return obj def update_moved(self,obj): 'Updated the moved flag. Mark affected constraints.' obj.moved = not obj.moved if obj.moved: for c_obj in self.related_constraints(obj): c_obj.recreate = True def adjust_children(self,obj): ''' All stuff children related: manage the nodes of children, update the list of children for the parent, update parents in the children. ''' new_children_ids = get_rsc_children_ids(obj.node) if not new_children_ids: return old_children = obj.children obj.children = [self.find_object(x) for x in new_children_ids] self._relink_orphans_to_top(old_children,obj.children) self._update_children(obj) def _relink_child_to_top(self,obj): 'Relink a child to the top node.' obj.node.parentNode.removeChild(obj.node) self.topnode[obj.parent_type].appendChild(obj.node) if obj.origin == "cib": self.update_moved(obj) obj.parent = None def _update_children(self,obj): '''For composite objects: update all children nodes. ''' # unlink all and find them in the new node for child in obj.children: oldnode = child.node child.node = obj.find_child_in_node(child) if child.children: # and children of children self._update_children(child) rmnode(oldnode) if not child.parent and child.origin == "cib": self.update_moved(child) if child.parent and child.parent != obj: child.parent.updated = True # the other parent updated child.parent = obj def _relink_orphans_to_top(self,old_children,new_children): "New orphans move to the top level for the object type." for child in old_children: if child not in new_children: self._relink_child_to_top(child) def test_element(self,obj,node): if not node.getAttribute("id"): return False if not self.verify_element(node): return False if user_prefs.is_check_always() \ and obj.check_sanity() > 1: return False return True def add_element(self,obj,node): + common_debug("append child %s to %s" % \ + (obj.obj_id,self.topnode[obj.parent_type].tagName)) self.topnode[obj.parent_type].appendChild(node) self.adjust_children(obj) self.redirect_children_constraints(obj) if not obj.cli_use_validate(): + self.nocli_warn = True obj.nocli = True obj.update_links() obj.origin = "user" self.cib_objects.append(obj) def create_from_node(self,node): 'Create a new cib object from a document node.' if not node: return None try: obj_type = cib_object_map[node.tagName][0] except: return None if is_defaults(node): node = get_rscop_defaults_meta_node(node) if not node: return None if node.ownerDocument != self.doc: node = self.doc.importNode(node,1) obj = self.new_object(obj_type, node.getAttribute("id")) if not obj: return None if not id_store.store_xml(node): return None obj.node = node obj.obj_id = node.getAttribute("id") if not self.test_element(obj, node): id_store.remove_xml(node) node.unlink() return None self.add_element(obj, node) return obj def cib_objects_string(self, obj_list = None): l = [] if not obj_list: obj_list = self.cib_objects for obj in obj_list: l.append(obj.obj_string()) return ' '.join(l) def _remove_obj(self,obj): "Remove a cib object and its children." # remove children first # can't remove them here from obj.children! common_debug("remove object %s" % obj.obj_string()) for child in obj.children: #self._remove_obj(child) # just relink, don't remove children self._relink_child_to_top(child) if obj.parent: # remove obj from its parent, if any obj.parent.children.remove(obj) id_store.remove_xml(obj.node) rmnode(obj.node) obj.invalid = True self.add_to_remove_queue(obj) self.cib_objects.remove(obj) for c_obj in self.related_constraints(obj): if is_simpleconstraint(c_obj.node) and obj.children: # the first child inherits constraints rename_rscref(c_obj,obj.obj_id,obj.children[0].obj_id) delete_rscref(c_obj,obj.obj_id) if silly_constraint(c_obj.node,obj.obj_id): # remove invalid constraints self._remove_obj(c_obj) if not self._no_constraint_rm_msg: err_buf.info("hanging %s deleted" % c_obj.obj_string()) def related_constraints(self,obj): if not is_resource(obj.node): return [] c_list = [] for obj2 in self.cib_objects: if not is_constraint(obj2.node): continue if rsc_constraint(obj.obj_id,obj2.node): c_list.append(obj2) return c_list def redirect_children_constraints(self,obj): ''' Redirect constraints to the new parent ''' for child in obj.children: for c_obj in self.related_constraints(child): self.remove_queue.append(c_obj.mkcopy()) rename_rscref(c_obj,child.obj_id,obj.obj_id) # drop useless constraints which may have been created above for c_obj in self.related_constraints(obj): if silly_constraint(c_obj.node,obj.obj_id): self._no_constraint_rm_msg = True self._remove_obj(c_obj) self._no_constraint_rm_msg = False def add_to_remove_queue(self,obj): if obj.origin == "cib": self.remove_queue.append(obj) #print self.cib_objects_string(self.remove_queue) def delete_1(self,obj): ''' Remove an object and its parent in case the object is the only child. ''' if obj.parent and len(obj.parent.children) == 1: self.delete_1(obj.parent) if obj in self.cib_objects: # don't remove parents twice self._remove_obj(obj) def delete(self,*args): 'Delete a cib object.' if not self.doc: empty_cib_err() return False rc = True l = [] for obj_id in args: obj = self.find_object(obj_id) if not obj: no_object_err(obj_id) rc = False continue if is_rsc_running(obj_id): common_warn("resource %s is running, can't delete it" % obj_id) else: l.append(obj) if l: l = processing_sort_cli(l) for obj in reversed(l): self.delete_1(obj) return rc def remove_on_rename(self,obj): ''' If the renamed object is coming from the cib, then it must be removed and a new one created. ''' if obj.origin == "cib": self.remove_queue.append(obj.mkcopy()) obj.origin = "user" def rename(self,old_id,new_id): ''' Rename a cib object. - check if the resource (if it's a resource) is stopped - check if the new id is not taken - find the object with old id - rename old id to new id in all related objects (constraints) - if the object came from the CIB, then it must be deleted and the one with the new name created - rename old id to new id in the object ''' if not self.doc: empty_cib_err() return False if id_store.id_in_use(new_id): return False obj = self.find_object(old_id) if not obj: no_object_err(old_id) return False if not obj.can_be_renamed(): return False for c_obj in self.related_constraints(obj): rename_rscref(c_obj,old_id,new_id) self.remove_on_rename(obj) rename_id(obj.node,old_id,new_id) obj.obj_id = new_id id_store.rename(old_id,new_id) obj.updated = True obj.propagate_updated() def erase(self): "Remove all cib objects." # remove only bottom objects and no constraints # the rest will automatically follow if not self.doc: empty_cib_err() return False erase_ok = True l = [] for obj in [obj for obj in self.cib_objects \ if not obj.children and not is_constraint(obj.node) \ and obj.obj_type != "node" ]: if is_rsc_running(obj.obj_id): common_warn("resource %s is running, can't delete it" % obj.obj_id) erase_ok = False else: l.append(obj) if not erase_ok: common_err("CIB erase aborted (nothing was deleted)") return False self._no_constraint_rm_msg = True for obj in l: self.delete(obj.obj_id) self._no_constraint_rm_msg = False remaining = 0 for obj in self.cib_objects: if obj.obj_type != "node": remaining += 1 if remaining > 0: common_err("strange, but these objects remained:") for obj in self.cib_objects: if obj.obj_type != "node": print >> sys.stderr, obj.obj_string() self.cib_objects = [] return True def erase_nodes(self): "Remove nodes only." if not self.doc: empty_cib_err() return False l = [obj for obj in self.cib_objects if obj.obj_type == "node"] for obj in l: self.delete(obj.obj_id) def refresh(self): "Refresh from the CIB." self.reset() self.initialize() user_prefs = UserPrefs.getInstance() options = Options.getInstance() err_buf = ErrorBuffer.getInstance() vars = Vars.getInstance() cib_factory = CibFactory.getInstance() cli_display = CliDisplay.getInstance() cib_status = CibStatus.getInstance() id_store = IdMgmt.getInstance() # vim:ts=4:sw=4:et: diff --git a/shell/modules/msg.py b/shell/modules/msg.py index 559a4ba709..3ae1a4ff88 100644 --- a/shell/modules/msg.py +++ b/shell/modules/msg.py @@ -1,149 +1,149 @@ # 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 sys from singletonmixin import Singleton from userprefs import Options, UserPrefs class ErrorBuffer(Singleton): ''' Show error messages either immediately or buffered. ''' def __init__(self): self.msg_list = [] self.mode = "immediate" self.lineno = -1 def buffer(self): self.mode = "keep" def release(self): if self.msg_list: print >> sys.stderr, '\n'.join(self.msg_list) if not options.batch: try: raw_input("Press enter to continue... ") except EOFError: pass self.msg_list = [] self.mode = "immediate" def writemsg(self,msg): if self.mode == "immediate": if options.regression_tests: print msg else: print >> sys.stderr, msg else: self.msg_list.append(msg) def reset_lineno(self): self.lineno = 0 def incr_lineno(self): if self.lineno >= 0: self.lineno += 1 def start_tmp_lineno(self): self._save_lineno = self.lineno self.reset_lineno() def stop_tmp_lineno(self): self.lineno = self._save_lineno def add_lineno(self,s): if self.lineno > 0: return "%d: %s" % (self.lineno,s) else: return s def error(self,s): self.writemsg("ERROR: %s" % self.add_lineno(s)) def warning(self,s): self.writemsg("WARNING: %s" % self.add_lineno(s)) def info(self,s): self.writemsg("INFO: %s" % self.add_lineno(s)) def debug(self,s): if user_prefs.get_debug(): self.writemsg("DEBUG: %s" % self.add_lineno(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 common_debug(s): err_buf.debug(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 obj_cli_warn(name): + err_buf.warning("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_usage(cmd,args): err_buf.error("bad usage: %s %s"%(cmd,args)) def empty_cib_err(): err_buf.error("No CIB!") def cib_parse_err(msg,s): err_buf.error("%s"%msg) err_buf.info("offending string: %s" % s) 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,xml): if cibadm_opt == '-U': task = "update" elif cibadm_opt == '-D': task = "delete" else: task = "replace" err_buf.error("could not %s %s"%(task,obj_id)) err_buf.info("offending xml: %s" % xml) def not_impl_info(s): err_buf.info("%s is not implemented yet" % s) user_prefs = UserPrefs.getInstance() err_buf = ErrorBuffer.getInstance() options = Options.getInstance() # vim:ts=4:sw=4:et: diff --git a/shell/modules/parse.py b/shell/modules/parse.py index 5dab950e75..1d3ca60429 100644 --- a/shell/modules/parse.py +++ b/shell/modules/parse.py @@ -1,620 +1,664 @@ # 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 re +import xml.dom.minidom from utils import * from vars import Vars from msg import * from ra import disambiguate_ra_type, ra_type_validate # # CLI parsing utilities # WARNING: ugly code ahead (to be replaced some day by a proper # yacc parser, if there's such a thing) # def cli_parse_rsctype(s, pl): ''' Parse the resource type. ''' ra_class,provider,rsc_type = disambiguate_ra_type(s) if not ra_type_validate(s,ra_class,provider,rsc_type): return None pl.append(["class",ra_class]) if ra_class == "ocf": pl.append(["provider",provider]) pl.append(["type",rsc_type]) def is_attribute(p,a): return p.startswith(a + '=') def cli_parse_attr_strict(s,pl): ''' Parse attributes in the 'p=v' form. ''' if s and '=' in s[0]: n,v = s[0].split('=',1) if not n: return pl.append([n,v]) cli_parse_attr_strict(s[1:],pl) def cli_parse_attr(s,pl): ''' Parse attributes in the 'p=v' form. Allow also the 'p' form (no value) unless p is one of the attr_list_keyw words. ''' attr_lists_keyw = olist(["params","meta","operations","op","attributes"]) if s: if s[0] in attr_lists_keyw: return if '=' in s[0]: n,v = s[0].split('=',1) else: n = s[0]; v = None if not n: return pl.append([n,v]) cli_parse_attr(s[1:],pl) def is_only_id(pl,keyw): if len(pl) > 1: common_err("%s: only single $id or $id-ref attribute is allowed" % keyw) return False if len(pl) == 1 and pl[0][0] not in ("$id","$id-ref"): common_err("%s: only single $id or $id-ref attribute is allowed" % keyw) return False return True def check_operation(pl): op_name = find_value(pl,"name") if not op_name in olist(vars.op_cli_names): common_warn("%s: operation not recognized" % op_name) if op_name == "monitor" and not find_value(pl,"interval"): common_err("monitor requires interval") return False return True def parse_resource(s): el_type = s[0].lower() if el_type == "master": # ugly kludge :( el_type = "ms" attr_lists_keyw = olist(["params","meta"]) cli_list = [] # the head head = [] head.append(["id",s[1]]) i = 3 if el_type == "primitive": cli_parse_rsctype(s[2],head) if not find_value(head,"type"): syntax_err(s[2:], context = "primitive") return False else: cl = [] cl.append(s[2]) if el_type == "group": while i < len(s): if s[i] in attr_lists_keyw: break elif is_attribute(s[i],"description"): break else: cl.append(s[i]) i += 1 # skip to the next token head.append(["$children",cl]) try: # s[i] may be out of range if is_attribute(s[i],"description"): cli_parse_attr(s[i:i+1],head) i += 1 # skip to the next token except: pass cli_list.append([el_type,head]) # the rest state = 0 # 1: reading operations; 2: operations read while len(s) > i+1: pl = [] keyw = s[i].lower() if keyw in attr_lists_keyw: if state == 1: state = 2 elif el_type == "primitive" and state == 0 and keyword_cmp(keyw, "operations"): state = 1 elif el_type == "primitive" and state <= 1 and keyword_cmp(keyw, "op"): if state == 0: state = 1 pl.append(["name",s[i+1]]) else: syntax_err(s[i:], context = 'primitive') return False if keyword_cmp(keyw, "op"): if len(s) > i+2: cli_parse_attr(s[i+2:],pl) if not check_operation(pl): return False else: cli_parse_attr(s[i+1:],pl) if len(pl) == 0: syntax_err(s[i:], context = 'primitive') return False if keyword_cmp(keyw, "operations") and not is_only_id(pl,keyw): return False i += len(pl)+1 # interval is obligatory for ops, supply 0 if not there if keyword_cmp(keyw, "op") and not find_value(pl,"interval"): pl.append(["interval","0"]) cli_list.append([keyw,pl]) if len(s) > i: syntax_err(s[i:], context = 'primitive') return False return cli_list def parse_op(s): if len(s) != 3: syntax_err(s, context = s[0]) return False cli_list = [] head_pl = [] # this is an op cli_list.append(["op",head_pl]) if not cli_parse_rsc_role(s[1],head_pl): return False if not cli_parse_op_times(s[2],head_pl): return False # rename rsc-role to role for i in range(len(head_pl)): if head_pl[i][0] == "rsc-role": head_pl[i][0] = "role" break # add the operation name head_pl.append(["name",s[0]]) return cli_list def cli_parse_score(score,pl,noattr = False): if score.endswith(':'): score = score.rstrip(':') else: syntax_err(score, context = 'score') return False if score in vars.score_types: pl.append(["score",vars.score_types[score]]) elif re.match("^[+-]?(inf|infinity|INFINITY|[[0-9]+)$",score): score = score.replace("infinity","INFINITY") score = score.replace("inf","INFINITY") pl.append(["score",score]) elif score: if noattr: common_err("attribute not allowed for score in orders") return False else: pl.append(["score-attribute",score]) return True def is_binary_op(s): l = s.split(':') if len(l) == 2: return l[0] in vars.binary_types and l[1] in olist(vars.binary_ops) elif len(l) == 1: return l[0] in olist(vars.binary_ops) else: return False def cli_parse_binary_op(s,pl): l = s.split(':') if len(l) == 2: pl.append(["type",l[0]]) pl.append(["operation",l[1]]) else: pl.append(["operation",l[0]]) def cli_parse_expression(s,pl): if len(s) > 1 and s[0] in olist(vars.unary_ops): pl.append(["operation",s[0]]) pl.append(["attribute",s[1]]) elif len(s) > 2 and is_binary_op(s[1]): pl.append(["attribute",s[0]]) cli_parse_binary_op(s[1],pl) pl.append(["value",s[2]]) else: return False return True def cli_parse_dateexpr(s,pl): if len(s) < 3: return False if s[1] not in olist(vars.date_ops): return False pl.append(["operation",s[1]]) if s[1] in olist(vars.simple_date_ops): pl.append([keyword_cmp(s[1], 'lt') and "end" or "start",s[2]]) return True cli_parse_attr_strict(s[2:],pl) return True def parse_rule(s): if not keyword_cmp(s[0], "rule"): syntax_err(s,context = "rule") return 0,None rule_list = [] head_pl = [] rule_list.append([s[0].lower(),head_pl]) i = 1 cli_parse_attr_strict(s[i:],head_pl) i += len(head_pl) if find_value(head_pl,"$id-ref"): return i,rule_list if not cli_parse_score(s[i],head_pl): return i,None i += 1 bool_op = '' while len(s) > i+1: pl = [] if keyword_cmp(s[i], "date"): fun = cli_parse_dateexpr elem = "date_expression" else: fun = cli_parse_expression elem = "expression" if not fun(s[i:],pl): syntax_err(s[i:],context = "rule") return i,None rule_list.append([elem,pl]) i += len(pl) if find_value(pl, "type"): i -= 1 # reduce no of tokens by one if there was "type:op" if elem == "date_expression": i += 1 # increase no of tokens by one if it was date expression if len(s) > i and s[i] in olist(vars.boolean_ops): if bool_op and not keyword_cmp(bool_op, s[i]): common_err("rule contains different bool operations: %s" % ' '.join(s)) return i,None else: bool_op = s[i].lower() i += 1 if len(s) > i and keyword_cmp(s[i], "rule"): break if bool_op and not keyword_cmp(bool_op, 'and'): head_pl.append(["boolean-op",bool_op]) return i,rule_list def parse_location(s): cli_list = [] head_pl = [] head_pl.append(["id",s[1]]) head_pl.append(["rsc",s[2]]) cli_list.append([s[0].lower(),head_pl]) if len(s) == 5 and not keyword_cmp(s[3], "rule"): # the short node preference form if not cli_parse_score(s[3],head_pl): return False head_pl.append(["node",s[4]]) return cli_list i = 3 while i < len(s): numtoks,l = parse_rule(s[i:]) if not l: return False cli_list += l i += numtoks if len(s) < i: syntax_err(s[i:],context = "location") return False return cli_list def cli_opt_symmetrical(p,pl): if not p: return True pl1 = [] cli_parse_attr([p],pl1) if len(pl1) != 1 or not find_value(pl1,"symmetrical"): syntax_err(p,context = "order") return False pl += pl1 return True def cli_parse_rsc_role(s,pl,attr_pfx = ''): l = s.split(':') pl.append([attr_pfx+"rsc",l[0]]) if len(l) == 2: if l[1] not in vars.roles_names: bad_def_err("resource role",s) return False pl.append([attr_pfx+"rsc-role",l[1]]) elif len(l) > 2: bad_def_err("resource role",s) return False return True def cli_parse_op_times(s,pl): l = s.split(':') pl.append(["interval",l[0]]) if len(l) == 2: pl.append(["timeout",l[1]]) elif len(l) > 2: bad_def_err("op times",s) return False return True class ResourceSet(object): ''' Constraint resource set parser. Parses sth like: a ( b c:start ) d:Master e ... Appends one or more lists to cli_list. Lists are in form: list :: ["resource_set",set_pl] set_pl :: [["sequential","false"], ["action"|"role",action|role], ["resource_ref",["id",rsc]], ...] (the first two elements of set_pl are optional) Action/role change makes a new resource set. ''' def __init__(self,type,s,cli_list): self.type = type self.valid_q = (type == "order") and vars.actions_names or vars.roles_names self.q_attr = (type == "order") and "action" or "role" self.tokens = s self.cli_list = cli_list self.reset_set() self.sequential = True self.fix_parentheses() def fix_parentheses(self): newtoks = [] for p in self.tokens: if p.startswith('(') and len(p) > 1: newtoks.append('(') newtoks.append(p[1:]) elif p.endswith(')') and len(p) > 1: newtoks.append(p[0:len(p)-1]) newtoks.append(')') else: newtoks.append(p) self.tokens = newtoks def reset_set(self): self.set_pl = [] self.prev_q = '' # previous qualifier (action or role) self.curr_attr = '' # attribute (action or role) def save_set(self): if not self.set_pl: return if self.curr_attr: self.set_pl.insert(0,[self.curr_attr,self.prev_q]) if not self.sequential: self.set_pl.insert(0,["sequential","false"]) self.cli_list.append(["resource_set",self.set_pl]) self.reset_set() def splitrsc(self,p): l = p.split(':') return (len(l) == 1) and [p,''] or l def parse(self): tokpos = -1 for p in self.tokens: tokpos += 1 if p == "_rsc_set_": continue # a degenerate resource set if p == '(': if self.set_pl: # save the set before self.save_set() self.sequential = False continue if p == ')': if self.sequential: # no '(' syntax_err(self.tokens[tokpos:],context = self.type) return False if not self.set_pl: # empty sets not allowed syntax_err(self.tokens[tokpos:],context = self.type) return False self.save_set() self.sequential = True continue rsc,q = self.splitrsc(p) if q != self.prev_q: # one set can't have different roles/actions self.save_set() self.prev_q = q if q: if q not in self.valid_q: common_err("%s: invalid %s in %s" % (q,self.q_attr,self.type)) return False if not self.curr_attr: self.curr_attr = self.q_attr else: self.curr_attr = '' self.set_pl.append(["resource_ref",["id",rsc]]) if not self.sequential: # no ')' syntax_err(self.tokens[tokpos:],context = self.type) return False if self.set_pl: # save the final set self.save_set() return True def parse_colocation(s): cli_list = [] head_pl = [] type = s[0] if type == "collocation": # another ugly :( type = "colocation" cli_list.append([type,head_pl]) if len(s) < 5: syntax_err(s,context = "colocation") return False head_pl.append(["id",s[1]]) if not cli_parse_score(s[2],head_pl): return False if len(s) == 5: if not cli_parse_rsc_role(s[3],head_pl): return False if not cli_parse_rsc_role(s[4],head_pl,'with-'): return False else: resource_set_obj = ResourceSet(type,s[3:],cli_list) if not resource_set_obj.parse(): return False return cli_list def cli_parse_rsc_action(s,pl,rsc_pos): l = s.split(':') pl.append([rsc_pos,l[0]]) if len(l) == 2: if l[1] not in vars.actions_names: bad_def_err("resource action",s) return False pl.append([rsc_pos+"-action",l[1]]) elif len(l) > 1: bad_def_err("resource action",s) return False return True def parse_order(s): cli_list = [] head_pl = [] type = "order" cli_list.append([s[0],head_pl]) if len(s) < 5: syntax_err(s,context = "order") return False head_pl.append(["id",s[1]]) if not cli_parse_score(s[2],head_pl,noattr = True): return False # save symmetrical for later (if it exists) symm = "" if is_attribute(s[len(s)-1],"symmetrical"): symm = s.pop() if len(s) == 5: if not cli_parse_rsc_action(s[3],head_pl,'first'): return False if not cli_parse_rsc_action(s[4],head_pl,'then'): return False else: resource_set_obj = ResourceSet(type,s[3:],cli_list) if not resource_set_obj.parse(): return False if not cli_opt_symmetrical(symm,head_pl): return False return cli_list def parse_constraint(s): if keyword_cmp(s[0], "location"): return parse_location(s) elif s[0] in olist(["colocation","collocation"]): return parse_colocation(s) elif keyword_cmp(s[0], "order"): return parse_order(s) def parse_property(s): cli_list = [] head_pl = [] cli_list.append([s[0],head_pl]) cli_parse_attr(s[1:],head_pl) if len(head_pl) < 0 or len(s) > len(head_pl)+1: syntax_err(s, context = s[0]) return False return cli_list def cli_parse_uname(s, pl): l = s.split(':') if not l or len(l) > 2: return None pl.append(["uname",l[0]]) if len(l) == 2: pl.append(["type",l[1]]) def parse_node(s): cli_list = [] # the head head = [] # optional $id id = '' opt_id_l = [] i = 1 cli_parse_attr_strict(s[i:],opt_id_l) if opt_id_l: id = find_value(opt_id_l,"$id") i += 1 # uname[:type] cli_parse_uname(s[i],head) uname = find_value(head,"uname") if not uname: return False head.append(["id",id and id or uname]) # drop type if default type = find_value(head,"type") if type == vars.node_default_type: head.remove(["type",type]) cli_list.append([s[0],head]) if len(s) == i: return cli_list # the rest i += 1 try: # s[i] may be out of range if is_attribute(s[i],"description"): cli_parse_attr(s[i:i+1],head) i += 1 # skip to the next token except: pass while len(s) > i+1: if not s[i] in olist(vars.node_attributes_keyw): syntax_err(s[i:], context = 'node') return False pl = [] cli_parse_attr(s[i+1:],pl) if len(pl) == 0: syntax_err(s[i:], context = 'node') return False cli_list.append([s[i],pl]) i += len(pl)+1 if len(s) > i: syntax_err(s[i:], context = 'node') return False return cli_list +def parse_xml(s): + cli_list = [] + head = [] + try: + xml_s = ' '.join(s[1:]) + except: + syntax_err(s, context = 'xml') + return False + # strip spaces between elements + # they produce text elements + xml_s = re.sub(r">\s+<", "><", xml_s) + try: + doc = xml.dom.minidom.parseString(xml_s) + except xml.parsers.expat.ExpatError, msg: + common_err("cannot parse xml chunk: %s" % xml_s) + common_err(msg) + return False + try: + elnode = doc.childNodes[0] + except: + common_err("no elements in %s" % xml_s) + return False + try: + el_type = vars.cib_cli_map[elnode.tagName] + except: + common_err("element %s not recognized" % elnode.tagName) + return False + id = elnode.getAttribute("id") + head.append(["id",id]) + cli_list.append([el_type,head]) + cli_list.append(["raw",xml_s]) + return cli_list + +def xml_lex(s): + l = lines2cli(s) + a = [] + for p in l: + a += p.split() + return a class CliParser(object): parsers = { "primitive": (3,parse_resource), "group": (3,parse_resource), "clone": (3,parse_resource), "ms": (3,parse_resource), "master": (3,parse_resource), "location": (3,parse_constraint), "colocation": (3,parse_constraint), "collocation": (3,parse_constraint), "order": (3,parse_constraint), "monitor": (3,parse_op), "node": (2,parse_node), "property": (2,parse_property), "rsc_defaults": (2,parse_property), "op_defaults": (2,parse_property), + "xml": (3,parse_xml), } def __init__(self): self.comments = [] def parse(self,s): ''' Input: a list of tokens (or a CLI format string). Return: a list of items; each item is a tuple with two members: a string (tag) and a nvpairs or attributes dict. ''' cli_list = '' if type(s) == type(u''): s = s.encode('ascii') if type(s) == type(''): if s and s.startswith('#'): #self.comments.append(s) return None - try: - s = shlex.split(s) - except ValueError, msg: - common_err(msg) - return False + if s.startswith('xml'): + s = xml_lex(s) + else: + try: + s = shlex.split(s) + except ValueError, msg: + common_err(msg) + return False # but there shouldn't be any newlines (?) while '\n' in s: s.remove('\n') if not s: return None if s[0] not in self.parsers.keys(): syntax_err(s) return False mintoks,parser_fn = self.parsers[s[0]] if len(s) < mintoks: syntax_err(s) return False cli_list = parser_fn(s) if not cli_list: return False if self.comments: cli_list.append(["comments",self.comments]) self.comments = [] return cli_list vars = Vars.getInstance() # vim:ts=4:sw=4:et: diff --git a/shell/modules/ui.py.in b/shell/modules/ui.py.in index 54b6ecbbef..652864f918 100644 --- a/shell/modules/ui.py.in +++ b/shell/modules/ui.py.in @@ -1,1765 +1,1769 @@ # 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 sys import re import os import readline import time from help import HelpSystem, cmd_help from vars import Vars from cache import WCache from levels import Levels from cibconfig import mkset_obj, CibFactory from cibstatus import CibStatus from template import LoadTemplate from ra import * from msg import * from utils import * from xmlutil import * def cmd_end(cmd,dir = ".."): "Go up one level." levels.droplevel() def cmd_exit(cmd): "Exit the crm program" cmd_end(cmd) if options.interactive and not options.batch: print "bye" try: readline.write_history_file(hist_file) except: pass for f in vars.tmpfiles: os.unlink(f) sys.exit() class UserInterface(object): ''' Stuff common to all user interface classes. ''' global_cmd_aliases = { "quit": ("bye","exit"), "end": ("cd","up"), } def __init__(self): self.cmd_table = odict() self.cmd_table["help"] = (self.help,(0,1),0) self.cmd_table["quit"] = (self.exit,(0,0),0) self.cmd_table["end"] = (self.end,(0,1),0) self.cmd_aliases = self.global_cmd_aliases.copy() def end_game(self, no_questions_asked = False): pass def help(self,cmd,topic = ''): "usage: help []" cmd_help(self.help_table,topic) def end(self,cmd,dir = ".."): "usage: end" self.end_game() cmd_end(cmd,dir) def exit(self,cmd): "usage: exit" self.end_game() cmd_exit(cmd) class CliOptions(UserInterface): ''' Manage user preferences ''' def __init__(self): UserInterface.__init__(self) self.help_table = help_sys.load_level("options") self.cmd_table["skill-level"] = (self.set_skill_level,(1,1),0,(skills_list,)) self.cmd_table["editor"] = (self.set_editor,(1,1),0) self.cmd_table["pager"] = (self.set_pager,(1,1),0) self.cmd_table["user"] = (self.set_crm_user,(0,1),0) self.cmd_table["output"] = (self.set_output,(1,1),0) self.cmd_table["colorscheme"] = (self.set_colors,(1,1),0) self.cmd_table["check-frequency"] = (self.set_check_frequency,(1,1),0) self.cmd_table["check-mode"] = (self.set_check_mode,(1,1),0) self.cmd_table["sort-elements"] = (self.set_sort_elements,(1,1),0) self.cmd_table["save"] = (self.save_options,(0,0),0) self.cmd_table["show"] = (self.show_options,(0,0),0) setup_aliases(self) def set_skill_level(self,cmd,skill_level): """usage: skill-level level: operator | administrator | expert""" return user_prefs.set_skill_level(skill_level) def set_editor(self,cmd,prog): "usage: editor " return user_prefs.set_editor(prog) def set_pager(self,cmd,prog): "usage: pager " return user_prefs.set_pager(prog) def set_crm_user(self,cmd,user = ''): "usage: user []" return user_prefs.set_crm_user(user) def set_output(self,cmd,otypes): "usage: output " return user_prefs.set_output(otypes) def set_colors(self,cmd,scheme): "usage: colorscheme " return user_prefs.set_colors(scheme) def set_check_frequency(self,cmd,freq): "usage: check-frequence " return user_prefs.set_check_freq(freq) def set_check_mode(self,cmd,mode): "usage: check-mode " return user_prefs.set_check_mode(mode) def set_sort_elements(self,cmd,opt): "usage: sort-elements {yes|no}" if not verify_boolean(opt): common_err("%s: bad boolean option"%opt) return True return user_prefs.set_sort_elems(opt) def show_options(self,cmd): "usage: show" return user_prefs.write_rc(sys.stdout) def save_options(self,cmd): "usage: save" return user_prefs.save_options(vars.rc_file) def end_game(self, no_questions_asked = False): if no_questions_asked and not options.interactive: self.save_options("save") def listshadows(): return stdout2list("ls @CRM_CONFIG_DIR@ | fgrep shadow. | sed 's/^shadow\.//'") def shadowfile(name): return "@CRM_CONFIG_DIR@/shadow.%s" % name def shadow2doc(name): return file2doc(shadowfile(name)) class CibShadow(UserInterface): ''' CIB shadow management class ''' extcmd = ">/dev/null &1" % self.extcmd) except os.error: no_prog_err(self.extcmd) return False return True def new(self,cmd,name,*args): "usage: new [withstatus] [force]" if not is_filename_sane(name): return False new_cmd = "%s -c '%s'" % (self.extcmd,name) for par in args: if not par in ("force","--force","withstatus"): syntax_err((cmd,name,par), context = 'new') return False if user_prefs.get_force() or "force" in args or "--force" in args: new_cmd = "%s --force" % new_cmd if ext_cmd(new_cmd) == 0: common_info("%s shadow CIB created"%name) self.use("use",name) if "withstatus" in args: cib_status.load("shadow:%s" % name) def delete(self,cmd,name): "usage: delete " if not is_filename_sane(name): return False if vars.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)) == 0: 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 not is_filename_sane(name): return False if ext_cmd("%s -r '%s'" % (self.extcmd,name)) == 0: 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 not is_filename_sane(name): return False if ext_cmd("%s -C '%s' --force" % (self.extcmd,name)) == 0: common_info("commited '%s' shadow CIB to the cluster"%name) wcache.clear() else: common_err("failed to commit the %s shadow CIB"%name) return False def diff(self,cmd): "usage: diff" s = get_stdout(add_sudo("%s -d" % self.extcmd_stdout)) page_string(s) def list(self,cmd): "usage: list" if options.regression_tests: for t in listshadows(): print t else: multicolumn(listshadows()) def _use(self,name,withstatus): # Choose a shadow cib for further changes. If the name # provided is empty, then choose the live (cluster) cib. # Don't allow ' in shadow names if not name or name == "live": os.unsetenv(vars.shadow_envvar) vars.cib_in_use = "" if withstatus: cib_status.load("live") else: os.putenv(vars.shadow_envvar,name) vars.cib_in_use = name if withstatus: cib_status.load("shadow:%s" % name) def use(self,cmd,name = '', withstatus = ''): "usage: use [] [withstatus]" # check the name argument if name and not is_filename_sane(name): return False if name and name != "live": if not os.access(shadowfile(name),os.F_OK): common_err("%s: no such shadow CIB"%name) return False if withstatus and withstatus != "withstatus": syntax_err((cmd,withstatus), context = 'use') return False # If invoked from configure # take special precautions try: prev_level = levels.previous().myname() except: prev_level = '' if prev_level != "cibconfig": self._use(name,withstatus) return True if not cib_factory.has_cib_changed(): self._use(name,withstatus) # new CIB: refresh the CIB factory cib_factory.refresh() return True saved_cib = vars.cib_in_use self._use(name,'') # don't load the status yet if not cib_factory.is_current_cib_equal(silent = True): # user made changes and now wants to switch to a # different and unequal CIB; we refuse to cooperate common_err("the requested CIB is different from the current one") if user_prefs.get_force(): common_info("CIB overwrite forced") elif not ask("All changes will be dropped. Do you want to proceed?"): self._use(saved_cib,'') # revert to the previous CIB return False self._use(name,withstatus) # now load the status too return True def listtemplates(): l = [] for f in os.listdir(vars.tmpl_dir): if os.path.isfile("%s/%s" % (vars.tmpl_dir,f)): l.append(f) return l def listconfigs(): l = [] for f in os.listdir(vars.tmpl_conf_dir): if os.path.isfile("%s/%s" % (vars.tmpl_conf_dir,f)): l.append(f) return l def check_transition(inp,state,possible_l): if not state in possible_l: common_err("input (%s) in wrong state %s" % (inp,state)) return False return True class Template(UserInterface): ''' Configuration templates. ''' def __init__(self): UserInterface.__init__(self) self.help_table = help_sys.load_level("template") self.cmd_table["new"] = (self.new,(2,),1,(null_list,templates_list,loop)) self.cmd_table["load"] = (self.load,(0,1),1,(config_list,)) self.cmd_table["edit"] = (self.edit,(0,1),1,(config_list,)) self.cmd_table["delete"] = (self.delete,(1,2),1,(config_list,)) self.cmd_table["show"] = (self.show,(0,1),0,(config_list,)) self.cmd_table["apply"] = (self.apply,(0,2),1,(config_list_method,config_list)) self.cmd_table["list"] = (self.list,(0,1),0) setup_aliases(self) self.init_dir() self.curr_conf = '' def init_dir(self): '''Create the conf directory, link to templates''' if not os.path.isdir(vars.tmpl_conf_dir): try: os.makedirs(vars.tmpl_conf_dir) except os.error,msg: common_err("makedirs: %s"%msg) return def get_depends(self,tmpl): '''return a list of required templates''' # Not used. May need it later. try: tf = open("%s/%s" % (vars.tmpl_dir, tmpl),"r") except IOError,msg: common_err("open: %s"%msg) return l = [] for s in tf: a = s.split() if len(a) >= 2 and a[0] == '%depends_on': l += a[1:] tf.close() return l def replace_params(self,s,user_data): change = False for i in range(len(s)): word = s[i] for p in user_data: # is parameter in the word? pos = word.find('%' + p) if pos < 0: continue endpos = pos + len('%' + p) # and it isn't part of another word? if re.match("[A-Za-z0-9]", word[endpos:endpos+1]): continue # if the value contains a space or # it is a value of an attribute # put quotes around it if user_data[p].find(' ') >= 0 or word[pos-1:pos] == '=': v = '"' + user_data[p] + '"' else: v = user_data[p] word = word.replace('%' + p, v) change = True # we did replace something if change: s[i] = word if 'opt' in s: if not change: s = [] else: s.remove('opt') return s def generate(self,l,user_data): '''replace parameters (user_data) and generate output ''' l2 = [] for piece in l: piece2 = [] for s in piece: s = self.replace_params(s,user_data) if s: piece2.append(' '.join(s)) if piece2: l2.append(' \\\n\t'.join(piece2)) return '\n'.join(l2) def process(self,config = ''): '''Create a cli configuration from the current config''' try: f = open("%s/%s" % (vars.tmpl_conf_dir, config or self.curr_conf),'r') except IOError,msg: common_err("open: %s"%msg) return '' l = [] piece = [] user_data = {} # states START = 0; PFX = 1; DATA = 2; GENERATE = 3 state = START err_buf.start_tmp_lineno() rc = True for inp in f: err_buf.incr_lineno() if inp.startswith('#'): continue if type(inp) == type(u''): inp = inp.encode('ascii') inp = inp.strip() try: s = shlex.split(inp) except ValueError, msg: common_err(msg) continue while '\n' in s: s.remove('\n') if not s: if state == GENERATE and piece: l.append(piece) piece = [] elif s[0] in ("%name","%depends_on","%suggests"): continue elif s[0] == "%pfx": if check_transition(inp,state,(START,DATA)) and len(s) == 2: pfx = s[1] state = PFX elif s[0] == "%required": if check_transition(inp,state,(PFX,)): state = DATA data_reqd = True elif s[0] == "%optional": if check_transition(inp,state,(PFX,DATA)): state = DATA data_reqd = False elif s[0] == "%%": if state != DATA: common_warn("user data in wrong state %s" % state) if len(s) < 2: common_warn("parameter name missing") elif len(s) == 2: if data_reqd: common_err("required parameter %s not set" % s[1]) rc = False elif len(s) == 3: user_data["%s:%s" % (pfx,s[1])] = s[2] else: common_err("%s: syntax error" % inp) elif s[0] == "%generate": if check_transition(inp,state,(DATA,)): state = GENERATE piece = [] elif state == GENERATE: if s: piece.append(s) else: common_err("<%s> unexpected" % inp) if piece: l.append(piece) err_buf.stop_tmp_lineno() f.close() if not rc: return '' return self.generate(l,user_data) def new(self,cmd,name,*args): "usage: new