コード例 #1
0
ファイル: util.py プロジェクト: brightmaraba/devnet-work
def one_of(*args):
    "Verifies that only one of the arguments is not None"
    for i, arg in enumerate(args):
        if arg is not None:
            for argh in args[i + 1:]:
                if argh is not None:
                    raise OperationError("Too many parameters")
            else:
                return
    raise OperationError("Insufficient parameters")
コード例 #2
0
def build_filter(spec, capcheck=None):
    type = None
    if isinstance(spec, tuple):
        type, criteria = spec
        if type == "xpath":
            ns, select = criteria
            rep = new_ele_nsmap("filter", ns, type=type)
            rep.attrib["select"] = select
        elif type == "subtree":
            rep = new_ele("filter", type=type)
            rep.append(to_ele(criteria))
        else:
            raise OperationError("Invalid filter type")
    elif isinstance(spec, list):
        rep = new_ele("filter", type="subtree")
        for cri in spec:
            rep.append(to_ele(cri))
    else:

        rep = validated_element(
            spec, ("filter", qualify("filter"),
                   qualify("filter", ns=NETCONF_NOTIFICATION_NS)))
        # results in XMLError: line 105 ncclient/xml_.py - commented by earies - 5/10/13
        #rep = validated_element(spec, ("filter", qualify("filter")),
        #                                attrs=("type",))
        # TODO set type var here, check if select attr present in case of xpath..
    if type == "xpath" and capcheck is not None:
        capcheck(":xpath")
    return rep
コード例 #3
0
 def check_device_params(self):
     value = self.device_params.get('with_ns')
     if value in [True, False]:
         return value
     elif value is None:
         return False
     else:
         raise OperationError('Invalid "with_ns" value: %s' % value)
コード例 #4
0
ファイル: rpc.py プロジェクト: rsmekala/ncclient
 def callback(self, root, raw):
     tag, attrs = root
     if self._device_handler.perform_qualify_check():
         if tag != qualify("rpc-reply"):
             return
     if "message-id" not in attrs:
         # required attribute so raise OperationError
         raise OperationError("Could not find 'message-id' attribute in <rpc-reply>")
     else:
         id = attrs["message-id"]  # get the msgid
         with self._lock:
             try:
                 rpc = self._id2rpc[id]  # the corresponding rpc
                 self.logger.debug("Delivering to %r", rpc)
                 rpc.deliver_reply(raw)
             except KeyError:
                 raise OperationError("Unknown 'message-id': %s" % id)
             # no catching other exceptions, fail loudly if must
             else:
                 # if no error delivering, can del the reference to the RPC
                 del self._id2rpc[id]
コード例 #5
0
    def startElement(self, tag, attributes):
        if tag in ['rpc-reply', 'nc:rpc-reply']:
            if tag == 'nc:rpc-reply':
                RPCTags.RPC_REPLY_END_TAG = "</nc:rpc-reply>"
                RPCTags.RPC_REPLY_START_TAG = "<nc:rpc-reply"
            # in case last rpc called used sax parsing and error'd out
            # without resetting use_filer in endElement rpc-reply check
            with self._lock:
                listeners = list(self._session._listeners)
            rpc_reply_listener = [
                i for i in listeners if isinstance(i, rpc.RPCReplyListener)
            ]
            rpc_msg_id = attributes._attrs['message-id']
            if rpc_msg_id in rpc_reply_listener[0]._id2rpc:
                rpc_reply_handler = rpc_reply_listener[0]._id2rpc[rpc_msg_id]
                if hasattr(rpc_reply_handler, '_filter_xml') and \
                        rpc_reply_handler._filter_xml is not None:
                    self._cur = self._root = _get_sax_parser_root(
                        rpc_reply_handler._filter_xml)
                else:
                    raise SAXFilterXMLNotFoundError(rpc_reply_handler)
            else:
                raise OperationError("Unknown 'message-id': %s" % rpc_msg_id)
        if self._ignoretag is not None:
            return

        if self._cur == self._root and self._cur.tag == tag:
            node = self._root
        else:
            node = self._cur.find(tag, namespaces=RPCTags.NAMESPACES)

        if self._validate_reply_and_sax_tag:
            if tag != self._root.tag:
                self._write_buffer(tag, format_str='<{}>\n')
                self._cur = E(tag, self._cur)
            else:
                self._write_buffer(tag, format_str='<{}{}>', **attributes)
                self._cur = node
                self._currenttag = tag
            self._validate_reply_and_sax_tag = False
            self._defaulttags.append(tag)
        elif node is not None:
            self._write_buffer(tag, format_str='<{}{}>', **attributes)
            self._cur = node
            self._currenttag = tag
        elif tag in ['rpc-reply', 'nc:rpc-reply']:
            self._write_buffer(tag, format_str='<{}{}>', **attributes)
            self._defaulttags.append(tag)
            self._validate_reply_and_sax_tag = True
        else:
            self._currenttag = None
            self._ignoretag = tag
コード例 #6
0
def parse_datetime(time_str):
    """Returns a datetime for a RFC3339 time representation

    The returned datetime is timezone aware. This method is required to handle
    the finer aspects of RFC3339 - fraction seconds and the timezone Z
    representation.
    """
    match = _datetime_re.match(time_str)
    if match is None:
        raise OperationError(
            'Invalid Internet Time Format {}'.format(time_str))

    yyyy, mm, dd, hh, mins, sec, _, ms, utc_z, _, tz_sign, tz_hh, tz_min = match.groups(
    )
    micro_sec = 0
    if ms:
        micro_sec = int(float('0.' + ms) * 1000000)

    if utc_z in ['z', 'Z']:
        tz = datetime.timezone.utc
    else:
        tz_hh = int(tz_hh) if tz_hh is not None else 0
        tz_min = int(tz_min) if tz_min is not None else 0
        if tz_hh > 24 or tz_min > 60:
            raise OperationError(
                'Invalid Internet Time Offset {}'.format(time_str))

        tz_offset = tz_hh * 60 + tz_min
        if tz_offset == 0:
            tz = datetime.timezone.utc
        else:
            if tz_sign == '-':
                tz_offset = -tz_offset
            tz = datetime.timezone(datetime.timedelta(minutes=tz_offset))

    return datetime.datetime(int(yyyy), int(mm), int(dd), int(hh), int(mins),
                             int(sec), micro_sec, tz)
コード例 #7
0
ファイル: rpc.py プロジェクト: nwautomator/ncclient
 def __init__(self, raw, errs=None):
     self._raw = raw
     if errs is None:
         # Single RPCError
         self._errlist = None
         for attr in six.itervalues(RPCError.tag_to_attr):
             setattr(self, attr, None)
         for subele in raw:
             attr = RPCError.tag_to_attr.get(subele.tag, None)
             if attr is not None:
                 setattr(self, attr,
                         subele.text if attr != "_info" else to_xml(subele))
         if self.message is not None:
             OperationError.__init__(self, self.message)
         else:
             OperationError.__init__(self, self.to_dict())
     else:
         # Multiple errors returned. Errors is a list of RPCError objs
         self._errlist = errs
         errlist = []
         for err in errs:
             if err.severity:
                 errsev = err.severity
             else:
                 errsev = 'undefined'
             if err.message:
                 errmsg = err.message
             else:
                 errmsg = 'not an error message in the reply. Enable debug'
             errordict = {"severity": errsev, "message": errmsg}
             errlist.append(errordict)
         # We are interested in the severity and the message
         self._severity = 'warning'
         self._message = "\n".join([
             "%s: %s" % (err['severity'].strip(), err['message'].strip())
             for err in errlist
         ])
         self.errors = errs
         has_error = filter(lambda higherr: higherr['severity'] == 'error',
                            errlist)
         if has_error:
             self._severity = 'error'
         OperationError.__init__(self, self.message)
コード例 #8
0
ファイル: rpc.py プロジェクト: siming85/ncclient
 def __init__(self, raw, errs=None):
     self._raw = raw
     if errs is None:
         # Single RPCError
         for attr in six.itervalues(RPCError.tag_to_attr):
             setattr(self, attr, None)
         for subele in raw:
             attr = RPCError.tag_to_attr.get(subele.tag, None)
             if attr is not None:
                 setattr(self, attr, subele.text if attr != "_info" else to_xml(subele) )
         if self.message is not None:
             OperationError.__init__(self, self.message)
         else:
             OperationError.__init__(self, self.to_dict())
     else:
         # Multiple errors returned. Errors is a list of RPCError objs
         errlist = []
         for err in errs:
             if err.severity:
                 errsev = err.severity
             else:
                 errsev = 'undefined'
             if err.message:
                 errmsg = err.message
             else:
                 errmsg = 'not an error message in the reply. Enable debug'
             errordict = {"severity": errsev, "message":errmsg}
             errlist.append(errordict)
         # We are interested in the severity and the message
         self._severity = 'warning'
         self._message = "\n".join(["%s: %s" %(err['severity'].strip(), err['message'].strip()) for err in errlist])
         self.errors = errs
         has_error = filter(lambda higherr: higherr['severity'] == 'error', errlist)
         if has_error:
             self._severity = 'error'
         OperationError.__init__(self, self.message)
コード例 #9
0
def validate_args(arg_name, value, args_list):
    # this is a common method, which used to check whether a value is in args_list
    if value not in args_list:
        raise OperationError('Invalid value "%s" in "%s" element' %
                             (value, arg_name))
    return True