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()
def main():

    global exiting
    global idl
    global seqno

    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

    supportability_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, "could not create unix-ctl server", vlog)

    # Sequence number when we last processed the db.
    seqno = idl.change_seqno
    exiting = False
    while not exiting:

        supportability_run()

        unixctl_server.run()

        supportability_wait()

        crashprocessing_run()

        if exiting:
            break

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

    # Daemon Exit.
    unixctl_server.close()
    idl.close()
Example #3
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')
Example #4
0
def main():

    global exiting
    global idl
    global seqno

    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

    bufmond_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, "could not create unix-ctl server", vlog)

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

    exiting = False
    while not exiting:

        bufmond_run()

        unixctl_server.run()

        bufmond_wait()

        if exiting:
            break;

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

    #Daemon Exit
    unixctl_server.close()
    idl.close()
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()
Example #6
0
    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
Example #7
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()
Example #8
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)
Example #9
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()
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)
Example #11
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)
Example #12
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)
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)
Example #14
0
def main():

    global exiting
    global idl
    global seqno

    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

    schema_helper = ovs.db.idl.SchemaHelper(location=ovs_schema)
    schema_helper.register_columns(SYSTEM_TABLE, ["cur_cfg"])
    schema_helper.register_columns(SYSTEM_TABLE, ["other_config"])
    schema_helper.register_columns(SYSTEM_TABLE, ["mgmt_intf_status"])
    schema_helper.register_columns(
        PORT_TABLE, ["ip4_address", "name", "ip4_address_secondary"])
    schema_helper.register_columns(
        VRF_TABLE,
        ["name", "ports", "table_id", "source_ip", "source_interface"])

    schema_helper.register_columns(SYSTEM_TABLE, [
        SYSTEM_AAA_COLUMN, SYSTEM_OTHER_CONFIG,
        SYSTEM_AUTO_PROVISIONING_STATUS_COLUMN
    ])

    schema_helper.register_columns(SYSTEM_TABLE, [SYSTEM_RADIUS_SERVER_COLUMN])
    schema_helper.register_columns(TACACS_SERVER_TABLE, [
        TACACS_SERVER_IPADDRESS, TACACS_SERVER_PORT, TACACS_SERVER_PASSKEY,
        TACACS_SERVER_TIMEOUT, TACACS_SERVER_AUTH_TYPE, TACACS_SERVER_GROUP,
        TACACS_SERVER_GROUP_PRIO, TACACS_SERVER_DEFAULT_PRIO
    ])
    schema_helper.register_columns(RADIUS_SERVER_TABLE, [
        RADIUS_SERVER_IPADDRESS, RADIUS_SERVER_PORT, RADIUS_SERVER_PASSKEY,
        RADIUS_SERVER_RETRIES, RADIUS_SERVER_TIMEOUT, RADIUS_SERVER_AUTH_TYPE,
        RADIUS_SERVER_GROUP, RADIUS_SERVER_GROUP_PRIO,
        RADIUS_SERVER_DEFAULT_PRIO
    ])
    schema_helper.register_columns(AAA_SERVER_GROUP_TABLE, [
        AAA_SERVER_GROUP_IS_STATIC, AAA_SERVER_GROUP_NAME,
        AAA_SERVER_GROUP_TYPE
    ])
    schema_helper.register_columns(AAA_SERVER_GROUP_PRIO_TABLE, [
        AAA_SERVER_GROUP_PRIO_SESSION_TYPE, AAA_AUTHENTICATION_GROUP_PRIOS,
        AAA_AUTHORIZATION_GROUP_PRIOS
    ])

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

    ovs.daemon.daemonize()
    ovs.daemon.set_pidfile(None)
    ovs.daemon._make_pidfile()

    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)

    # Diags callback init for AAA
    ops_diagdump.init_diag_dump_basic(ops_aaa_diagnostics_handler)

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

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

    while not exiting:
        unixctl_server.run()

        aaa_util_run()

        if exiting:
            break

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

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

    return
Example #15
0
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)
Example #16
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
    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)
def main():

    global exiting
    global idl
    global seqno

    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

    schema_helper = ovs.db.idl.SchemaHelper(location=ovs_schema)
    schema_helper.register_columns(SYSTEM_TABLE, ["cur_cfg"])
    schema_helper.register_columns(
        SYSTEM_TABLE,
        [SYSTEM_AAA_COLUMN, SYSTEM_OTHER_CONFIG,
         SYSTEM_AUTO_PROVISIONING_STATUS_COLUMN])

    schema_helper.register_columns(SYSTEM_TABLE,
                                   [SYSTEM_RADIUS_SERVER_COLUMN])
    schema_helper.register_columns(RADIUS_SERVER_TABLE,
                                   [RADIUS_SERVER_IPADDRESS,
                                    RADIUS_SERVER_PORT,
                                    RADIUS_SERVER_PASSKEY,
                                    RADIUS_SERVER_TIMEOUT,
                                    RADIUS_SERVER_RETRIES,
                                    RADIUS_SEREVR_PRIORITY])

    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 last processed the db

    while not exiting:
        unixctl_server.run()

        aaa_util_run()

        if exiting:
            break

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

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

    return
Example #18
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)
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()