client.py 11 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
import logging
import os
import signal
import sys
from pprint import pprint
from threading import Thread
from time import (sleep,)
from iso8583_web.read_conf import (ip_conf)
from iso8583_web.read_conf import (read_conf, name_conf)
from iso8583_web.scripts.forwarder import get_db
from opensipkd.string import (exception_message, dict_to_str,)
from opensipkd.tcp.client import Client as BaseClient
from opensipkd.tcp.connection import (
    ConnectionManager as BaseConnectionManager,
    join_ip_port,
)
from pyramid.paster import setup_logging
from datetime import datetime
from opensipkd.iso8583.bjb.samsat.banten.doc import Doc
from optparse import OptionParser
try:
    from configparser import (
        ConfigParser,
        NoOptionError,
    )
except ImportError:
    from ConfigParser import (
        ConfigParser,
        NoOptionError,
    )

INQUIRY_CODE = '301099'

from iso8583_web.scripts.forwarder import (
    CommonConnection, iso_to_dict, create_thread, Log, parser_threads,
    log_info, to_str)

from iso8583_web.scripts.forwarder import (
    # check_connection, check_job,
    # check_parser,
    logs, running, conn_mgr,
    ConnectionManager, out)

def get_option(argv):
    # bank = conf.host['streamer'] #'bjb'
    pars = OptionParser()
    count = 10
    pars.add_option('-i', '--invoice-id')
    pars.add_option('-c', '--count', default=count, help="Default %s" % count)
    option, remain = pars.parse_args(argv)
    if not option.invoice_id:
        print('--invoice-id harus diisi.')
        return
    return option

# todo: harus nya diimport saja dari scripts inquiry
def inquiry_request(iso, invoice_id, bank_id=None):
    bank_id = bank_id and bank_id or '110'
    kini = datetime.now()
    iso.setBit(2, kini.strftime('%Y%m%d%H%M%S'))
    iso.set_transaction_code(INQUIRY_CODE)
    iso.setBit(12, kini.strftime('%H%M%S'))
    iso.setBit(13, kini.strftime('%m%d'))
    iso.setBit(15, kini.strftime('%m%d'))
    iso.setBit(18, '6010')
    iso.setBit(22, '021')
    iso.setBit(32, bank_id)
    iso.setBit(33, bank_id.rjust(5,'0')) #forwarder
    iso.setBit(37, kini.strftime('%H%M%S'))
    iso.setBit(41, '000')
    iso.setBit(42, '000000000000000')
    iso.setBit(43, 'Nama Bank')
    iso.setBit(49, '390')
    iso.setBit(61, invoice_id)

class TestInquiry(object):
    def __init__(self, argv, client):
        self.option = get_option(argv)
        if not self.option:
            return
        self.invoice_id = self.option.invoice_id.replace('-', '')
        # print(name_conf['banten'])
        self.conf = name_conf[client]
        self.bank_id = 'bank_id' in self.conf and self.conf['bank_id'] or '110'
        self.count = self.option.count

    def run(self):
        if not self.option:
            return
        print('\nBank kirim inquiry request')
        req_iso = Doc(conf=self.conf)
        req_iso.inquiry_request()
        inquiry_request(req_iso, self.invoice_id, self.bank_id)
        raw = self.get_raw(req_iso)
        return raw

    def get_raw(self, iso):
        msg = 'MTI {mti}'.format(mti=iso.getMTI())
        # print(msg)
        # pprint(iso_to_dict(iso))  # getBitsAndValues())
        raw = iso.getRawIso()
        # sleep(1)
        # print([raw])
        return raw



# class CommonConnection(Log):
#     def log_receive_raw(self, raw):
#         raw = to_str(raw)
#         self.log_info('Receive {}'.format([raw]))
#
#     def log_send(self, raw):
#         if isinstance(raw, bytes):
#             raw = raw.decode('utf-8')
#         raw = to_str(raw)
#         self.log_info('Send {}'.format([raw]))
#
#     def log_close(self, reason):
#         msg = 'close connection because {}'.format(reason)
#         self.log_info(msg)
#
#     def log_timeout(self):
#         self.log_error("DBUG > COmmond")
#         self.log_close('timeout')
#
#     def log_raw_to_iso(self, raw):
#         self.log_info('Raw to ISO8583 {}'.format([raw]))
#
#     def log_iso_to_raw(self, raw):
#         raw = to_str(raw)
#         # self.log_info('ISO8583 to raw {}'.format([raw]))
#
#     def process(self, raw):
#         raw = raw+chr(13)
#         for i in range(1,20):
#             parser = Parser(self, raw)
#             thread = create_thread(parser.run)
#             parser_threads.append((parser, thread))
#             thread.start()

###################
# ISO 8583 Client #
###################
class Client(BaseClient, CommonConnection):
    def connect(self):
        ip, port = self.address
        self.log_info('connect to port {}'.format(port))
        BaseClient.connect(self)

    def on_receive_raw(self, raw):
        self.log_receive_raw(raw)
        BaseClient.on_receive_raw(self, raw)

    # Override BaseClient.process()
    def process(self, raw):
        CommonConnection.process(self, raw)

    def close_because_timeout(self):
        self.log_error("DEBUG -> CLIENT")
        self.log_timeout()
        BaseClient.close_because_timeout(self)

    def on_refused(self, err):
        ip, port = self.address
        self.log_error('port {} {}'.format(port, err))
        BaseClient.on_refused(self, err)

    def on_socket_error(self, err):
        self.log_error(err)
        BaseClient.on_socket_error(self, err)

    def raw_for_send(self, raw):
        self.log_iso_to_raw(raw)
        raw = BaseClient.raw_for_send(self, raw)
        self.log_send(raw)
        return raw

    def run(self):
        try:
            BaseClient.run(self)
        except:
            self.log_unknown()


    def on_loop(self):
        raw = self.receive_raw()
        if not raw:
            if self.is_timeout():
                if not self.conf['listen']:
                    self.set_connected_time()
                    return

                self.close_because_timeout()
            return

        # raw = self.streamer.get(raw)
        # if not raw:
        #     return
        # raw = self.process(raw)
        # if raw:
        #     self.send(raw)
        while True:
            raw = self.streamer.get(raw)
            # i += 1
            # self.log_info(">> RAW {}, {}".format(i, raw))
            # self.log_info(">> SISA {}, {}".format(i, self.streamer.raw))

            if not raw:
                break
            raw = self.process(raw)
            if raw:
                self.send(raw)
            raw = ''


def start_client(conf):
    client = Client(conf)
    thread = create_thread(client.run)
    ip_port = join_ip_port(conf['ip'], conf['port'])
    clients[ip_port] = (client, thread)
    thread.start()
    conn_mgr.add(client)


clients = {}


# def stop_connections(reason):
#     for ip_port, connection in conn_mgr:
#         connection.log_close(reason)
#         connection.close()
#         sleep(1)
#     for ip_port in clients:
#         client, thread = clients[ip_port]
#         thread.join()


#######################
# Raw ISO 8583 parser #
#######################
class Parser(Log):
    def __init__(self, connection, raw):
        self.connection = connection
        self.raw = raw
        self.conf = connection.conf
        self.conn_id = id(connection)
        self.parser_id = id(self)
        self.running = True

    # Override
    def log_message(self, msg):
        return '{ip} {name} {conn_id} -> {parser_id} {msg}'.format(
            ip=self.conf['ip'], name=self.conf['name'], conn_id=self.conn_id,
            parser_id=self.parser_id, msg=msg)

    def run(self):
        from_iso = self.connection.job.raw_to_iso(self.raw)
        # self.log_decode(from_iso)
        # ditambahkan disini
        raw = iso['inquiry'].run()
        self.connection.send(raw)

        #ini di remark
        # iso = self.connection.job.process(from_iso)
        #
        # if iso:
        #     self.log_encode(iso)
        #     raw = iso.getRawIso()
        #     self.connection.send(raw)
        # else:  # dapat response
        #     ip_port = join_ip_port(self.conf['ip'], self.conf['port'])

        self.running = False


######################
# Connection Manager #
######################
# class ConnectionManager(BaseConnectionManager):
#     def close_old_connection(self, old_conn):
#         old_conn.log_close('new connection found')
#         BaseConnectionManager.close_old_connection(self, old_conn)


# conn_mgr = ConnectionManager()

# MSG_KILL_BY_SIGNAL = 'kill by signal {}'
# MSG_KILL_BY_KEYBOARD = 'kill by keyboard interrupt'
#
#
# def out(sig=None, func=None):
#     if running:
#         del running[0]  # Akhiri loop utama
#     if sig:
#         reason = MSG_KILL_BY_SIGNAL.format(sig)
#     else:
#         reason = MSG_KILL_BY_KEYBOARD
#     stop_connections(reason)


def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri>\n'
          '(example: "%s test.ini -i invoice_id [-c count]")' % (cmd, cmd))
    sys.exit(1)

def check_connection():
    log_info("Check Connection")
    for ip_port in ip_conf:
        if ip_port in conn_mgr:
            index = -1
            while True:
                index += 1
                if not conn_mgr[index:]:
                    break
                this_ip_port, conn = conn_mgr[index]
                if this_ip_port != ip_port:
                    continue
                if conn.running:
                    continue
                conn_mgr.remove(index)
                break
            continue

        cfg = ip_conf[ip_port]
        if cfg['listen']:
            continue
        start_client(cfg)
        sleep(5)


def check_job():
    log_info("Check Job")
    for ip_port, connection in conn_mgr:
        if not connection.running:
            continue
        if not connection.is_connected():
            continue
        iso = connection.job.get_iso()
        if not iso:
            continue

        # connection.log_encode(iso)
        raw = iso.getRawIso()
        connection.send(raw)


def check_parser():
    log_info("Check Parser")
    i = -1
    while True:
        i += 1
        if not parser_threads[i:]:
            break
        parser, thread = parser_threads[i]
        if not parser.running:
            thread.join()
            del parser_threads[i]
            i -= 1


# logs = []
# running = []


# iso_raw = None
iso = {}
def main(argv=sys.argv):
    if len(argv) <= 3:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    conf = read_conf(config_uri)
    # conf['invoice_id'] = argv[2]
    get_db(conf)

    log = logging.getLogger(__file__)
    logs.append(log)
    running.append(True)
    iso['inquiry'] = TestInquiry(argv, 'banten')

    # Antisipasi kill
    signal.signal(signal.SIGTERM, out)
    try:
        start = True
        while running:
            check_connection()
            check_job()
            for c in conn_mgr:
                this_ip_port = c[0]
                conn = c[1]
                if conn.running and start:
                    for i in range(int(iso['inquiry'].count)):
                        raw = iso['inquiry'].run()
                        conn.send(raw)
                        sleep(0.5)
                    start = False

            check_parser()
            # break
            sleep(5)
    except KeyboardInterrupt:
        out()


if __name__ == '__main__':
    main(sys.argv)