예제 #1
0
def main():
    global idl
    argv = sys.argv
    n_args = 2

    if len(argv) != n_args:
        hostname = MGMT_INTF_NULL_VAL
    else:
        hostname = argv[1]

    # Locate default config if it exists
    schema_helper = ovs.db.idl.SchemaHelper(location=OVS_SCHEMA)
    schema_helper.register_columns(SYSTEM_TABLE, ["cur_cfg"])
    schema_helper.register_columns(SYSTEM_TABLE, ["mgmt_intf_status"])

    idl = ovs.db.idl.Idl(DEF_DB, schema_helper)

    seqno = idl.change_seqno    # Sequence number when we last processed the db

    # Wait until the ovsdb sync up.
    while (seqno == idl.change_seqno):
        idl.run()
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()

    wait_for_config_complete(idl)

    update_mgmt_intf_status_hostname(hostname)

    idl.close()
예제 #2
0
def copy_running_startup():
    cfg = cfgdb.Cfgdb()
    manager = OvsdbConnectionManager(settings.get('ovs_remote'),
                                     settings.get('ovs_schema'))
    manager.start()
    idl = manager.idl

    init_seq_no = idl.change_seqno
    # Wait until the connection is ready
    while True:
        idl.run()
        # print self.idl.change_seqno
        if init_seq_no != idl.change_seqno:
            break
        time.sleep(1)

    restschema = restparser.parseSchema(settings.get('ext_schema'))

    run_config_util = RunConfigUtil(idl, restschema)
    config = run_config_util.get_running_config()

    cfg.config = ovs.json.to_string(config)
    cfg.type = "startup"
    row, tbl_found = cfg.find_row_by_type("startup")
    if tbl_found:
        cfg.update_row(row)
    else:
        cfg.insert_row()

    cfg.close()
    return True
예제 #3
0
def ops_ntpd_provision_ntpd_daemon():
    '''
       This function provisions NTPD default config and launches the
       NTPD daemon
    '''
    global idl
    global seqno
    global ntpd_started
    global ntpd_info
    idl.run()
    if seqno != idl.change_seqno:
        vlog.dbg("ops-ntpd-debug - seqno change from %d to %d " %
                 (seqno, idl.change_seqno))
        seqno = idl.change_seqno
        # Check if system is configured and startup config is restored
        if ops_ntpd_check_system_status() is False:
            return
        else:
            # Get the default ntp config, keys file
            ntpd_info = ops_ntpd_setup_ntpd_default_config()
            # Kill zombie ntpd process and Start a new ntpd daemon
            ops_ntpd_cleanup_ntpd_processes()
            ops_ntpd_start_ntpd(ntpd_info)
            ops_ntpd_init_transaction_mgr()
            # Get the ntp config
            time.sleep(5)
            ops_ntpd_check_updates_from_ovsdb()
            ntpd_started = True
예제 #4
0
def bufmond_run():

    global idl
    global seqno

    idl.run()

    if seqno != idl.change_seqno:
        bufmond_reconfigure()
        seqno = idl.change_seqno
예제 #5
0
def bufmond_run():

    global idl
    global seqno

    idl.run()

    if seqno != idl.change_seqno:
        bufmond_reconfigure()
        seqno = idl.change_seqno
예제 #6
0
def supportability_run():

    global idl
    global seqno

    idl.run()

    if seqno != idl.change_seqno:
        supportability_reconfigure()
        seqno = idl.change_seqno
예제 #7
0
def discover_system_id(idl):
    system_id = None

    while system_id is None and idl._session.is_connected():
        idl.run()
        openvswitch = idl.tables['Open_vSwitch'].rows

        if openvswitch:
            row = openvswitch.get(list(openvswitch.keys())[0])
            system_id = row.external_ids.get('system-id')

    return system_id
예제 #8
0
파일: client.py 프로젝트: John-Lin/ryu
def discover_system_id(idl):
    system_id = None

    while system_id is None and idl._session.is_connected():
        idl.run()
        openvswitch = idl.tables['Open_vSwitch'].rows

        if openvswitch:
            row = openvswitch.get(list(openvswitch.keys())[0])
            system_id = row.external_ids.get('system-id')

    return system_id
예제 #9
0
def wait_for_config_complete(idl):

    system_is_configured = 0
    while system_is_configured == 0:
        for ovs_rec in idl.tables[SYSTEM_TABLE].rows.itervalues():
            if ovs_rec.cur_cfg is not None and ovs_rec.cur_cfg != 0:
                system_is_configured = ovs_rec.cur_cfg
                break

        poller = ovs.poller.Poller()
        idl.run()
        idl.wait(poller)
        poller.block()
def aaa_util_run():
    '''
    Run idl, and call reconfigure function when there is a change in DB \
   sequence number. \
    '''

    global idl
    global seqno

    idl.run()

    if seqno != idl.change_seqno:
        aaa_util_reconfigure()
        seqno = idl.change_seqno

    return
예제 #11
0
파일: openvswitch.py 프로젝트: 42qu/vps
    def find(self, columns, table, cond=None):
        """ which only works in main thread, depends on signal """
        schema_file = "%s/vswitch.ovsschema" % ovs.dirs.PKGDATADIR
        try:
            from ovs.db.idl import SchemaHelper
            schema_helper = SchemaHelper(schema_file)
            schema_helper.register_all()
            schema = schema_helper.get_idl_schema()
            self._check_column(schema, columns, table, cond)
            idl = ovs.db.idl.Idl(self.sock, schema_helper)
        except ImportError:
            schema = ovs.db.schema.DbSchema.from_json(
                ovs.json.from_file(schema_file))
            # check schema
            self._check_column(schema, columns, table, cond)
            idl = ovs.db.idl.Idl(self.sock, schema)

        seqno = idl.change_seqno
        while True:
            idl.run()
            if seqno == idl.change_seqno:
                poller = ovs.poller.Poller()
                idl.wait(poller)
                poller.block()
                continue
            break
        results = list()

        def __append_row(results, row):
            result = dict()
            for column_name in columns:
                result[column_name] = self._get_row_val(row, column_name)
            results.append(result)
            return

        for row in idl.tables[table].rows.itervalues():
            match = True
            if cond:
                for k, v in cond.iteritems():
                    if self._get_row_val(row, k) != v:
                        match = False
                        break
            if match:
                __append_row(results, row)
        idl.close()
        return results
예제 #12
0
 def wait_for_db_change(idl):
     seq = idl.change_seqno
     stop = time.time() + 10
     while idl.change_seqno == seq and not idl.run():
         poller = Poller()
         idl.wait(poller)
         poller.block()
         if time.time() >= stop:
             raise Exception('Retry Timeout')
예제 #13
0
파일: test-ovsdb.py 프로젝트: 18SUN/ovs
def do_idl_passive(schema_file, remote, *commands):
    symtab = {}
    step = 0
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)
    schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)

    while idl._session.rpc is None:
        idl.run()

    rpc = idl._session.rpc

    print_idl(idl, step)
    step += 1

    for command in commands:
        json = ovs.json.from_string(command)
        if isinstance(json, six.string_types):
            sys.stderr.write("\"%s\": %s\n" % (command, json))
            sys.exit(1)
        json = substitute_uuids(json, symtab)
        request = ovs.jsonrpc.Message.create_request("transact", json)
        error, reply = rpc.transact_block(request)
        if error:
            sys.stderr.write("jsonrpc transaction failed: %s"
                             % os.strerror(error))
            sys.exit(1)
        elif reply.error is not None:
            sys.stderr.write("jsonrpc transaction failed: %s"
                             % reply.error)
            sys.exit(1)

        sys.stdout.write("%03d: " % step)
        sys.stdout.flush()
        step += 1
        if reply.result is not None:
            parse_uuids(reply.result, symtab)
        reply.id = None
        sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
        sys.stdout.flush()

    idl.close()
    print("%03d: done" % step)
예제 #14
0
def do_idl_passive(schema_file, remote, *commands):
    symtab = {}
    step = 0
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)
    schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)

    while idl._session.rpc is None:
        idl.run()

    rpc = idl._session.rpc

    print_idl(idl, step)
    step += 1

    for command in commands:
        json = ovs.json.from_string(command)
        if isinstance(json, str):
            sys.stderr.write("\"%s\": %s\n" % (command, json))
            sys.exit(1)
        json = substitute_uuids(json, symtab)
        request = ovs.jsonrpc.Message.create_request("transact", json)
        error, reply = rpc.transact_block(request)
        if error:
            sys.stderr.write("jsonrpc transaction failed: %s\n"
                             % os.strerror(error))
            sys.exit(1)
        elif reply.error is not None:
            sys.stderr.write("jsonrpc transaction failed: %s\n"
                             % reply.error)
            sys.exit(1)

        sys.stdout.write("%03d: " % step)
        sys.stdout.flush()
        step += 1
        if reply.result is not None:
            parse_uuids(reply.result, symtab)
        reply.id = None
        sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
        sys.stdout.flush()

    idl.close()
    print("%03d: done" % step)
예제 #15
0
def main():
    global idl
    argv = sys.argv
    n_args = 2
    dns_1 = ''
    dns_2 = ''
    domainname = ''

    if argv[1] != 'None':
        hostname = argv[1]
    else:
        hostname = MGMT_INTF_NULL_VAL

    dns_1 = argv[2]
    dns_2 = argv[3]
    if argv[4] != 'None':
        domainname = argv[4]
    else:
        domainname = MGMT_INTF_NULL_VAL

    # Locate default config if it exists
    schema_helper = ovs.db.idl.SchemaHelper(location=OVS_SCHEMA)
    schema_helper.register_columns(SYSTEM_TABLE, ["cur_cfg"])
    schema_helper.register_columns(SYSTEM_TABLE, ["mgmt_intf_status"])

    idl = ovs.db.idl.Idl(DEF_DB, schema_helper)

    seqno = idl.change_seqno  # Sequence number when we last processed the db

    # Wait until the ovsdb sync up.
    while (seqno == idl.change_seqno):
        idl.run()
        if seqno == idl.change_seqno:
            poller = ovs.poller.Poller()
            idl.wait(poller)
            poller.block()

    wait_for_config_complete(idl)

    update_mgmt_intf_status(hostname, dns_1, dns_2, domainname)

    idl.close()
예제 #16
0
def dnsmasq_run():

    global idl
    global seqno
    global dnsmasq_started

    idl.run()

    if seqno != idl.change_seqno:
        vlog.info("dhcp_tftp_debug - seqno change from %d to %d " %
                  (seqno, idl.change_seqno))
        seqno = idl.change_seqno

        # Check if system is configured and startup config is restored
        if system_is_configured() == False:
            return
        else:
            # Get the dhcp-tftp config
            dhcp_tftp_get_config()

            # Start the dnsmasq
            dnsmasq_start_process()
            dnsmasq_started = True
예제 #17
0
def dnsmasq_run():

    global idl
    global seqno
    global dnsmasq_started

    idl.run()

    if seqno != idl.change_seqno:
        vlog.info("dhcp_tftp_debug - seqno change from %d to %d "
                  % (seqno, idl.change_seqno))
        seqno = idl.change_seqno

        # Check if system is configured and startup config is restored
        if system_is_configured() == False:
            return
        else:
            # Get the dhcp-tftp config
            dhcp_tftp_get_config()

            # Start the dnsmasq
            dnsmasq_start_process()
            dnsmasq_started = True
예제 #18
0
def ops_ntpd_init():
    '''
       This function
       - intiializes with OVSDB
       - provisions the NTPD daemon
       - keeps checking of configuration changes in OVSDB
    '''
    global exiting
    global idl
    global seqno
    global ntpd_started

    parser = argparse.ArgumentParser()
    parser.add_argument('-d',
                        '--database',
                        metavar="DATABASE",
                        help="A socket on which ovsdb-server is listening.",
                        dest='database')

    ovs.vlog.add_args(parser)
    ovs.daemon.add_args(parser)
    args = parser.parse_args()
    ovs.vlog.handle_args(args)
    ovs.daemon.handle_args(args)

    if args.database is None:
        remote = def_db
    else:
        remote = args.database
    ops_ntpd_setup_ovsdb_monitoring(remote)
    ovs.daemon.daemonize()
    ovs.daemon.set_pidfile(None)
    ovs.daemon._make_pidfile()
    ovs.unixctl.command_register("exit", "", 0, 0,
                                 ops_ntpd_connection_exit_handler, None)
    error, unixctl_server = ovs.unixctl.server.UnixctlServer.create(None)

    if error:
        ovs.util.ovs_fatal(
            error, "ops_ntpd_helper: could not create "
            "unix-ctl server", vlog)
    while ntpd_started is False:
        ops_ntpd_provision_ntpd_daemon()
        time.sleep(2)

    # Event logging init for NTP
    event_log_init("NTP")

    # Diags callback init for NTP
    ops_diagdump.init_diag_dump_basic(ops_ntpd_diagnostics_handler)

    seqno = idl.change_seqno  # Sequence number when we last processed the db
    exiting = False
    while not exiting:
        unixctl_server.run()
        if exiting:
            break
        idl.run()
        if seqno == idl.change_seqno:
            ops_ntpd_sync_updates_to_ovsdb()
            time.sleep(2)
        else:
            vlog.dbg("ops-ntpd-debug main - seqno change from %d to %d " %
                     (seqno, idl.change_seqno))
            ops_ntpd_check_updates_from_ovsdb()
            seqno = idl.change_seqno

    # Daemon exit
    unixctl_server.close()
    if ntpd_process is not None:
        vlog.dbg("ops-ntpd-debug - killing ntpd")
    idl.close()
    ops_ntpd_cleanup_ntpd_processes()
    ops_ntpd_shutdown_transaction_mgr()
예제 #19
0
def do_idl(schema_file, remote, *commands):
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)
    schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)

    if commands:
        error, stream = ovs.stream.Stream.open_block(
            ovs.stream.Stream.open(remote))
        if error:
            sys.stderr.write("failed to connect to \"%s\"" % remote)
            sys.exit(1)
        rpc = ovs.jsonrpc.Connection(stream)
    else:
        rpc = None

    symtab = {}
    seqno = 0
    step = 0
    for command in commands:
        if command.startswith("+"):
            # The previous transaction didn't change anything.
            command = command[1:]
        else:
            # Wait for update.
            while idl.change_seqno == seqno and not idl.run():
                rpc.run()

                poller = ovs.poller.Poller()
                idl.wait(poller)
                rpc.wait(poller)
                poller.block()

            print_idl(idl, step)
            step += 1

        seqno = idl.change_seqno

        if command == "reconnect":
            print("%03d: reconnect" % step)
            sys.stdout.flush()
            step += 1
            idl.force_reconnect()
        elif not command.startswith("["):
            idl_set(idl, command, step)
            step += 1
        else:
            json = ovs.json.from_string(command)
            if type(json) in [str, unicode]:
                sys.stderr.write("\"%s\": %s\n" % (command, json))
                sys.exit(1)
            json = substitute_uuids(json, symtab)
            request = ovs.jsonrpc.Message.create_request("transact", json)
            error, reply = rpc.transact_block(request)
            if error:
                sys.stderr.write("jsonrpc transaction failed: %s" %
                                 os.strerror(error))
                sys.exit(1)
            elif reply.error is not None:
                sys.stderr.write("jsonrpc transaction failed: %s" %
                                 reply.error)
                sys.exit(1)

            sys.stdout.write("%03d: " % step)
            sys.stdout.flush()
            step += 1
            if reply.result is not None:
                parse_uuids(reply.result, symtab)
            reply.id = None
            sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
            sys.stdout.flush()

    if rpc:
        rpc.close()
    while idl.change_seqno == seqno and not idl.run():
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()
    print_idl(idl, step)
    step += 1
    idl.close()
    print("%03d: done" % step)
예제 #20
0
def do_idl(schema_file, remote, *commands):
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)
    track_notify = False

    if remote.startswith("ssl:"):
        if len(commands) < 3:
            sys.stderr.write("SSL connection requires private key, "
                             "certificate for private key, and peer CA "
                             "certificate as arguments\n")
            sys.exit(1)
        ovs.stream.Stream.ssl_set_private_key_file(commands[0])
        ovs.stream.Stream.ssl_set_certificate_file(commands[1])
        ovs.stream.Stream.ssl_set_ca_cert_file(commands[2])
        commands = commands[3:]

    if commands and commands[0] == "track-notify":
        commands = commands[1:]
        track_notify = True

    if commands and commands[0].startswith("?"):
        readonly = {}
        for x in commands[0][1:].split("?"):
            readonly = []
            table, columns = x.split(":")
            columns = columns.split(",")
            for index, column in enumerate(columns):
                if column[-1] == '!':
                    columns[index] = columns[index][:-1]
                    readonly.append(columns[index])
            schema_helper.register_columns(table, columns, readonly)
        commands = commands[1:]
    else:
        schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)
    if "simple3" in idl.tables:
        idl.index_create("simple3", "simple3_by_name")

    if commands:
        remotes = remote.split(',')
        stream = None
        for r in remotes:
            error, stream = ovs.stream.Stream.open_block(
                ovs.stream.Stream.open(r))
            if not error and stream:
                break
            stream = None

        if not stream:
            sys.stderr.write("failed to connect to \"%s\"" % remote)
            sys.exit(1)
        rpc = ovs.jsonrpc.Connection(stream)
    else:
        rpc = None

    symtab = {}
    seqno = 0
    step = 0

    def mock_notify(event, row, updates=None):
        output = "%03d: " % step
        output += "event:" + str(event) + ", row={"
        output += get_simple_table_printable_row(row) + "}, updates="
        if updates is None:
            output += "None"
        else:
            output += "{" + get_simple_table_printable_row(updates) + "}"

        output += '\n'
        sys.stdout.write(output)
        sys.stdout.flush()

    if track_notify and "simple" in idl.tables:
        idl.notify = mock_notify

    commands = list(commands)
    if len(commands) >= 1 and "condition" in commands[0]:
        update_condition(idl, commands.pop(0))
        sys.stdout.write("%03d: change conditions\n" % step)
        sys.stdout.flush()
        step += 1

    for command in commands:
        if command.startswith("+"):
            # The previous transaction didn't change anything.
            command = command[1:]
        else:
            # Wait for update.
            while idl.change_seqno == seqno and not idl.run():
                rpc.run()

                poller = ovs.poller.Poller()
                idl.wait(poller)
                rpc.wait(poller)
                poller.block()

            print_idl(idl, step)
            step += 1

        seqno = idl.change_seqno

        if command == "reconnect":
            print("%03d: reconnect" % step)
            sys.stdout.flush()
            step += 1
            idl.force_reconnect()
        elif "condition" in command:
            update_condition(idl, command)
            sys.stdout.write("%03d: change conditions\n" % step)
            sys.stdout.flush()
            step += 1
        elif not command.startswith("["):
            idl_set(idl, command, step)
            step += 1
        else:
            json = ovs.json.from_string(command)
            if isinstance(json, six.string_types):
                sys.stderr.write("\"%s\": %s\n" % (command, json))
                sys.exit(1)
            json = substitute_uuids(json, symtab)
            request = ovs.jsonrpc.Message.create_request("transact", json)
            error, reply = rpc.transact_block(request)
            if error:
                sys.stderr.write("jsonrpc transaction failed: %s\n" %
                                 os.strerror(error))
                sys.exit(1)
            elif reply.error is not None:
                sys.stderr.write("jsonrpc transaction failed: %s\n" %
                                 reply.error)
                sys.exit(1)

            sys.stdout.write("%03d: " % step)
            sys.stdout.flush()
            step += 1
            if reply.result is not None:
                parse_uuids(reply.result, symtab)
            reply.id = None
            sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
            sys.stdout.flush()

    if rpc:
        rpc.close()
    while idl.change_seqno == seqno and not idl.run():
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()
    print_idl(idl, step)
    step += 1
    idl.close()
    print("%03d: done" % step)
예제 #21
0
파일: test-ovsdb.py 프로젝트: 18SUN/ovs
def do_idl(schema_file, remote, *commands):
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)
    if commands and commands[0].startswith("?"):
        readonly = {}
        for x in commands[0][1:].split("?"):
            readonly = []
            table, columns = x.split(":")
            columns = columns.split(",")
            for index, column in enumerate(columns):
                if column[-1] == '!':
                    columns[index] = columns[index][:-1]
                    readonly.append(columns[index])
            schema_helper.register_columns(table, columns, readonly)
        commands = commands[1:]
    else:
        schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)

    if commands:
        error, stream = ovs.stream.Stream.open_block(
            ovs.stream.Stream.open(remote))
        if error:
            sys.stderr.write("failed to connect to \"%s\"" % remote)
            sys.exit(1)
        rpc = ovs.jsonrpc.Connection(stream)
    else:
        rpc = None

    symtab = {}
    seqno = 0
    step = 0
    for command in commands:
        if command.startswith("+"):
            # The previous transaction didn't change anything.
            command = command[1:]
        else:
            # Wait for update.
            while idl.change_seqno == seqno and not idl.run():
                rpc.run()

                poller = ovs.poller.Poller()
                idl.wait(poller)
                rpc.wait(poller)
                poller.block()

            print_idl(idl, step)
            step += 1

        seqno = idl.change_seqno

        if command == "reconnect":
            print("%03d: reconnect" % step)
            sys.stdout.flush()
            step += 1
            idl.force_reconnect()
        elif not command.startswith("["):
            idl_set(idl, command, step)
            step += 1
        else:
            json = ovs.json.from_string(command)
            if isinstance(json, six.string_types):
                sys.stderr.write("\"%s\": %s\n" % (command, json))
                sys.exit(1)
            json = substitute_uuids(json, symtab)
            request = ovs.jsonrpc.Message.create_request("transact", json)
            error, reply = rpc.transact_block(request)
            if error:
                sys.stderr.write("jsonrpc transaction failed: %s"
                                 % os.strerror(error))
                sys.exit(1)
            elif reply.error is not None:
                sys.stderr.write("jsonrpc transaction failed: %s"
                                 % reply.error)
                sys.exit(1)

            sys.stdout.write("%03d: " % step)
            sys.stdout.flush()
            step += 1
            if reply.result is not None:
                parse_uuids(reply.result, symtab)
            reply.id = None
            sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
            sys.stdout.flush()

    if rpc:
        rpc.close()
    while idl.change_seqno == seqno and not idl.run():
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()
    print_idl(idl, step)
    step += 1
    idl.close()
    print("%03d: done" % step)
예제 #22
0
def main():
    '''cfgd.main()

    cfgd processing logic is:

    create IDL session to configdb
    if row with type=startup exists, save off the config data
    close configdb IDL session

    start main loop and call functions to...
        wait for h/w initialization to complete
        if default config (see above), push the config to the db.
        mark configuration completion in the db.
        terminate
    '''

    global exiting
    global idl
    global loop_seq_no

    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--database', metavar="DATABASE",
                        help="A socket on which ovsdb-server is listening.",
                        dest='database')

    ovs.vlog.add_args(parser)
    ovs.daemon.add_args(parser)
    args = parser.parse_args()
    ovs.vlog.handle_args(args)
    ovs.daemon.handle_args(args)

    if args.database is None:
        remote = def_db
    else:
        remote = args.database

    # Locate default config if it exists
    check_for_startup_config(remote)

    schema_helper = ovs.db.idl.SchemaHelper(location=ovs_schema)
    schema_helper.register_columns("System",
                                   ["cur_hw", "cur_cfg", "next_cfg"])

    idl = ovs.db.idl.Idl(remote, schema_helper)

    ovs.daemon.daemonize()

    ovs.unixctl.command_register("exit", "", 0, 0, unixctl_exit, None)
    error, unixctl_server = ovs.unixctl.server.UnixctlServer.create(None)
    if error:
        ovs.util.ovs_fatal(error, "could not create unixctl server", vlog)

    seqno = idl.change_seqno    # Sequence number when we last processed the db

    init_dispatcher()

    while not exiting:
        # See if we have an incoming command
        unixctl_server.run()
        if exiting:
            break

        # Take a pass at the db to see if anything has come in
        idl.run()

        # Keeping this here for later when we don't terminate.
        '''
        # OPS_TODO: when we want to keep cfgd running, add code
        # ...to know when the dispatcher is through and then start
        # ...using this code to block on a db change.
        if seqno == idl.change_seqno:
            poller = ovs.poller.Poller()
            unixctl_server.wait(poller)
            idl.wait(poller)
            poller.block()
        '''

        # Call next method in the sequence
        dispatcher()

        seqno = idl.change_seqno

    unixctl_server.close()
    idl.close()

    return
예제 #23
0
def do_idl(schema_file, remote, *commands):
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)
    if commands and commands[0].startswith("?"):
        readonly = {}
        for x in commands[0][1:].split("?"):
            readonly = []
            table, columns = x.split(":")
            columns = columns.split(",")
            for index, column in enumerate(columns):
                if column[-1] == '!':
                    columns[index] = columns[index][:-1]
                    readonly.append(columns[index])
            schema_helper.register_columns(table, columns, readonly)
        commands = commands[1:]
    else:
        schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)

    if commands:
        error, stream = ovs.stream.Stream.open_block(
            ovs.stream.Stream.open(remote))
        if error:
            sys.stderr.write("failed to connect to \"%s\"" % remote)
            sys.exit(1)
        rpc = ovs.jsonrpc.Connection(stream)
    else:
        rpc = None

    symtab = {}
    seqno = 0
    step = 0

    commands = list(commands)
    if len(commands) >= 1 and "condition" in commands[0]:
        update_condition(idl, commands.pop(0))
        sys.stdout.write("%03d: change conditions\n" % step)
        sys.stdout.flush()
        step += 1

    for command in commands:
        if command.startswith("+"):
            # The previous transaction didn't change anything.
            command = command[1:]
        else:
            # Wait for update.
            while idl.change_seqno == seqno and not idl.run():
                rpc.run()

                poller = ovs.poller.Poller()
                idl.wait(poller)
                rpc.wait(poller)
                poller.block()

            print_idl(idl, step)
            step += 1

        seqno = idl.change_seqno

        if command == "reconnect":
            print("%03d: reconnect" % step)
            sys.stdout.flush()
            step += 1
            idl.force_reconnect()
        elif "condition" in command:
            update_condition(idl, command)
            sys.stdout.write("%03d: change conditions\n" % step)
            sys.stdout.flush()
            step += 1
        elif not command.startswith("["):
            idl_set(idl, command, step)
            step += 1
        else:
            json = ovs.json.from_string(command)
            if isinstance(json, six.string_types):
                sys.stderr.write("\"%s\": %s\n" % (command, json))
                sys.exit(1)
            json = substitute_uuids(json, symtab)
            request = ovs.jsonrpc.Message.create_request("transact", json)
            error, reply = rpc.transact_block(request)
            if error:
                sys.stderr.write("jsonrpc transaction failed: %s"
                                 % os.strerror(error))
                sys.exit(1)
            elif reply.error is not None:
                sys.stderr.write("jsonrpc transaction failed: %s"
                                 % reply.error)
                sys.exit(1)

            sys.stdout.write("%03d: " % step)
            sys.stdout.flush()
            step += 1
            if reply.result is not None:
                parse_uuids(reply.result, symtab)
            reply.id = None
            sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
            sys.stdout.flush()

    if rpc:
        rpc.close()
    while idl.change_seqno == seqno and not idl.run():
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()
    print_idl(idl, step)
    step += 1
    idl.close()
    print("%03d: done" % step)
예제 #24
0
파일: test-ovsdb.py 프로젝트: jhhan/ovs
def do_idl(schema_file, remote, *commands):
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)
    track_notify = False

    if remote.startswith("ssl:"):
        ovs.stream.Stream.ssl_set_private_key_file(commands[0])
        ovs.stream.Stream.ssl_set_certificate_file(commands[1])
        ovs.stream.Stream.ssl_set_ca_cert_file(commands[2])
        commands = commands[3:]

    if commands and commands[0] == "track-notify":
        commands = commands[1:]
        track_notify = True

    if commands and commands[0].startswith("?"):
        readonly = {}
        for x in commands[0][1:].split("?"):
            readonly = []
            table, columns = x.split(":")
            columns = columns.split(",")
            for index, column in enumerate(columns):
                if column[-1] == '!':
                    columns[index] = columns[index][:-1]
                    readonly.append(columns[index])
            schema_helper.register_columns(table, columns, readonly)
        commands = commands[1:]
    else:
        schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)

    if commands:
        error, stream = ovs.stream.Stream.open_block(
            ovs.stream.Stream.open(remote))
        if error:
            sys.stderr.write("failed to connect to \"%s\"" % remote)
            sys.exit(1)
        rpc = ovs.jsonrpc.Connection(stream)
    else:
        rpc = None

    symtab = {}
    seqno = 0
    step = 0

    def mock_notify(event, row, updates=None):
        output = "%03d: " % step
        output += "event:" + str(event) + ", row={"
        output += get_simple_table_printable_row(row) + "}, updates="
        if updates is None:
            output += "None"
        else:
            output += "{" + get_simple_table_printable_row(updates) + "}"

        output += '\n'
        sys.stdout.write(output)
        sys.stdout.flush()

    if track_notify and "simple" in idl.tables:
        idl.notify = mock_notify

    commands = list(commands)
    if len(commands) >= 1 and "condition" in commands[0]:
        update_condition(idl, commands.pop(0))
        sys.stdout.write("%03d: change conditions\n" % step)
        sys.stdout.flush()
        step += 1

    for command in commands:
        if command.startswith("+"):
            # The previous transaction didn't change anything.
            command = command[1:]
        else:
            # Wait for update.
            while idl.change_seqno == seqno and not idl.run():
                rpc.run()

                poller = ovs.poller.Poller()
                idl.wait(poller)
                rpc.wait(poller)
                poller.block()

            print_idl(idl, step)
            step += 1

        seqno = idl.change_seqno

        if command == "reconnect":
            print("%03d: reconnect" % step)
            sys.stdout.flush()
            step += 1
            idl.force_reconnect()
        elif "condition" in command:
            update_condition(idl, command)
            sys.stdout.write("%03d: change conditions\n" % step)
            sys.stdout.flush()
            step += 1
        elif not command.startswith("["):
            idl_set(idl, command, step)
            step += 1
        else:
            json = ovs.json.from_string(command)
            if isinstance(json, six.string_types):
                sys.stderr.write("\"%s\": %s\n" % (command, json))
                sys.exit(1)
            json = substitute_uuids(json, symtab)
            request = ovs.jsonrpc.Message.create_request("transact", json)
            error, reply = rpc.transact_block(request)
            if error:
                sys.stderr.write("jsonrpc transaction failed: %s"
                                 % os.strerror(error))
                sys.exit(1)
            elif reply.error is not None:
                sys.stderr.write("jsonrpc transaction failed: %s"
                                 % reply.error)
                sys.exit(1)

            sys.stdout.write("%03d: " % step)
            sys.stdout.flush()
            step += 1
            if reply.result is not None:
                parse_uuids(reply.result, symtab)
            reply.id = None
            sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
            sys.stdout.flush()

    if rpc:
        rpc.close()
    while idl.change_seqno == seqno and not idl.run():
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()
    print_idl(idl, step)
    step += 1
    idl.close()
    print("%03d: done" % step)
예제 #25
0
def main():
    global idl
    argv = sys.argv
    n_args = 2

    if len(argv) != n_args:
        print("Requires %d arguments but %d provided \n" % (n_args, len(argv)))
        return

    # Locate default config if it exists
    schema_helper = ovs.db.idl.SchemaHelper(location=OVS_SCHEMA)
    schema_helper.register_columns(SYSTEM_TABLE, ["cur_cfg"])
    schema_helper.register_columns(SYSTEM_TABLE,
                                   ["auto_provisioning_status"])

    idl = ovs.db.idl.Idl(DEF_DB, schema_helper)

    seqno = idl.change_seqno    # Sequence number when last processed the db

    # Wait until the ovsdb sync up.
    while (seqno == idl.change_seqno):
        idl.run()
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()

    wait_for_config_complete(idl)

    if os.path.exists(AUTOPROVISION_STATUS_FILE):
        print("Autoprovisioning already completed")
        update_autoprovision_status(OPS_TRUE, argv[1])
        idl.close()
        return

    if(fetch_autoprovision_script(argv[1]) is False):
        print("Downloading autoprovisioning script failed")
        idl.close()
        return

    sys.stdout.flush()

    ret = 1
    if os.path.exists(AUTOPROVISION_SCRIPT):
        ret = os.system('chmod +x ' + AUTOPROVISION_SCRIPT)
        ret = os.system(AUTOPROVISION_SCRIPT)
        if (ret == 0):
            try:
                FILE = open(AUTOPROVISION_STATUS_FILE, "w")
                FILE.close()
            except IOError as e:
                print "Creating autoprovision status file, I/O error({0}): \
                      {1}".format(e.errno, e.strerror)
                idl.close()
                return
            except Exception, e:
                print('Creating autoprovision status file, generic exception: '
                      + str(e))
                idl.close()
                return

            update_autoprovision_status(OPS_TRUE, argv[1])
            print("Autoprovision status: performed = %s URL =  %s"
                  % (OPS_TRUE, argv[1]))
        else:
            print("Error, executing autoprovision script returned error %d"
                  % ret)
예제 #26
0
def main():

    global exiting
    global idl
    global seqno
    global dnsmasq_started

    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--database', metavar="DATABASE",
                        help="A socket on which ovsdb-server is listening.",
                        dest='database')

    ovs.vlog.add_args(parser)
    ovs.daemon.add_args(parser)
    args = parser.parse_args()
    ovs.vlog.handle_args(args)
    ovs.daemon.handle_args(args)

    if args.database is None:
        remote = def_db
    else:
        remote = args.database

    dhcp_tftp_init(remote)

    ovs.daemon.daemonize()

    ovs.unixctl.command_register("exit", "", 0, 0, unixctl_exit, None)
    error, unixctl_server = ovs.unixctl.server.UnixctlServer.create(None)

    if error:
        ovs.util.ovs_fatal(error, "dhcp_tftp_helper: could not create "
                                  "unix-ctl server", vlog)

    while dnsmasq_started is False:
        dnsmasq_run()
        sleep(2)

    seqno = idl.change_seqno    # Sequence number when we last processed the db

    exiting = False
    while not exiting:

        unixctl_server.run()

        if exiting:
            break

        if seqno == idl.change_seqno:
            poller = ovs.poller.Poller()
            unixctl_server.wait(poller)
            idl.wait(poller)
            poller.block()

        idl.run()  # Better reload the tables

        vlog.dbg("dhcp_tftp_debug main - seqno change from %d to %d "
                 % (seqno, idl.change_seqno))
        if seqno != idl.change_seqno:
            '''
            OPS_TODO:
              If seqno is changed, it is assumed that DHCP/TFTP server config
              parameters have been changed by user and hence dnsmasq is
              is restarted with new config.

              This needs to be fixed - even if seqno gets changed, we need
              to check if the DHCP/TFTP server configuration is really changed
              or not and restart the dnsmasq daemon only if the config had
              been changed.
            '''
            dnsmasq_restart()
            seqno = idl.change_seqno

    # Daemon exit
    unixctl_server.close()
    idl.close()
예제 #27
0
def do_idl_cluster(schema_file, remote, pid, *commands):
    schema_helper = ovs.db.idl.SchemaHelper(schema_file)

    if remote.startswith("ssl:"):
        if len(commands) < 3:
            sys.stderr.write("SSL connection requires private key, "
                             "certificate for private key, and peer CA "
                             "certificate as arguments\n")
            sys.exit(1)
        ovs.stream.Stream.ssl_set_private_key_file(commands[0])
        ovs.stream.Stream.ssl_set_certificate_file(commands[1])
        ovs.stream.Stream.ssl_set_ca_cert_file(commands[2])
        commands = commands[3:]

    schema_helper.register_all()
    idl = ovs.db.idl.Idl(remote, schema_helper)

    step = 0
    seqno = 0
    commands = list(commands)
    for command in commands:
        if command.startswith("+"):
            # The previous transaction didn't change anything.
            command = command[1:]
        else:
            # Wait for update.
            while idl.change_seqno == seqno and not idl.run():
                poller = ovs.poller.Poller()
                idl.wait(poller)
                poller.block()
            step += 1

        seqno = idl.change_seqno

        if command == "reconnect":
            print("%03d: reconnect" % step)
            sys.stdout.flush()
            step += 1
            idl.force_reconnect()
        elif command == "remote":
            print("%03d: %s" % (step, idl.session_name()))
            sys.stdout.flush()
            step += 1
        elif command == "remotestop":
            r = idl.session_name()
            remotes = remote.split(',')
            i = remotes.index(r)
            pids = pid.split(',')
            command = None
            try:
                command = "kill %s" % pids[i]
            except ValueError as error:
                sys.stderr.write("Cannot find pid of remote: %s\n"
                                 % os.strerror(error))
                sys.exit(1)
            os.popen(command)
            print("%03d: stop %s" % (step, pids[i]))
            sys.stdout.flush()
            step += 1

    idl.close()
    print("%03d: done" % step)
def do_idl(schema_file, remote, *commands):
    schema = ovs.db.schema.DbSchema.from_json(ovs.json.from_file(schema_file))
    idl = ovs.db.idl.Idl(remote, schema)

    if commands:
        error, stream = ovs.stream.Stream.open_block(
            ovs.stream.Stream.open(remote))
        if error:
            sys.stderr.write("failed to connect to \"%s\"" % remote)
            sys.exit(1)
        rpc = ovs.jsonrpc.Connection(stream)
    else:
        rpc = None

    symtab = {}
    seqno = 0
    step = 0
    for command in commands:
        if command.startswith("+"):
            # The previous transaction didn't change anything.
            command = command[1:]
        else:
            # Wait for update.
            while idl.change_seqno == seqno and not idl.run():
                rpc.run()

                poller = ovs.poller.Poller()
                idl.wait(poller)
                rpc.wait(poller)
                poller.block()

            print_idl(idl, step)
            step += 1

        seqno = idl.change_seqno

        if command == "reconnect":
            print("%03d: reconnect" % step)
            sys.stdout.flush()
            step += 1
            idl.force_reconnect()
        elif not command.startswith("["):
            idl_set(idl, command, step)
            step += 1
        else:
            json = ovs.json.from_string(command)
            if type(json) in [str, unicode]:
                sys.stderr.write("\"%s\": %s\n" % (command, json))
                sys.exit(1)
            json = substitute_uuids(json, symtab)
            request = ovs.jsonrpc.Message.create_request("transact", json)
            error, reply = rpc.transact_block(request)
            if error:
                sys.stderr.write("jsonrpc transaction failed: %s"
                                 % os.strerror(error))
                sys.exit(1)
            sys.stdout.write("%03d: " % step)
            sys.stdout.flush()
            step += 1
            if reply.result is not None:
                parse_uuids(reply.result, symtab)
            reply.id = None
            sys.stdout.write("%s\n" % ovs.json.to_string(reply.to_json()))
            sys.stdout.flush()

    if rpc:
        rpc.close()
    while idl.change_seqno == seqno and not idl.run():
        poller = ovs.poller.Poller()
        idl.wait(poller)
        poller.block()
    print_idl(idl, step)
    step += 1
    idl.close()
    print("%03d: done" % step)
예제 #29
0
def main():

    global exiting
    global idl
    global seqno
    global dnsmasq_started

    parser = argparse.ArgumentParser()
    parser.add_argument('-d',
                        '--database',
                        metavar="DATABASE",
                        help="A socket on which ovsdb-server is listening.",
                        dest='database')

    ovs.vlog.add_args(parser)
    ovs.daemon.add_args(parser)
    args = parser.parse_args()
    ovs.vlog.handle_args(args)
    ovs.daemon.handle_args(args)

    if args.database is None:
        remote = def_db
    else:
        remote = args.database

    dhcp_tftp_init(remote)

    ovs.daemon.daemonize()

    ovs.unixctl.command_register("exit", "", 0, 0, unixctl_exit, None)
    error, unixctl_server = ovs.unixctl.server.UnixctlServer.create(None)

    if error:
        ovs.util.ovs_fatal(
            error, "dhcp_tftp_helper: could not create "
            "unix-ctl server", vlog)

    while dnsmasq_started is False:
        dnsmasq_run()
        sleep(2)

    seqno = idl.change_seqno  # Sequence number when we last processed the db

    exiting = False
    while not exiting:

        unixctl_server.run()

        if exiting:
            break

        if seqno == idl.change_seqno:
            poller = ovs.poller.Poller()
            unixctl_server.wait(poller)
            idl.wait(poller)
            poller.block()

        idl.run()  # Better reload the tables

        vlog.dbg("dhcp_tftp_debug main - seqno change from %d to %d " %
                 (seqno, idl.change_seqno))
        if seqno != idl.change_seqno:
            '''
            OPS_TODO:
              If seqno is changed, it is assumed that DHCP/TFTP server config
              parameters have been changed by user and hence dnsmasq is
              is restarted with new config.

              This needs to be fixed - even if seqno gets changed, we need
              to check if the DHCP/TFTP server configuration is really changed
              or not and restart the dnsmasq daemon only if the config had
              been changed.
            '''
            dnsmasq_restart()
            seqno = idl.change_seqno

    # Daemon exit
    unixctl_server.close()
    idl.close()