Example #1
0
    def test_seqin_and_seqout_connected(self):
        count = 0
        while count < 20 :
            try:
                tree = rtctree.tree.RTCTree(servers='localhost:2809')
                seqin  = tree.get_node(['/', 'localhost:2809','SequenceInComponent0.rtc'])
                seqout = tree.get_node(['/', 'localhost:2809','SequenceInComponent0.rtc'])
                seqin_port1  = seqin.get_port_by_name("Float")
                seqin_port2  = seqin.get_port_by_name("FloatSeq")
                seqout_port1 = seqout.get_port_by_name("Float")
                seqout_port2 = seqout.get_port_by_name("FloatSeq")
                connection1 = seqin_port1.get_connection_by_dest(seqout_port1)
                connection2 = seqin_port2.get_connection_by_dest(seqout_port2)
                print >>sys.stderr, "Connection : ", connection1.properties
                print >>sys.stderr, "Connection : ", connection2.properties
                break
            except:
                pass
            time.sleep(1)
            count += 1

        self.assertTrue(connection1.properties['dataport.data_type']=='IDL:RTC/TimedFloat:1.0')
        self.assertTrue(connection1.properties['dataport.subscription_type']=='new') # Float
        self.assertTrue(connection1.properties['dataport.publisher.push_policy']=='all')

        self.assertTrue(connection2.properties['dataport.data_type']=='IDL:RTC/TimedFloatSeq:1.0')
        self.assertTrue(connection2.properties['dataport.subscription_type']=='flush') # FloatSeq
        self.assertTrue(connection2.properties.get('dataport.publisher.push_policy')==None)
Example #2
0
def delete_object_reference(cmd_path, full_path, options, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.UndeletableObjectError(cmd_path)
    if not path[-1]:
        path = path[:-1]

    # Cannot delete name servers
    if len(path) == 2:
        raise rts_exceptions.UndeletableObjectError(cmd_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    if options.zombies and not tree.is_zombie(path):
        raise rts_exceptions.NotZombieObjectError(cmd_path)

    # There is no point in doing path checks for the path, as the path we are
    # deleting may not be in the tree if it's a zombie. Instead, we need to
    # find its parent, and use that to remove the name.
    parent = tree.get_node(path[:-1])
    if parent.is_manager:
        raise rts_exceptions.ParentNotADirectoryError(cmd_path)
    if not parent.is_directory:
        raise rts_exceptions.ParentNotADirectoryError(cmd_path)
    parent.unbind(path[-1])
Example #3
0
def connect_ports(paths, options, tree=None):
    cmd_paths, fps = list(zip(*paths))
    pathports = [rtctree.path.parse_path(fp) for fp in fps]
    for ii, p in enumerate(pathports):
        if not p[1]:
            raise rts_exceptions.NotAPortError(cmd_paths[ii])
        if not p[0][-1]:
            raise rts_exceptions.NotAPortError(cmd_paths[ii])
    paths, ports = list(zip(*pathports))

    if not tree:
        tree = rtctree.tree.RTCTree(paths=paths, filter=paths)

    port_objs = []
    for ii, p in enumerate(pathports):
        obj = tree.get_node(p[0])
        if not obj:
            raise rts_exceptions.NoSuchObjectError(cmd_paths[ii])
        if obj.is_zombie:
            raise rts_exceptions.ZombieObjectError(cmd_paths[ii])
        if not obj.is_component:
            raise rts_exceptions.NotAComponentError(cmd_paths[ii])
        port_obj = obj.get_port_by_name(p[1])
        if not port_obj:
            raise rts_exceptions.PortNotFoundError(p[0], p[1])
        port_objs.append(port_obj)

    conn_name = options.name if options.name else None
    port_objs[0].connect(port_objs[1:], name=conn_name, id=options.id,
            props=options.properties)
Example #4
0
def manage_fsm(tgt_raw_path, tgt_full_path, command, argument, options, tree=None):
    path, port = rtctree.path.parse_path(tgt_full_path)
    if port:
        raise rts_exceptions.NotAComponentError(tgt_raw_path)
    if not path[-1]:
        raise rts_exceptions.NotAComponentError(tgt_raw_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(path)
    rtc = tree.get_node(path)
    if rtc.is_zombie:
        raise rts_exceptions.ZombieObjectError(path)
    if not rtc.is_component:
        raise rts_exceptions.NotAComponentError(path)

    fsm = rtc.get_extended_fsm_service()

    try:
        cmdfunc = FSM_CMDS[command]
        return cmdfunc(fsm, argument)
    except KeyError:
        raise Exception('unknown command: {0}'.format(command))
Example #5
0
def print_logs(paths, options, tree=None):
    for p in paths:
        path, port = rtctree.path.parse_path(p[1])
        if port:
            raise rts_exceptions.NotAComponentError(p[0])
        if not path[-1]:
            raise rts_exceptions.NotAComponentError(p[0])
        p.append(path)

    if not tree:
        parsed = [p[2] for p in paths]
        tree = rtctree.tree.RTCTree(paths=parsed, filter=parsed)

    filters = ','.join(options.filters)
    ids = []
    try:
        for p in paths:
            if not tree.has_path(p[2]):
                raise rts_exceptions.NoSuchObjectError(p[0])
            rtc = tree.get_node(p[2])
            if rtc.is_zombie:
                raise rts_exceptions.ZombieObjectError(p[0])
            if not rtc.is_component:
                raise rts_exceptions.NotAComponentError(p[0])

            id = rtc.add_logger(log_cb, level=options.level,
                    filters=filters)
            ids.append((rtc, id))
    except rtctree.exceptions.AddLoggerError, e:
        # Remove all the loggers that were added
        for i in ids:
            i[0].remove_logger(i[1])
        # Re-raise
        raise e
Example #6
0
 def test_provider_and_consumer_connected(self):
     count = 0
     while count < 20 :
         try:
             tree = rtctree.tree.RTCTree(servers='localhost:2809')
             provider = tree.get_node(['/', 'localhost:2809','MyServiceProvider0.rtc'])
             consumer = tree.get_node(['/', 'localhost:2809','MyServiceConsumer0.rtc'])
             provider_port = provider.get_port_by_name("MyService")
             consumer_port = consumer.get_port_by_name("MyService")
             connection = provider_port.get_connection_by_dest(consumer_port)
             print >>sys.stderr, "Connection : ", connection.properties
             break
         except:
             pass
         time.sleep(1)
         count += 1
     self.assertTrue(connection.properties['port.port_type']=='CorbaPort')
     self.assertTrue(connection.properties['dataport.subscription_type']=='flush')
Example #7
0
def get_comp_objs(paths, tree):
    objs = {}
    for fp, cp, ports in paths:
        obj = tree.get_node(cp)
        if not obj:
            raise rts_exceptions.NoSuchObjectError(fp)
        if not obj.is_component:
            raise rts_exceptions.NotAComponentError(fp)
        objs[fp] = (obj, ports)
    return objs
Example #8
0
def get_comp_objs(paths, tree):
    cs = {}
    for fp, pp in paths:
        c = tree.get_node(pp)
        if not c:
            raise rts_exceptions.NoSuchObjectError(pp)
        if not c.is_component:
            raise rts_exceptions.NotAComponentError(pp)
        cs[fp] = c
    return cs
Example #9
0
def get_potential_comp_objs(paths, tree):
    objs = {}
    zombies = {}
    for fp, cp, ports in paths:
        obj = tree.get_node(cp)
        if not obj:
            zombies[fp] = (cp[0], ports)
        else:
            objs[fp] = (obj, ports)
    return objs, zombies
Example #10
0
def connect_ports(paths, options, tree=None):
    '''connect_ports

    This should raise exception:

    >>> connect_ports([
    ...   ('Std0.rtc', '/localhost/local.host_cxt/Std0.rtc'),
    ...   ('Output0.rtc:out', '/localhost/local.host_cxt/Output0.rtc:out')
    ... ], {})
    Traceback (most recent call last):
    ...
    NoSourcePortError: No source port specified.

    >>> connect_ports([
    ...   ('Std0.rtc:in', '/localhost/local.host_cxt/Std0.rtc:in'),
    ...   ('Output0.rtc', '/localhost/local.host_cxt/Output0.rtc')
    ... ], {})
    Traceback (most recent call last):
    ...
    NoDestPortError: No destination port specified.
    '''
    cmd_paths, fps = list(zip(*paths))
    pathports = [rtctree.path.parse_path(fp) for fp in fps]
    for ii, p in enumerate(pathports):
        if not p[1]:
            if ii == 0:
                raise rts_exceptions.NoSourcePortError(cmd_paths[ii])
            else:
                raise rts_exceptions.NoDestPortError(cmd_paths[ii])
        if not p[0][-1]:
            raise rts_exceptions.NotAPortError(cmd_paths[ii])
    paths, ports = list(zip(*pathports))

    if not tree:
        tree = rtctree.tree.RTCTree(paths=paths, filter=paths)

    port_objs = []
    for ii, p in enumerate(pathports):
        obj = tree.get_node(p[0])
        if not obj:
            raise rts_exceptions.NoSuchObjectError(cmd_paths[ii])
        if obj.is_zombie:
            raise rts_exceptions.ZombieObjectError(cmd_paths[ii])
        if not obj.is_component:
            raise rts_exceptions.NotAComponentError(cmd_paths[ii])
        port_obj = obj.get_port_by_name(p[1])
        if not port_obj:
            raise rts_exceptions.PortNotFoundError(p[0], p[1])
        port_objs.append(port_obj)

    conn_name = options.name if options.name else None
    port_objs[0].connect(port_objs[1:], name=conn_name, id=options.id,
            props=options.properties)
Example #11
0
def print_logs(paths, options, tree=None):
    global counter
    for p in paths:
        path, port = rtctree.path.parse_path(p[1])
        if port:
            raise rts_exceptions.NotAComponentError(p[0])
        if not path[-1]:
            raise rts_exceptions.NotAComponentError(p[0])
        p.append(path)

    if not tree:
        parsed = [p[2] for p in paths]
        tree = rtctree.tree.RTCTree(paths=parsed, filter=parsed)

    rtcs = []
    event = Event()
    for p in paths:
        if not tree.has_path(p[2]):
            raise rts_exceptions.NoSuchObjectError(p[0])
        rtc = tree.get_node(p[2])
        if rtc.is_zombie:
            raise rts_exceptions.ZombieObjectError(p[0])
        if not rtc.is_component:
            raise rts_exceptions.NotAComponentError(p[0])

        rtc.dynamic = True
        if len(options.filters) == 0 or "ALL" in options.filters:
            for (k, v) in filtermap.items():
                rtc.add_callback(v[0], v[1], [event])
        else:
            for f in options.filters:
                try:
                    v = filtermap[f]
                    rtc.add_callback(v[0], v[1], [event])
                except KeyError:
                    print("Unknown filter: {0}".format(f))
        rtcs.append(rtc)

    # Wait for a keyboard interrupt
    counter = 0
    atexit.register(clean_events, rtcs)
    while True:
        if options.number > 0 and counter >= options.number:
            break
        try:
            event.wait()
        except KeyboardInterrupt:
            break
        event.clear()
    clean_events(rtcs)
Example #12
0
 def test_consumer_activated(self):
     count = 0
     while count < 20 :
         try:
             tree = rtctree.tree.RTCTree(servers='localhost:2809')
             consumer = tree.get_node(['/', 'localhost:2809','MyServiceConsumer0.rtc'])
             print >>sys.stderr, "Consumer : ", consumer, consumer.get_state_string()
             if consumer.state==rtctree.component.Component.ACTIVE:
                 break
         except:
             pass
         time.sleep(1)
         count += 1
     self.assertTrue(consumer.state==rtctree.component.Component.ACTIVE, "State of Consumer is %s"%(consumer.state_string))
Example #13
0
 def test_seqout_activated(self):
     count = 0
     while count < 20 :
         try:
             tree = rtctree.tree.RTCTree(servers='localhost:2809')
             seqout = tree.get_node(['/', 'localhost:2809','SequenceOutComponent0.rtc'])
             print >>sys.stderr, "SeqOut : ", seqout, seqout.get_state_string()
             if seqout.state==rtctree.component.Component.ACTIVE:
                 break
         except:
             pass
         time.sleep(1)
         count += 1
     self.assertTrue(seqout.state==rtctree.component.Component.ACTIVE, "State of SeqOut is %s"%(seqout.state_string))
Example #14
0
def delComponentRef(fullpath, tree=None):
  path, port = rtctree.path.parse_path(fullpath)
  if port: return False
  if not path[-1]: path = path[:-1]
  if len(path) <= 2: return False

  if not tree: tree = getRtcTree(paths=path)
  parent=tree.get_node(path[:-1])

  if parent.is_manager: return False
  if not parent.is_directory: return False

  name = path[-1]
  if name.find('.') == -1 : name=name+'.'

  parent.unbind(name)
  return True
Example #15
0
def print_logs(paths, options, tree=None):
    for p in paths:
        path, port = rtctree.path.parse_path(p[1])
        if port:
            raise rts_exceptions.NotAComponentError(p[0])
        if not path[-1]:
            raise rts_exceptions.NotAComponentError(p[0])
        p.append(path)

    if not tree:
        parsed = [p[2] for p in paths]
        tree = rtctree.tree.RTCTree(paths=parsed, filter=parsed)

    filters = ",".join(options.filters)
    ids = []
    try:
        for p in paths:
            if not tree.has_path(p[2]):
                raise rts_exceptions.NoSuchObjectError(p[0])
            rtc = tree.get_node(p[2])
            if rtc.is_zombie:
                raise rts_exceptions.ZombieObjectError(p[0])
            if not rtc.is_component:
                raise rts_exceptions.NotAComponentError(p[0])

            id = rtc.add_logger(log_cb, level=options.level, filters=filters)
            ids.append((rtc, id))
    except rtctree.exceptions.AddLoggerError as e:
        # Remove all the loggers that were added
        for i in ids:
            i[0].remove_logger(i[1])
        # Re-raise
        raise e

    # Wait for a keyboard interrupt
    try:
        while True:
            if sys.version_info[0] == 3:
                input()
            else:
                raw_input("")
    except KeyboardInterrupt:
        pass
    # Remove all the loggers that were added
    for i in ids:
        i[0].remove_logger(i[1])
Example #16
0
def disconnect_ports(paths, options, tree=None):
    cmd_paths, fps = list(zip(*paths))
    pathports = [rtctree.path.parse_path(fp) for fp in fps]
    for ii, p in enumerate(pathports):
        if not p[1]:
            raise rts_exceptions.NotAPortError(cmd_paths[ii])
        if not p[0][-1]:
            raise rts_exceptions.NotAPortError(cmd_paths[ii])
    paths, ports = list(zip(*pathports))

    if not tree:
        tree = rtctree.tree.RTCTree(paths=paths, filter=paths)

    port_objs = []
    for ii, p in enumerate(pathports):
        obj = tree.get_node(p[0])
        if not obj:
            raise rts_exceptions.NoSuchObjectError(cmd_paths[ii])
        if obj.is_zombie:
            raise rts_exceptions.ZombieObjectError(cmd_paths[ii])
        if not obj.is_component:
            raise rts_exceptions.NotAComponentError(cmd_paths[ii])
        port_obj = obj.get_port_by_name(p[1])
        if not port_obj:
            raise rts_exceptions.PortNotFoundError(p[0], p[1])
        port_objs.append(port_obj)
    if len(port_objs) < 2:
        raise rts_exceptions.NoDestPortError

    if options.id:
        all_conns = port_objs[0].get_connections_by_dests(port_objs[1:])
        conns = []
        for c in all_conns:
            if c.id == options.id:
                conns.append(c)
    else:
        conns = port_objs[0].get_connections_by_dests(port_objs[1:])

    if not conns:
        if options.id:
            raise rts_exceptions.ConnectionIDNotFoundError(options.id,
                    cmd_paths[0])
        else:
            raise rts_exceptions.MultiConnectionNotFoundError
    for c in conns:
        c.disconnect()
Example #17
0
def cat_target(cmd_path, full_path, options, tree=None):
    use_colour = sys.stdout.isatty()

    path, port = rtctree.path.parse_path(full_path)
    if not path[-1]:
        # There was a trailing slash
        trailing_slash = True
        path = path[:-1]
    else:
        trailing_slash = False

    if not tree:
        if options.long > 0:
            # Longer output needs to look around the tree, so don't filter
            filter = []
        else:
            filter = [path]
        tree = rtctree.tree.RTCTree(paths=path, filter=filter)

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    object = tree.get_node(path)
    if port:
        if not object.is_component:
            raise rts_exceptions.NotAComponentError(cmd_path)
        if trailing_slash:
            raise rts_exceptions.NoSuchObjectError(cmd_path)
        p = object.get_port_by_name(port)
        if not p:
            raise rts_exceptions.PortNotFoundError(path, port)
        return format_port(p, object, start_indent=0,
                use_colour=sys.stdout.isatty(), long=options.long)
    else:
        if object.is_component:
            if trailing_slash:
                raise rts_exceptions.NoSuchObjectError(cmd_path)
            return format_component(object, tree, use_colour=sys.stdout.isatty(),
                    long=options.long)
        elif object.is_manager:
            return format_manager(object, use_colour=sys.stdout.isatty(),
                    long=options.long)
        elif object.is_zombie:
            raise rts_exceptions.ZombieObjectError(cmd_path)
        else:
            raise rts_exceptions.NoSuchObjectError(cmd_path)
Example #18
0
def get_comp(cmd_path, full_path, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if port:
        # Can't configure a port
        raise rts_exceptions.NotAComponentError(cmd_path)
    if not path[-1]:
        # There was a trailing slash
        raise rts_exceptions.NoSuchObjectError(cmd_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    comp = tree.get_node(path)
    if not comp:
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if comp.is_zombie:
        raise rts_exceptions.ZombieObjectError(cmd_path)
    if not comp.is_component:
        raise rts_exceptions.NotAComponentError(cmd_path)
    return tree, comp
Example #19
0
def get_manager(cmd_path, full_path, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.NotAManagerError(cmd_path)

    if not path[-1]:
        # There was a trailing slash - ignore it
        path = path[:-1]

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    object = tree.get_node(path)
    if not object:
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if object.is_zombie:
        raise rts_exceptions.ZombieObjectError(cmd_path)
    if not object.is_manager:
        raise rts_exceptions.NotAManagerError(cmd_path)
    return tree, object
Example #20
0
def get_comp(cmd_path, full_path, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if port:
        # Can't configure a port
        raise rts_exceptions.NotAComponentError(cmd_path)
    if not path[-1]:
        # There was a trailing slash
        raise rts_exceptions.NoSuchObjectError(cmd_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    comp = tree.get_node(path)
    if not comp:
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if comp.is_zombie:
        raise rts_exceptions.ZombieObjectError(cmd_path)
    if not comp.is_component:
        raise rts_exceptions.NotAComponentError(cmd_path)
    return tree, comp
Example #21
0
def exit_target(cmd_path, full_path, options, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.NotAComponentError(cmd_path)

    trailing_slash = False
    if not path[-1]:
        raise rts_exceptions.NotAComponentError(cmd_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    object = tree.get_node(path)
    if object.is_zombie:
        raise rts_exceptions.ZombieObjectError(cmd_path)
    if not object.is_component:
        raise rts_exceptions.NotAComponentError(cmd_path)

    object.exit()
Example #22
0
def exit_target(cmd_path, full_path, options, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.NotAComponentError(cmd_path)

    trailing_slash = False
    if not path[-1]:
        raise rts_exceptions.NotAComponentError(cmd_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    object = tree.get_node(path)
    if object.is_zombie:
        raise rts_exceptions.ZombieObjectError(cmd_path)
    if not object.is_component:
        raise rts_exceptions.NotAComponentError(cmd_path)

    object.exit()
Example #23
0
def getComponent(cwd, name=None, tree=None, orb='global'):
  try:
    path = cwd.split("/")
    if not path[-1] :
      path.pop()
      cwd = '/'.join(path)

    rootpath, port = rtctree.path.parse_path(cwd)

    if not tree:
      tree = getRtcTree(paths=rootpath, orb=orb)

    if name :
      rootpath.append(name)

    comp = tree.get_node(rootpath)
  except:
    tree = None
    comp = None

  return tree, comp, port
Example #24
0
def get_docs(cmd_path, full_path, options, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if not path[-1]:
        # There was a trailing slash
        raise rts_exceptions.NotAComponentError(cmd_path)
    if port:
        raise rts_exceptions.NotAComponentError(cmd_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path)

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    object = tree.get_node(path)

    if object.is_component:
        return get_comp_docs(object, tree, options)
    elif object.is_zombie:
        raise rts_exceptions.ZombieObjectError(cmd_path)
    else:
        raise rts_exceptions.NotAComponentError(cmd_path)
Example #25
0
def get_docs(cmd_path, full_path, options, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if not path[-1]:
        # There was a trailing slash
        raise rts_exceptions.NotAComponentError(cmd_path)
    if port:
        raise rts_exceptions.NotAComponentError(cmd_path)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path)

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    object = tree.get_node(path)

    if object.is_component:
        return get_comp_docs(object, tree, options)
    elif object.is_zombie:
        raise rts_exceptions.ZombieObjectError(cmd_path)
    else:
        raise rts_exceptions.NotAComponentError(cmd_path)
Example #26
0
def disconnect_all(cmd_path, full_path, options, tree=None):
    path, port = rtctree.path.parse_path(full_path)
    if not path[-1]:
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    object = tree.get_node(path)
    if not object:
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if not object.is_component:
        raise rts_exceptions.NotAComponentError(cmd_path)

    if port:
        # Disconnect a single port
        port_obj = object.get_port_by_name(port)
        if not port_obj:
            raise rts_exceptions.PortNotFoundError(path, port)
        if options.id:
            conn = port_obj.get_connection_by_id(options.id)
            if not conn:
                raise rts_exceptions.ConnectionIDNotFoundError(options.id,
                        cmd_path)
            conn.disconnect()
        else:
            port_obj.disconnect_all()
    else:
        if options.id:
            # Hunt through the ports for the connection ID
            for p in object.ports:
                conn = p.get_connection_by_id(options.id)
                if not conn:
                    continue
                conn.disconnect()
                return
            raise rts_exceptions.ConnectionIDNotFoundError(options.id,
                    cmd_path)
        else:
            # Disconnect all ports
            object.disconnect_all()
Example #27
0
def get_comp(rtc, tree=None, orb=None):
    '''Get a rtctree.Component object from an rtctree.RTCTree.

    Get the component object by searching the RTCTree for the specified RTC.

    @param rtc Path to the component. This should be in
               the format used by rtctree, i.e. a list of path entries, with
               the first being a /. e.g. ['/', 'localhost', 'comp0.rtc'].
    @param tree An already-populated rtctree.RTCTree object, or None if one
                should be created.
    @param orb An ORB to use if the tree must be created, or None to make one.

    '''
    if not tree:
        tree = rtctree.tree.RTCTree(paths=rtc, orb=orb, filter=[rtc])

    if not tree.has_path(rtc):
        raise rts_exceptions.NoSuchObjectError(rtc)
    comp = tree.get_node(rtc)
    if not comp.is_component:
        raise rts_exceptions.NotAComponentError(rtc)
    return comp
Example #28
0
def get_comp(rtc, tree=None, orb=None):
    '''Get a rtctree.Component object from an rtctree.RTCTree.

    Get the component object by searching the RTCTree for the specified RTC.

    @param rtc Path to the component. This should be in
               the format used by rtctree, i.e. a list of path entries, with
               the first being a /. e.g. ['/', 'localhost', 'comp0.rtc'].
    @param tree An already-populated rtctree.RTCTree object, or None if one
                should be created.
    @param orb An ORB to use if the tree must be created, or None to make one.

    '''
    if not tree:
        tree = rtctree.tree.RTCTree(paths=rtc, orb=orb, filter=[rtc])

    if not tree.has_path(rtc):
        raise rts_exceptions.NoSuchObjectError(rtc)
    comp = tree.get_node(rtc)
    if not comp.is_component:
        raise rts_exceptions.NotAComponentError(rtc)
    return comp
Example #29
0
def alter_component_states(action, paths, options, tree=None):
    cmd_paths, fps = zip(*paths)
    pathports = [rtctree.path.parse_path(fp) for fp in fps]
    for ii, p in enumerate(pathports):
        if p[1]:
            raise rts_exceptions.NotAComponentError(cmd_paths[ii])
        if not p[0][-1]:
            raise rts_exceptions.NotAComponentError(cmd_paths[ii])
    paths, ports = zip(*pathports)

    if not tree:
        tree = rtctree.tree.RTCTree(paths=paths, filter=paths)

    for ii, p in enumerate(paths):
        if not tree.has_path(p):
            raise rts_exceptions.NoSuchObjectError(cmd_paths[ii])
        object_ = tree.get_node(p)
        if object_.is_zombie:
            raise rts_exceptions.ZombieObjectError(cmd_paths[ii])
        if not object_.is_component:
            raise rts_exceptions.NotAComponentError(cmd_paths[ii])
        action(object_, options.ec_index)
Example #30
0
def getComponent(cwd, name=None, tree=None, orb='global'):
    try:
        path = cwd.split("/")
        if not path[-1]:
            path.pop()
            cwd = '/'.join(path)

        rootpath, port = rtctree.path.parse_path(cwd)

        if not tree:
            tree = getRtcTree(paths=rootpath, orb=orb)

        if name:
            rootpath.append(name)

        comp = tree.get_node(rootpath)
    except:
        tree = None
        comp = None
        port = None

    return tree, comp, port
Example #31
0
def list_target(cmd_path, full_path, options, tree=None):
    use_colour = rtctree.utils.colour_supported(sys.stdout)

    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.CannotDoToPortError('list')

    trailing_slash = False
    if not path[-1]:
        # There was a trailing slash
        trailing_slash = True
        path = path[:-1]

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if tree.is_component(path) or tree.is_unknown(path) or \
            tree.is_zombie(path):
        # Path points to a single object: print it like 'ls <file>'.
        if trailing_slash:
            # If there was a trailing slash, complain that the object is not a
            # directory.
            raise rts_exceptions.NoSuchObjectError(cmd_path)
        if options.long:
            return get_node_long_lines([tree.get_node(path)], use_colour)
        else:
            if tree.is_component(path):
                return [path[-1]]
            elif tree.is_zombie(path):
                return [(rtctree.utils.build_attr_string(['faint', 'white'],
                        supported=use_colour) + '*' + path[-1] +
                        rtctree.utils.build_attr_string(['reset'],
                        supported=use_colour))]
            else:
                # Assume unknown
                return [(rtctree.utils.build_attr_string(['faint', 'white'],
                        supported=use_colour) + path[-1] +
                        rtctree.utils.build_attr_string(['reset'],
                        supported=use_colour))]
    elif tree.is_directory(path):
        # If recursing, need to list this directory and all its children
        if options.recurse:
            recurse_root = tree.get_node(path)
            recurse_root_path = recurse_root.full_path_str
            def get_name(node, args):
                if node.full_path_str.startswith(recurse_root_path):
                    result = node.full_path_str[len(recurse_root_path):]
                else:
                    result = node.full_path_str
                return result.lstrip('/')
            dir_names = ['.'] + recurse_root.iterate(get_name,
                    args=options.long, filter=['is_directory'])[1:]
            listings = recurse_root.iterate(list_directory,
                    args=options.long, filter=['is_directory'])
            result = []
            for dir, listing in zip(dir_names, listings):
                if dir == '.':
                    result.append('.:')
                else:
                    result.append('./' + dir + ':')
                result += listing
                result.append('')
            return result
        else:
            dir_node = tree.get_node(path)
            return list_directory(dir_node, options.long)
    else:
        raise rts_exceptions.UnknownObjectError(cmd_path)
Example #32
0
def search(cmd_path, full_path, options, tree=None):
    def get_result(node, args):
        if node.full_path_str.startswith(cmd_path):
            result = node.full_path_str[len(cmd_path):]
            if not result:
                # This will happen if the search root is a component
                return node.name
            return node.full_path_str
        else:
            return node.full_path_str


    def matches_search(node):
        # Filter out types
        if options.type:
            if node.is_component and 'c' not in options.type:
                return False
            if node.is_manager and 'm' not in options.type and \
                    'd' not in options.type:
                return False
            if node.is_nameserver and 'n' not in options.type and \
                    'd' not in options.type:
                return False
            if node.is_directory and 'd' not in options.type and \
                    (not node.is_nameserver and not node.is_manager):
                return False
            if node.is_zombie and 'z' not in options.type:
                return False
        # Filter out depth
        if max_depth > 0 and node.depth > max_depth:
            return False
        if not name_res:
            return True
        # Check for name matches
        for name_re in name_res:
            if name_re.search(node.full_path_str):
                return True
        return False

    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.NotADirectoryError(cmd_path)

    trailing_slash = False
    if not path[-1]:
        # There was a trailing slash
        trailing_slash = True
        path = path[:-1]

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    # Find the root node of the search
    root = tree.get_node(path)
    if not root:
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if root.is_component and trailing_slash:
        raise rts_exceptions.NotADirectoryError(cmd_path)

    if options.max_depth:
        max_depth = options.max_depth + len(path) - 1 # The root is 1-long
    else:
        max_depth = 0

    name_res = []
    for name in options.name:
        # Replace regex special characters
        name = re.escape (name)
        # * goes to .*?
        name = name.replace (r'\*', '.*?')
        # ? goes to .
        name = name.replace (r'\?', r'.')
        name_res.append(re.compile(name))
    for name in options.iname:
        # Replace regex special characters
        name = re.escape (name)
        # * goes to .*?
        name = name.replace (r'\*', '.*?')
        # ? goes to .
        name = name.replace (r'\?', r'.')
        name_res.append(re.compile(name, re.IGNORECASE))

    return root.iterate(get_result, filter=[matches_search])
Example #33
0
    def create_rtcprofile(self, rtc, ns="localhost:2809", verbose=False):
        import rtcprofile

        rtcb = rtcprofile.RTCProfileBuilder()

        import rtctree.path
        import rtctree.tree

        ns_addr = ns
        full_path = "/" + ns_addr + "/" + rtc.rtcprofile.basicInfo.name + "0" + ".rtc"

        path, port = rtctree.path.parse_path(full_path)
        if not path[-1]:
            # There was a trailing slash
            trailing_slash = True
            path = path[:-1]
        filter = []
        tree = None
        import CORBA

        while True:
            try:
                if verbose:
                    sys.stdout.write("# Searching for RTC (%s)\n" % full_path)
                tree = rtctree.tree.RTCTree(paths=path, filter=filter)
                comp = tree.get_node(path)

                if not comp.is_component:
                    sys.stdout.write(" Object is not component\n")
                    return None

                break
            except:
                if verbose:
                    traceback.print_exc()
            time.sleep(1.0)

        rtcb.setBasicInfo(comp.type_name, comp.category, comp.vendor, comp.version, comp.description)
        rtcb.setLanguage(comp.properties["language"])
        keys = [key for key in comp.properties.keys() if key.startswith("conf.default")]
        for key in keys:
            type = "string"
            rtcb.appendConfiguration(type, key.split(".")[-1], comp.properties[key])

        for p in comp.ports:
            if p.porttype == "DataOutPort":
                data_type = p.properties["dataport.data_type"].split(":")[1].replace("/", "::")
                rtcb.appendDataPort("DataOutPort", data_type, p.name)
            elif p.porttype == "DataInPort":
                data_type = p.properties["dataport.data_type"].split(":")[1].replace("/", "::")
                rtcb.appendDataPort("DataInPort", data_type, p.name)
            elif p.porttype == "CorbaPort":
                rtcb.appendServicePort(p.name)
                for i in p.interfaces:
                    path = ""
                    idlFile = ""
                    rtcb.appendServiceInterfaceToServicePort(
                        p.name, path, idlFile, i.type_name, i.polarity_as_string(add_colour=False), i.instance_name
                    )

        return rtcb.buildRTCProfile()
Example #34
0
def find_unique_connectors(tree, components):
    # Finds all unique connections between the components
    data_connectors = []
    seen_svc_connectors = []
    svc_connectors = []
    def in_svc_list(conn):
        for c in svc_connectors:
            if c.connector_id == conn.id:
                return True
        return False

    for comp in components:
        for op in comp.connected_outports:
            for conn in op.connections:
                name = comp.instance_name + '.' + op.name
                source_port = rtsprofile.targets.TargetPort(
                        component_id=make_comp_id(comp),
                        instance_name=comp.instance_name, port_name=name)
                source_port.properties['COMPONENT_PATH_ID'] = \
                        comp.full_path_str[1:]
                # Get the list of ports this connection goes to
                dest_ports = [name for name, p in conn.ports \
                                   if not comp.get_port_by_ref(p.object)]
                if len(dest_ports) == 0:
                    continue
                # Assume the first is the destination and find its component
                path = rtctree.path.parse_path(dest_ports[0])
                dest_comp = tree.get_node(path[0])
                # Now have all the info we need to make the target
                name = dest_comp.instance_name + '.' + path[1]
                dest_port = rtsprofile.targets.TargetPort(
                        component_id=make_comp_id(dest_comp),
                        instance_name=dest_comp.instance_name, port_name=name)
                dest_port.properties['COMPONENT_PATH_ID'] = \
                        dest_comp.full_path_str[1:]
                # Check if the data type is known (see issue 13)
                if 'dataport.data_type' in conn.properties:
                    data_type = conn.properties['dataport.data_type']
                else:
                    data_type = dest_port.port_name
                rts_conn = rtsprofile.port_connectors.DataPortConnector(
                        connector_id=conn.id, name=conn.name,
                        data_type=data_type,
                        interface_type=conn.properties['dataport.interface_type'],
                        data_flow_type=conn.properties['dataport.dataflow_type'],
                        subscription_type=conn.properties['dataport.subscription_type'],
                        source_data_port=source_port,
                        target_data_port=dest_port)
                rts_conn.properties = clean_props(conn.properties)
                data_connectors.append(rts_conn)

        for sp in comp.connected_svcports:
            for conn in sp.connections:
                if in_svc_list(conn):
                    continue;
                seen_svc_connectors.append(conn)
                name = comp.instance_name + '.' + sp.name
                source_port = rtsprofile.targets.TargetPort(
                        component_id=make_comp_id(comp),
                        instance_name=comp.instance_name, port_name=name)
                source_port.properties['COMPONENT_PATH_ID'] = \
                        comp.full_path_str[1:]
                # Get the list of ports this connection goes to
                dest_ports = [name for name, p in conn.ports \
                                   if not comp.get_port_by_ref(p.object)]
                if not dest_ports:
                    # Skip ports with no or unknown connections
                    # (Unknown connections cannot be preserved)
                    # See issue 13
                    continue
                # Assume the first is the destination and find its component
                path = rtctree.path.parse_path(dest_ports[0])
                dest_comp = tree.get_node(path[0])
                # Now have all the info we need to make the target
                name = dest_comp.instance_name + '.' + path[1]
                dest_port = rtsprofile.targets.TargetPort(
                        component_id=make_comp_id(dest_comp),
                        instance_name=dest_comp.instance_name, port_name=name)
                dest_port.properties['COMPONENT_PATH_ID'] = \
                        dest_comp.full_path_str[1:]
                rts_conn = rtsprofile.port_connectors.ServicePortConnector(
                        connector_id=conn.id, name=conn.name,
                        source_service_port=source_port,
                        target_service_port=dest_port)
                rts_conn.properties = clean_props(conn.properties)
                svc_connectors.append(rts_conn)
    return data_connectors, svc_connectors
Example #35
0
def connect_ports(paths, options, tree=None):
    '''connect_ports

    This should raise exception:

    >>> connect_ports([
    ...   ('Std0.rtc', '/localhost/local.host_cxt/Std0.rtc'),
    ...   ('Output0.rtc:out', '/localhost/local.host_cxt/Output0.rtc:out')
    ... ], {})
    Traceback (most recent call last):
    ...
    NoSourcePortError: No source port specified.

    >>> connect_ports([
    ...   ('Std0.rtc:in', '/localhost/local.host_cxt/Std0.rtc:in'),
    ...   ('Output0.rtc', '/localhost/local.host_cxt/Output0.rtc')
    ... ], {})
    Traceback (most recent call last):
    ...
    NoDestPortError: No destination port specified.
    '''
    cmd_paths, fps = list(zip(*paths))
    pathports = [rtctree.path.parse_path(fp) for fp in fps]
    for ii, p in enumerate(pathports):
        if not p[1]:
            if ii == 0:
                raise rts_exceptions.NoSourcePortError(cmd_paths[ii])
            else:
                raise rts_exceptions.NoDestPortError(cmd_paths[ii])
        if not p[0][-1]:
            raise rts_exceptions.NotAPortError(cmd_paths[ii])
    paths, ports = list(zip(*pathports))

    if not tree:
        tree = rtctree.tree.RTCTree(paths=paths, filter=paths)

    port_objs = []
    for ii, p in enumerate(pathports):
        obj = tree.get_node(p[0])
        if not obj:
            raise rts_exceptions.NoSuchObjectError(cmd_paths[ii])
        if obj.is_zombie:
            raise rts_exceptions.ZombieObjectError(cmd_paths[ii])
        if not obj.is_component:
            raise rts_exceptions.NotAComponentError(cmd_paths[ii])
        port_obj = obj.get_port_by_name(p[1])
        if not port_obj:
            raise rts_exceptions.PortNotFoundError(p[0], p[1])
        port_objs.append(port_obj)

    conn_name = options.name if options.name else None

    if options.no_dups:
        for p in port_objs:
            if p.get_connection_by_name(conn_name):
                raise rts_exceptions.DuplicateConnectionNameError(
                    conn_name, p.name)
            if options.id:
                if p.get_connection_by_id(options.id):
                    raise rts_exceptions.DuplicateConnectionIDError(options.id)
        if port_objs[0].get_connections_by_dests(port_objs[1:]):
            raise rts_exceptions.DuplicateConnectionError(cmd_paths)

    port_objs[0].connect(port_objs[1:],
                         name=conn_name,
                         id=options.id,
                         props=options.properties)
Example #36
0
    def create_rtcprofile(self, rtc, ns="localhost:2809", verbose=False):
        import rtcprofile
        rtcb = rtcprofile.RTCProfileBuilder()

        import rtctree.path
        import rtctree.tree
        ns_addr = ns
        full_path = '/' + ns_addr + '/' + rtc.rtcprofile.basicInfo.name + '0' + '.rtc'

        path, port = rtctree.path.parse_path(full_path)
        if not path[-1]:
            # There was a trailing slash
            trailing_slash = True
            path = path[:-1]
        filter = []
        tree = None
        import CORBA
        while True:
            try:
                if verbose:
                    sys.stdout.write('# Searching for RTC (%s)\n' % full_path)
                tree = rtctree.tree.RTCTree(paths=path, filter=filter)
                comp = tree.get_node(path)

                if not comp.is_component:
                    sys.stdout.write(' Object is not component\n')
                    return None

                break
            except:
                if verbose: traceback.print_exc()
            time.sleep(1.0)

        rtcb.setBasicInfo(comp.type_name, comp.category, comp.vendor,
                          comp.version, comp.description)
        rtcb.setLanguage(comp.properties['language'])
        keys = [
            key for key in comp.properties.keys()
            if key.startswith('conf.default')
        ]
        for key in keys:
            type = 'string'
            rtcb.appendConfiguration(type,
                                     key.split('.')[-1], comp.properties[key])

        for p in comp.ports:
            if p.porttype == 'DataOutPort':
                data_type = p.properties['dataport.data_type'].split(
                    ':')[1].replace('/', '::')
                rtcb.appendDataPort('DataOutPort', data_type, p.name)
            elif p.porttype == 'DataInPort':
                data_type = p.properties['dataport.data_type'].split(
                    ':')[1].replace('/', '::')
                rtcb.appendDataPort('DataInPort', data_type, p.name)
            elif p.porttype == 'CorbaPort':
                rtcb.appendServicePort(p.name)
                for i in p.interfaces:
                    path = ""
                    idlFile = ""
                    rtcb.appendServiceInterfaceToServicePort(
                        p.name, path, idlFile, i.type_name,
                        i.polarity_as_string(add_colour=False),
                        i.instance_name)

        return rtcb.buildRTCProfile()
Example #37
0
def find_unique_connectors(tree, components):
    # Finds all unique connections between the components
    data_connectors = []
    seen_svc_connectors = []
    svc_connectors = []

    def in_svc_list(conn):
        for c in svc_connectors:
            if c.connector_id == conn.id:
                return True
        return False

    for comp in components:
        for op in comp.connected_outports:
            for conn in op.connections:
                name = comp.instance_name + '.' + op.name
                source_port = rtsprofile.targets.TargetPort(
                    component_id=make_comp_id(comp),
                    instance_name=comp.instance_name,
                    port_name=name)
                source_port.properties['COMPONENT_PATH_ID'] = \
                        comp.full_path_str[1:]
                # Get the list of ports this connection goes to
                dest_ports = [name for name, p in conn.ports \
                                   if not comp.get_port_by_ref(p.object)]
                if len(dest_ports) == 0:
                    continue
                # Assume the first is the destination and find its component
                path = rtctree.path.parse_path(dest_ports[0])
                dest_comp = tree.get_node(path[0])
                # Now have all the info we need to make the target
                name = dest_comp.instance_name + '.' + path[1]
                dest_port = rtsprofile.targets.TargetPort(
                    component_id=make_comp_id(dest_comp),
                    instance_name=dest_comp.instance_name,
                    port_name=name)
                dest_port.properties['COMPONENT_PATH_ID'] = \
                        dest_comp.full_path_str[1:]
                # Check if the data type is known (see issue 13)
                if 'dataport.data_type' in conn.properties:
                    data_type = conn.properties['dataport.data_type']
                else:
                    data_type = dest_port.port_name
                rts_conn = rtsprofile.port_connectors.DataPortConnector(
                    connector_id=conn.id,
                    name=conn.name,
                    data_type=data_type,
                    interface_type=conn.properties['dataport.interface_type'],
                    data_flow_type=conn.properties['dataport.dataflow_type'],
                    subscription_type=conn.
                    properties['dataport.subscription_type'],
                    source_data_port=source_port,
                    target_data_port=dest_port)
                rts_conn.properties = clean_props(conn.properties)
                data_connectors.append(rts_conn)

        for sp in comp.connected_svcports:
            for conn in sp.connections:
                if in_svc_list(conn):
                    continue
                seen_svc_connectors.append(conn)
                name = comp.instance_name + '.' + sp.name
                source_port = rtsprofile.targets.TargetPort(
                    component_id=make_comp_id(comp),
                    instance_name=comp.instance_name,
                    port_name=name)
                source_port.properties['COMPONENT_PATH_ID'] = \
                        comp.full_path_str[1:]
                # Get the list of ports this connection goes to
                dest_ports = [name for name, p in conn.ports \
                                   if not comp.get_port_by_ref(p.object)]
                if not dest_ports:
                    # Skip ports with no or unknown connections
                    # (Unknown connections cannot be preserved)
                    # See issue 13
                    continue
                # Assume the first is the destination and find its component
                path = rtctree.path.parse_path(dest_ports[0])
                dest_comp = tree.get_node(path[0])
                # Now have all the info we need to make the target
                name = dest_comp.instance_name + '.' + path[1]
                dest_port = rtsprofile.targets.TargetPort(
                    component_id=make_comp_id(dest_comp),
                    instance_name=dest_comp.instance_name,
                    port_name=name)
                dest_port.properties['COMPONENT_PATH_ID'] = \
                        dest_comp.full_path_str[1:]
                rts_conn = rtsprofile.port_connectors.ServicePortConnector(
                    connector_id=conn.id,
                    name=conn.name,
                    source_service_port=source_port,
                    target_service_port=dest_port)
                rts_conn.properties = clean_props(conn.properties)
                svc_connectors.append(rts_conn)
    return data_connectors, svc_connectors
Example #38
0
def main():
    path = ['/', 'localhost']
    tree = rtctree.tree.RTCTree(servers='localhost')
    getNode(tree.get_node(path))
Example #39
0
def manage_composition(tgt_raw_path, tgt_full_path, options, tree=None):
    # Parse paths of components to add/remove
    add_paths = parse_member_paths(options.add)
    rem_paths = parse_member_paths(options.remove)

    # The target, either a manager or a component
    tgt_path, tgt_suffix = rtctree.path.parse_path(tgt_full_path)

    # Make a tree
    if not tree:
        paths = [tgt_path] + [y for x, y, z in add_paths + rem_paths]
        tree = rtctree.tree.RTCTree(paths=paths, filter=paths)
    tgt_obj = tree.get_node(tgt_path)
    if not tgt_obj:
        raise rts_exceptions.NoSuchObjectError(tgt_raw_path)

    # Input sanity check: ensure all components and ports to be added exist
    add_rtcs = get_comp_objs(add_paths, tree)
    for rtc in add_rtcs:
        for p in add_rtcs[rtc][1]:
            if not add_rtcs[rtc][0].get_port_by_name(p):
                raise rts_exceptions.PortNotFoundError(rtc, p)
    # Ensure all ports to be removed that are on components that are alive
    # exist
    rem_rtcs, rem_zombies = get_potential_comp_objs(rem_paths, tree)
    for rtc in rem_rtcs:
        for p in rem_rtcs[rtc][1]:
            if not rem_rtcs[rtc][0].get_port_by_name(p):
                raise rts_exceptions.PortNotFoundError(rtc, p)

    if tgt_obj.is_manager:
        # Create composition
        if not tgt_suffix:
            tgt_suffix = 'CompositeRTC'
            tgt_raw_path += ':' + tgt_suffix
        # Check if this composition already exists
        comp = tgt_obj.get_node([tgt_obj.name, tgt_suffix + '.rtc'])
        if not comp:
            # Cannot remove components when creating a new composition
            if options.remove:
                raise rts_exceptions.CannotRemoveFromNewCompositionError()
            # No composition exists in this manager; make a new one
            if options.verbose:
                print >>sys.stderr, 'Creating new composition {0}'.format(
                        tgt_raw_path)
            comp = create_composition(tgt_obj, tgt_suffix, options.options,
                    options.type)
        elif options.verbose:
            print >>sys.stderr, 'Editing existing composition {0}'.format(
                    tgt_raw_path)
    elif tgt_obj.is_component:
        # Edit composition - there should be no suffix
        if tgt_suffix:
            raise rts_exceptions.NotAComponentError(tgt_raw_path)
        comp = tgt_obj
        if options.verbose:
            print >>sys.stderr, 'Editing existing composition {0}'.format(
                    tgt_raw_path)
    else:
        raise rts_exceptions.NotAComponentOrManagerError(tgt_raw_path)
    if not comp.is_composite:
        raise rts_exceptions.NotACompositeComponentError(tgt_raw_path)

    if add_paths:
        add_to_composition(comp, add_rtcs, tree, options.verbose)
    if rem_paths:
        rem_rtcs.update(rem_zombies)
        rem_from_composition(comp, rem_rtcs, tree, options.verbose)
    if not comp.members[comp.organisations[0].org_id]:
        if options.verbose:
            print >>sys.stderr, 'Composition {0} has no members'.format(
                    tgt_raw_path)
Example #40
0
def manage_composition(tgt_raw_path, tgt_full_path, options, tree=None):
    # Parse paths of components to add/remove
    add_paths = parse_member_paths(options.add)
    rem_paths = parse_member_paths(options.remove)

    # The target, either a manager or a component
    tgt_path, tgt_suffix = rtctree.path.parse_path(tgt_full_path)

    # Make a tree
    if not tree:
        paths = [tgt_path] + [y for x, y, z in add_paths + rem_paths]
        tree = rtctree.tree.RTCTree(paths=paths, filter=paths)
    tgt_obj = tree.get_node(tgt_path)
    if not tgt_obj:
        raise rts_exceptions.NoSuchObjectError(tgt_raw_path)

    # Input sanity check: ensure all components and ports to be added exist
    add_rtcs = get_comp_objs(add_paths, tree)
    for rtc in add_rtcs:
        for p in add_rtcs[rtc][1]:
            if not add_rtcs[rtc][0].get_port_by_name(p):
                raise rts_exceptions.PortNotFoundError(rtc, p)
    # Ensure all ports to be removed that are on components that are alive
    # exist
    rem_rtcs, rem_zombies = get_potential_comp_objs(rem_paths, tree)
    for rtc in rem_rtcs:
        for p in rem_rtcs[rtc][1]:
            if not rem_rtcs[rtc][0].get_port_by_name(p):
                raise rts_exceptions.PortNotFoundError(rtc, p)

    if tgt_obj.is_manager:
        # Create composition
        if not tgt_suffix:
            tgt_suffix = 'CompositeRTC'
            tgt_raw_path += ':' + tgt_suffix
        # Check if this composition already exists
        comp = tgt_obj.get_node([tgt_obj.name, tgt_suffix + '.rtc'])
        if not comp:
            # Cannot remove components when creating a new composition
            if options.remove:
                raise rts_exceptions.CannotRemoveFromNewCompositionError()
            # No composition exists in this manager; make a new one
            if options.verbose:
                print >> sys.stderr, 'Creating new composition {0}'.format(
                    tgt_raw_path)
            comp = create_composition(tgt_obj, tgt_suffix, options.options,
                                      options.type)
        elif options.verbose:
            print >> sys.stderr, 'Editing existing composition {0}'.format(
                tgt_raw_path)
    elif tgt_obj.is_component:
        # Edit composition - there should be no suffix
        if tgt_suffix:
            raise rts_exceptions.NotAComponentError(tgt_raw_path)
        comp = tgt_obj
        if options.verbose:
            print >> sys.stderr, 'Editing existing composition {0}'.format(
                tgt_raw_path)
    else:
        raise rts_exceptions.NotAComponentOrManagerError(tgt_raw_path)
    if not comp.is_composite:
        raise rts_exceptions.NotACompositeComponentError(tgt_raw_path)

    if add_paths:
        add_to_composition(comp, add_rtcs, tree, options.verbose)
    if rem_paths:
        rem_rtcs.update(rem_zombies)
        rem_from_composition(comp, rem_rtcs, tree, options.verbose)
    if not comp.members[comp.organisations[0].org_id]:
        if options.verbose:
            print >> sys.stderr, 'Composition {0} has no members'.format(
                tgt_raw_path)
Example #41
0
def list_target(cmd_path, full_path, options, tree=None):
    use_colour = rtctree.utils.colour_supported(sys.stdout)

    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.CannotDoToPortError('list')

    trailing_slash = False
    if not path[-1]:
        # There was a trailing slash
        trailing_slash = True
        path = path[:-1]

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    if not tree.has_path(path):
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if tree.is_component(path) or tree.is_unknown(path) or \
            tree.is_zombie(path):
        # Path points to a single object: print it like 'ls <file>'.
        if trailing_slash:
            # If there was a trailing slash, complain that the object is not a
            # directory.
            raise rts_exceptions.NoSuchObjectError(cmd_path)
        if options.long:
            return get_node_long_lines([tree.get_node(path)], use_colour)
        else:
            if tree.is_component(path):
                return [path[-1]]
            elif tree.is_zombie(path):
                return [(rtctree.utils.build_attr_string(
                    ['faint', 'white'], supported=use_colour) + '*' +
                         path[-1] + rtctree.utils.build_attr_string(
                             ['reset'], supported=use_colour))]
            else:
                # Assume unknown
                return [(rtctree.utils.build_attr_string(
                    ['faint', 'white'], supported=use_colour) + path[-1] +
                         rtctree.utils.build_attr_string(
                             ['reset'], supported=use_colour))]
    elif tree.is_directory(path):
        # If recursing, need to list this directory and all its children
        if options.recurse:
            recurse_root = tree.get_node(path)
            recurse_root_path = recurse_root.full_path_str

            def get_name(node, args):
                if node.full_path_str.startswith(recurse_root_path):
                    result = node.full_path_str[len(recurse_root_path):]
                else:
                    result = node.full_path_str
                return result.lstrip('/')

            dir_names = ['.'] + recurse_root.iterate(
                get_name, args=options.long, filter=['is_directory'])[1:]
            listings = recurse_root.iterate(list_directory,
                                            args=options.long,
                                            filter=['is_directory'])
            result = []
            for dir, listing in zip(dir_names, listings):
                if dir == '.':
                    result.append('.:')
                else:
                    result.append('./' + dir + ':')
                result += listing
                result.append('')
            return result
        else:
            dir_node = tree.get_node(path)
            return list_directory(dir_node, options.long)
    else:
        raise rts_exceptions.UnknownObjectError(cmd_path)
Example #42
0
def search(cmd_path, full_path, options, tree=None):
    def get_result(node, args):
        if node.full_path_str.startswith(cmd_path):
            result = node.full_path_str[len(cmd_path):]
            if not result:
                # This will happen if the search root is a component
                return node.name
            return node.full_path_str
        else:
            return node.full_path_str


    def matches_search(node):
        # Filter out types
        if options.type:
            if node.is_component and 'c' not in options.type:
                return False
            if node.is_manager and 'm' not in options.type and \
                    'd' not in options.type:
                return False
            if node.is_nameserver and 'n' not in options.type and \
                    'd' not in options.type:
                return False
            if node.is_directory and 'd' not in options.type and \
                    (not node.is_nameserver and not node.is_manager):
                return False
            if node.is_zombie and 'z' not in options.type:
                return False
        # Filter out depth
        if max_depth > 0 and node.depth > max_depth:
            return False
        if not name_res:
            return True
        # Check for name matches
        for name_re in name_res:
            if name_re.search(node.full_path_str):
                return True
        return False

    path, port = rtctree.path.parse_path(full_path)
    if port:
        raise rts_exceptions.NotADirectoryError(cmd_path)

    trailing_slash = False
    if not path[-1]:
        # There was a trailing slash
        trailing_slash = True
        path = path[:-1]

    if not tree:
        tree = rtctree.tree.RTCTree(paths=path, filter=[path])

    # Find the root node of the search
    root = tree.get_node(path)
    if not root:
        raise rts_exceptions.NoSuchObjectError(cmd_path)
    if root.is_component and trailing_slash:
        raise rts_exceptions.NotADirectoryError(cmd_path)

    if options.max_depth:
        max_depth = options.max_depth + len(path) - 1 # The root is 1-long
    else:
        max_depth = 0

    name_res = []
    for name in options.name:
        # Replace regex special characters
        name = re.escape (name)
        # * goes to .*?
        name = name.replace (r'\*', '.*?')
        # ? goes to .
        name = name.replace (r'\?', r'.')
        name_res.append(re.compile(name))
    for name in options.iname:
        # Replace regex special characters
        name = re.escape (name)
        # * goes to .*?
        name = name.replace (r'\*', '.*?')
        # ? goes to .
        name = name.replace (r'\?', r'.')
        name_res.append(re.compile(name, re.IGNORECASE))

    return root.iterate(get_result, filter=[matches_search])