Пример #1
0
def _parse_path(p_names):
  """Parses a list of path names for path keys.

  Args:
    p_names: (list) of path elements, which may include keys.

  Returns:
    a gnmi_pb2.Path object representing gNMI path elements.

  Raises:
    XpathError: Unabled to parse the xpath provided.

    p_names will get passed in a list for examples ['interfaces', 'interface[name=Ethernet1]', 'state', 'counters']

    I think this is where it actually calls everything and returns back paths from the function of what is actually available.

  """
  gnmi_elems = []
  for word in p_names:
    word_search = _RE_PATH_COMPONENT.search(word)
    if not word_search:  # Invalid path specified.
      raise XpathError('xpath component parse error: %s' % word)
    if word_search.group('key') is not None:  # A path key was provided.
      tmp_key = {}
      for x in re.findall(r'\[([^]]*)\]', word):
        tmp_key[x.split("=")[0]] = x.split("=")[-1]
      gnmi_elems.append(gnmi_pb2.PathElem(name=word_search.group(
          'pname'), key=tmp_key))
    else:
      gnmi_elems.append(gnmi_pb2.PathElem(name=word, key={}))
  return gnmi_pb2.Path(elem=gnmi_elems)
Пример #2
0
def _parse_path(p_names):
    """Parses a list of path names for path keys.

  Args:
    p_names: (list) of path elements, which may include keys.

  Returns:
    a gnmi_pb2.Path object representing gNMI path elements.

  Raises:
    XpathError: Unabled to parse the xpath provided.
  """
    gnmi_elems = []
    for word in p_names:
        word_search = _RE_PATH_COMPONENT.search(word)
        if not word_search:  # Invalid path specified.
            raise XpathError('xpath component parse error: %s' % word)
        if word_search.group('key') is not None:  # A path key was provided.
            gnmi_elems.append(
                gnmi_pb2.PathElem(
                    name=word_search.group('pname'),
                    key={word_search.group('key'):
                         word_search.group('value')}))
        else:
            gnmi_elems.append(gnmi_pb2.PathElem(name=word, key={}))
    return gnmi_pb2.Path(elem=gnmi_elems)
Пример #3
0
def ParsePath(p_names: Iterable[Text]) -> gnmi_pb2.Path:
    """Parses a list of path names for path keys.

  Args:
    p_names: (list) of path elements, which may include keys.

  Returns:
    a gnmi_pb2.Path object representing gNMI path elements.

  Raises:
    XpathError: Unabled to parse the xpath provided.
  """
    gnmi_elems = []
    for word in p_names:
        word_search = _RE_PATH_COMPONENT.search(word)
        if not word_search:  # Invalid path specified.
            raise XpathError('xpath component parse error: %s' % word)
        if word_search.group('key') is not None:  # A path key was provided.
            tmp_key = {}
            for x in re.findall(r'\[([^]]*)\]', word):
                tmp_key[x.split('=')[0]] = x.split('=')[-1]
            gnmi_elems.append(
                gnmi_pb2.PathElem(name=word_search.group('pname'),
                                  key=tmp_key))
        else:
            gnmi_elems.append(gnmi_pb2.PathElem(name=word, key={}))
    return gnmi_pb2.Path(elem=gnmi_elems)
Пример #4
0
def GetRequest(stub, path_list):
    """Issue a gNMI GetRequest for the given path."""
    paths = gnmi_pb2.Path(elem=path_list)
    # Metadata is User/pass for our example gNMI Target
    response = stub.Get(gnmi_pb2.GetRequest(path=[paths]),
                        metadata=[('username', 'foo'), ('password', 'bar')])
    return response
Пример #5
0
def path_from_string(path='/'):
    mypath = []

    for e in list_from_path(path):
        eName = e.split("[", 1)[0]
        eKeys = re.findall('\[(.*?)\]', e)
        dKeys = dict(x.split('=', 1) for x in eKeys)
        mypath.append(gnmi_pb2.PathElem(name=eName, key=dKeys))

    return gnmi_pb2.Path(elem=mypath)
Пример #6
0
def _parse_path(p_names):
    gnmi_elems = []
    for word in p_names:
        word_search = _RE_PATH_COMPONENT.search(word)
        if not word_search:  # Invalid path specified.
            raise XpathError('xpath component parse error: %s' % word)
        if word_search.group('key') is not None:  # A path key was provided.
            tmp_key = {}
            for x in re.findall(r'\[([^]]*)\]', word):
                tmp_key[x.split("=")[0]] = x.split("=")[-1]
            gnmi_elems.append(
                gnmi_pb2.PathElem(name=word_search.group('pname'),
                                  key=tmp_key))
        else:
            gnmi_elems.append(gnmi_pb2.PathElem(name=word, key={}))
    return gnmi_pb2.Path(elem=gnmi_elems)
Пример #7
0
                                           metadata=metadata,
                                           timeout=args.timeout)
    #d_print("capabilityResponse: ", capabilityResponse)
    print("Capabilities received.")
    print("Supported models:")
    for m in capabilityResponse.supported_models:
        print(m)
    print("Supported Encodings:")
    for e in capabilityResponse.supported_encodings:
        print(e)
    print("gNMI Version: ", capabilityResponse.gNMI_version)


if args.paths:
    d_print("Creating getRequest...")
    prefix=gnmi_pb2.Path(origin=args.origin)
    # "repeated" PB message fields like "elem" and "path" must be Python iterables
    paths = []
    for path in args.paths:
        pathElems = []
        for elem in path.strip("/").split("/"):
            # TODO: add support for key-value pairs
            pathElems.append(gnmi_pb2.PathElem(name=elem))
        d_print("pathElems=", pathElems)
        paths.append(gnmi_pb2.Path(elem=pathElems))
    d_print("constructed paths=", paths)

    getRequest = gnmi_pb2.GetRequest(prefix=prefix, path=paths, type='ALL',
                                 encoding='JSON_IETF')
    d_print("getRequest=", getRequest)
Пример #8
0
def main():
  argparser = _create_parser()
  args = vars(argparser.parse_args())
  if args['version']:
    print(__version__)
    sys.exit()
  if args['debug']:
    os.environ['GRPC_TRACE'] = 'all'
    os.environ['GRPC_VERBOSITY'] = 'DEBUG'
  mode = args['mode']
  target = args['target']
  port = args['port']
  notls = args['notls']
  get_cert = args['get_cert']
  root_cert = args['root_cert']
  cert_chain = args['cert_chain']
  json_value = args['value']
  private_key = args['private_key']
  xpath = args['xpath']
  prefix = gnmi_pb2.Path(target=args['xpath_target'])
  host_override = args['host_override']
  user = args['username']
  password = args['password']
  form = args['format']
  create_connections = args['create_connections']
  paths = _parse_path(_path_names(xpath))
  kwargs = {'root_cert': root_cert, 'cert_chain': cert_chain,
            'private_key': private_key}
  certs = _open_certs(**kwargs)
  creds = _build_creds(target, port, get_cert, certs, notls)

  if create_connections < -1:
    print('''
          Default number of TCP connections with gNMI server is 1.
          Please use the '--create_connections <positive_number>' to
          create TCP connections or use '--create_connections -1' to
          create infinite TCP connections.
          ''', file=sys.stderr)
    sys.exit(INVALID_GNMI_CLIENT_CONNECTION_NUMBER)

  while True:
    if create_connections > 0:
        create_connections -= 1
    elif create_connections == 0:
        break

    try:
      stub = _create_stub(creds, target, port, host_override)
      if mode == 'get':
        print('Performing GetRequest, encoding=JSON_IETF', 'to', target,
              ' with the following gNMI Path\n', '-'*25, '\n', paths)
        response = _get(stub, paths, user, password, prefix)
        print('The GetResponse is below\n' + '-'*25 + '\n')
        if form == 'protobuff':
          print(response)
        elif response.notification[0].update[0].val.json_ietf_val:
          print(json.dumps(json.loads(response.notification[0].update[0].val.
                                      json_ietf_val), indent=2))
        elif response.notification[0].update[0].val.string_val:
          print(response.notification[0].update[0].val.string_val)
        else:
          print('JSON Format specified, but gNMI Response was not json_ietf_val')
          print(response)
      elif mode == 'set-update':
        print('Performing SetRequest Update, encoding=JSON_IETF', ' to ', target,
              ' with the following gNMI Path\n', '-'*25, '\n', paths, json_value)
        response = _set(stub, paths, 'update', user, password, json_value)
        print('The SetRequest response is below\n' + '-'*25 + '\n', response)
      elif mode == 'set-replace':
        print('Performing SetRequest Replace, encoding=JSON_IETF', ' to ', target,
              ' with the following gNMI Path\n', '-'*25, '\n', paths)
        response = _set(stub, paths, 'replace', user, password, json_value)
        print('The SetRequest response is below\n' + '-'*25 + '\n', response)
      elif mode == 'set-delete':
        print('Performing SetRequest Delete, encoding=JSON_IETF', ' to ', target,
              ' with the following gNMI Path\n', '-'*25, '\n', paths)
        response = _set(stub, paths, 'delete', user, password, json_value)
        print('The SetRequest response is below\n' + '-'*25 + '\n', response)
      elif mode == 'subscribe':
        request_iterator = gen_request(paths, args, prefix)
        subscribe_start(stub, args, request_iterator)
    except grpc.RpcError as err:
      if err.code() == grpc.StatusCode.UNAVAILABLE:
        print("Client receives an exception '{}' indicating gNMI server is shut down and Exiting ..."
              .format(err.details()))
        sys.exit(GNMI_SERVER_UNAVAILABLE)
Пример #9
0
def main():
    argparser = _create_parser()
    args = vars(argparser.parse_args())
    if args['version']:
        print(__version__)
        sys.exit()
    if args['debug']:
        os.environ['GRPC_TRACE'] = 'all'
        os.environ['GRPC_VERBOSITY'] = 'DEBUG'
    mode = args['mode']
    target = args['target']
    port = args['port']
    notls = args['notls']
    get_cert = args['get_cert']
    root_cert = args['root_cert']
    cert_chain = args['cert_chain']
    json_value = args['value']
    private_key = args['private_key']
    xpath = args['xpath']
    prefix = gnmi_pb2.Path(target=args['xpath_target'])
    host_override = args['host_override']
    user = args['username']
    password = args['password']
    form = args['format']
    paths = _parse_path(_path_names(xpath))
    kwargs = {
        'root_cert': root_cert,
        'cert_chain': cert_chain,
        'private_key': private_key
    }
    certs = _open_certs(**kwargs)
    creds = _build_creds(target, port, get_cert, certs, notls)
    stub = _create_stub(creds, target, port, host_override)
    if mode == 'get':
        print('Performing GetRequest, encoding=JSON_IETF', 'to', target,
              ' with the following gNMI Path\n', '-' * 25, '\n', paths)
        response = _get(stub, paths, user, password, prefix)
        print('The GetResponse is below\n' + '-' * 25 + '\n')
        if form == 'protobuff':
            print(response)
        elif response.notification[0].update[0].val.json_ietf_val:
            print(
                json.dumps(json.loads(
                    response.notification[0].update[0].val.json_ietf_val),
                           indent=2))
        elif response.notification[0].update[0].val.string_val:
            print(response.notification[0].update[0].val.string_val)
        else:
            print(
                'JSON Format specified, but gNMI Response was not json_ietf_val'
            )
            print(response)
    elif mode == 'set-update':
        print('Performing SetRequest Update, encoding=JSON_IETF', ' to ',
              target, ' with the following gNMI Path\n', '-' * 25, '\n', paths,
              json_value)
        response = _set(stub, paths, 'update', user, password, json_value)
        print('The SetRequest response is below\n' + '-' * 25 + '\n', response)
    elif mode == 'set-replace':
        print('Performing SetRequest Replace, encoding=JSON_IETF', ' to ',
              target, ' with the following gNMI Path\n', '-' * 25, '\n', paths)
        response = _set(stub, paths, 'replace', user, password, json_value)
        print('The SetRequest response is below\n' + '-' * 25 + '\n', response)
    elif mode == 'set-delete':
        print('Performing SetRequest Delete, encoding=JSON_IETF', ' to ',
              target, ' with the following gNMI Path\n', '-' * 25, '\n', paths)
        response = _set(stub, paths, 'delete', user, password, json_value)
        print('The SetRequest response is below\n' + '-' * 25 + '\n', response)
    elif mode == 'subscribe':
        request_iterator = gen_request(paths, args, prefix)
        subscribe_start(stub, args, request_iterator)