Beispiel #1
0
def get_connection(alias=DEFAULT_ALIAS, reconnect=False):
    """Return connection by alias.

    :param alias:
    :param reconnect:

    """
    global _connections

    if reconnect:
        disconnect(alias)

    if alias not in _connections:
        alias_settings = _connection_settings.get(alias)

        if not alias_settings:
            raise ValueError(
                'Connection with alias {alias} have not defined.'.format(
                    alias=alias))

        try:
            conn_settings = alias_settings.copy()
            host = conn_settings.pop('host')
            port = conn_settings.pop('port')
            conn_settings.pop('space', None)

            _connections[alias] = Connection(host, port, **conn_settings)
        except DatabaseError as exc:
            message = 'Connect error for alias "{alias}": "{message}".'.format(
                alias=alias, message=exc)
            raise ConnectionError, message, sys.exc_info()[2]

    return _connections[alias]
Beispiel #2
0
def key_exists(key):
    logger("key_exists()", key)
    c = Connection("127.0.0.1", 3301)
    print("key_exists()")
    exists = list(c.select("KVstorage", key))
    print(exists != [])
    return exists != []
    def connect_to_tarantool(self, host, port, user=None, password=None, alias=None):
        """
        Connection to Tarantool DB.

        *Args:*\n
            _host_ - host for db connection;\n
            _port_ - port for db connection;\n
            _user_ - username for db connection;\n
            _password_ - password for db connection;\n
            _alias_ - connection alias, used for switching between open connections;\n

        *Returns:*\n
            Returns ID of the new connection. The connection is set as active.

        *Example:*\n
            | Connect To Tarantool  |  127.0.0.1  |  3301  |
        """
        logger.debug('Connecting  to the Tarantool DB using \
        host={host}, port={port}, user={user}'.format(host=host,
                                                      port=port,
                                                      user=user))
        try:
            self._connection = Connection(host=host, port=int(port), user=user, password=password)
            return self._cache.register(self._connection, alias)
        except Exception as exc:
            raise Exception("Logon to Tarantool error:", str(exc))
Beispiel #4
0
def add_kv(key, value):
    print("sdfgh")
    logger("add_kv()", key + " " + value)
    c = Connection("127.0.0.1", 3301)
    print("add_key()")
    try:
        c.insert("KVstorage", (key, value))
        print(c.select("KVstorage", key))
        return True
    except:
        return False
Beispiel #5
0
def produce(table: str):
    tnt_connection = Connection("127.0.0.1", 3302)
    trace(table, "Produce start")
    start = time.perf_counter_ns()
    for row in range(0, 100000, 1):
        next_id = tnt_connection.call("box.sequence.test_seq:next")
        tnt_connection.insert(table, (str(uuid.uuid1()), next_id[0], "TestBook_" + str(row), randint(1900, 2000)))
        if row % 1000 == 0:
            trace(table, "Done insert row: {}".format(row))
    end = time.perf_counter_ns()
    table_size = tnt_connection.call("box.space.{}:len".format(table))
    diff = (end - start) / 1000.0
    trace(table, "Completed, table size: {}, time spent: {}"
          .format(table_size[0], diff))
    return diff
Beispiel #6
0
def run_requests(table: str, debug: bool = True):
    tnt_connection = Connection("127.0.0.1", 3302)
    trace(table, "Run requests")
    ids = get_ids(tnt_connection, table, 1000)
    start = time.perf_counter_ns()
    row = 0
    for item in ids:
        result = tnt_connection.select(table, [item])
        if row % 100 == 0 and debug:
            trace(table, "Request completed: {}, last result: {}".format(row, result[0]))
        row += 1
    end = time.perf_counter_ns()
    diff = (end - start) / 1000.0
    trace(table, "Completed, request count: {}, time spent: {}"
          .format(row, diff))
    return diff
Beispiel #7
0
def test(header, body):
    # Connect and authenticate
    c = Connection('localhost', server.iproto.port)
    c.connect()
    print 'query', repr_dict(header), repr_dict(body)
    header = msgpack.dumps(header)
    body = msgpack.dumps(body)
    query = msgpack.dumps(len(header) + len(body)) + header + body
    # Send raw request using connectred socket
    s = c._socket
    try:
        s.send(query)
    except OSError as e:
        print '   => ', 'Failed to send request'
    c.close()
    print iproto.py_con.ping() > 0
Beispiel #8
0
#!/usr/bin/python
import sys
from tarantool import Connection

c = Connection("127.0.0.1", 3301)

for line in sys.stdin:
    fields = line.rstrip().split('\t')
    num_fields = [int(x) for x in fields]
    c.insert("test1", tuple(num_fields))
Beispiel #9
0
 def __init__(self, *, host, port, user, password):
     self.space = "kv"
     self.conn = Connection(host, port, user=user, password=password)
Beispiel #10
0
print("IPROTO_REPLACE")
test({IPROTO_CODE: REQUEST_TYPE_REPLACE}, {IPROTO_SPACE_ID: 280})
print("\n")

print("IPROTO_CALL")
test({IPROTO_CODE: REQUEST_TYPE_CALL}, {})
test({IPROTO_CODE: REQUEST_TYPE_CALL}, {IPROTO_KEY: ("procname", )})
print("\n")

# gh-434 Tarantool crashes on multiple iproto requests with WAL enabled
admin("box.cfg.wal_mode")
admin("space = box.schema.space.create('test', { id = 567 })")
admin("index = space:create_index('primary', { type = 'hash' })")
admin("box.schema.user.grant('guest', 'read,write,execute', 'space', 'test')")

c = Connection("localhost", server.iproto.port)
c.connect()
request1 = RequestInsert(c, 567, [1, "baobab"])
request2 = RequestInsert(c, 567, [2, "obbaba"])
s = c._socket
try:
    s.send(bytes(request1) + bytes(request2))
except OSError as e:
    print("   => ", "Failed to send request")
response1 = Response(c, c._read_response())
response2 = Response(c, c._read_response())
print(response1.__str__())
print(response2.__str__())

request1 = RequestInsert(c, 567, [3, "occama"])
request2 = RequestSelect(c, 567, 0, [1], 0, 1, 0)
Beispiel #11
0
def update_value(key, value):
     logger("update_value", key + " " + value)
     c = Connection("127.0.0.1", 3301)
     print("update_value()")
     c.update("KVstorage", str(key), [('=', 1, value)] )
     print(c.select("KVstorage", key))
Beispiel #12
0
def get_kv(key):
    logger("get_kv()", key)
    c = Connection("127.0.0.1", 3301)
    print("get_kv()")
    print(c.select("KVstorage", key))
    return list(c.select("KVstorage", key))
Beispiel #13
0
def delete_value_by_key(key):
    c = Connection('127.0.0.1', 3301)
    c.delete("KVStorage", key)
    return
Beispiel #14
0
def update_value_by_key(key, value):
    c = Connection('127.0.0.1', 3301)
    c.update("KVStorage", key, [('=', 1, str(value))])
    return
Beispiel #15
0
def delete_kv(key):
    logger("delete_kv()", key)
    c = Connection("127.0.0.1", 3301)
    print("delete_kv()")
    c.delete("KVstorage", key)
    return
Beispiel #16
0
def add_value_by_key(key, value):
    c = Connection('127.0.0.1', 3301)
    c.insert("KVStorage", (key, value))
    return
Beispiel #17
0
print "IPROTO_REPLACE"
test({IPROTO_CODE: REQUEST_TYPE_REPLACE}, {IPROTO_SPACE_ID: 280})
print "\n"

print "IPROTO_CALL"
test({IPROTO_CODE: REQUEST_TYPE_CALL}, {})
test({IPROTO_CODE: REQUEST_TYPE_CALL}, {IPROTO_KEY: ('procname', )})
print "\n"

# gh-434 Tarantool crashes on multiple iproto requests with WAL enabled
admin("box.cfg.wal_mode")
admin("space = box.schema.space.create('test', { id = 567 })")
admin("index = space:create_index('primary', { type = 'hash' })")
admin("box.schema.user.grant('guest', 'read,write,execute', 'space', 'test')")

c = Connection('localhost', server.iproto.port)
c.connect()
request1 = RequestInsert(c, 567, [1, "baobab"])
request2 = RequestInsert(c, 567, [2, "obbaba"])
s = c._socket
try:
    s.send(bytes(request1) + bytes(request2))
except OSError as e:
    print '   => ', 'Failed to send request'
response1 = Response(c, c._read_response())
response2 = Response(c, c._read_response())
print response1.__str__()
print response2.__str__()

request1 = RequestInsert(c, 567, [3, "occama"])
request2 = RequestSelect(c, 567, 0, [1], 0, 1, 0)
Beispiel #18
0
from tarantool import Connection

conn = Connection("localhost", 3302)

conn.insert("user", (
    None,
    'a',
    1,
))
conn.insert("user", (
    None,
    'b',
    1,
))
conn.insert("user", (
    None,
    'a',
    0,
))
conn.insert("user", (
    None,
    'b',
    0,
))

conn.insert("channel", (None, '1001373637514', 1, 't.me/ofka'))
conn.insert("channel", (None, '1236565135464', 1, 't.me/root'))
conn.insert("channel", (None, 'icqchannel1', 0, 'icq.com/qwe'))
conn.insert("channel", (None, 'icqchannel2', 0, 'icq.com/zxcvbnm'))

conn.insert("link", (None, 1, 3, 1))
Beispiel #19
0
def show_samples(table: str):
    tnt_connection = Connection("127.0.0.1", 3302)
    trace(table, "Show samples")
    result = tnt_connection.select(space_name=table, offset=0, limit=10)
    for item in result:
        print(item)
Beispiel #20
0
 def db_connect(self):
     return Connection(self.host, self.port)
Beispiel #21
0
def get_value_by_key(key):
    c = Connection('127.0.0.1', 3301)
    value = list(c.select("KVStorage", key))
    return value