Beispiel #1
0
class LMDBRequestHandler(resource.Resource):
    """
    LMDBRequestHandler is comprised of HTTP interface which 
    listens for calls to LMDB
    """
    # The isLeaf instance variable describes whether or not
    # a resource will have children and only leaf resources get rendered.
    # LMDBRequestHandler is the most derived class hence isLeaf is required.

    isLeaf = True

    ## -----------------------------------------------------------------
    def __init__(self, config):

        if config.get('KvStorage') is None:
            logger.error("Kv Storage path is missing")
            sys.exit(-1)

        self.kv_helper = KvStorage()

        storage_path = TCFHOME + '/' + config['KvStorage']['StoragePath']
        if not self.kv_helper.open(storage_path):
            logger.error("Failed to open KV Storage DB")
            sys.exit(-1)

    def __del__(self):
        self.kv_helper.close()

    def _process_request(self, request):
        response = ""
        logger.info(request.encode('utf-8'))
        args = request.split('\n')
        for i in range(len(args)):
            args[i] = unescape(args[i])
        logger.info(args)
        cmd = args[0]

        # Lookup
        if (cmd == "L"):
            if len(args) == 2:
                result_list = self.kv_helper.lookup(args[1])
                result = ""
                for key in result_list:
                    if result == "":
                        result = key
                    else:
                        result = result + "," + key
                # Lookup result found
                if result != "":
                    response = "l\n" + escape(result)
                # No result found
                else:
                    response = "n"
            # Error
            else:
                logger.error("Invalid args for cmd Lookup")
                response = "e\nInvalid args for cmd Lookup"

        # Get
        elif (cmd == "G"):
            if len(args) == 3:
                result = self.kv_helper.get(args[1], args[2])
                # Value found
                if result is not None:
                    response = "v\n" + escape(result)
                # Value not found
                else:
                    response = "n"
            # Error
            else:
                logger.error("Invalid args for cmd Get")
                response = "e\nInvalid args for cmd Get"

        # Set
        elif (cmd == "S"):
            if len(args) == 4:
                result = self.kv_helper.set(args[1], args[2], args[3])
                # Set successful (returned True)
                if result:
                    response = "t"
                # Set unsuccessful (returned False)
                else:
                    response = "f"
            # Error
            else:
                logger.error("Invalid args for cmd Set")
                response = "e\nInvalid args for cmd Set"

        # Remove
        elif (cmd == "R"):
            if len(args) == 3 or len(args) == 4:
                if len(args) == 3:
                    result = self.kv_helper.remove(args[1], args[2])
                else:
                    result = self.kv_helper.remove(args[1],
                                                   args[2],
                                                   value=args[3])
                # Remove successful (returned True)
                if result:
                    response = "t"
                # Remove unsuccessful (returned False)
                else:
                    response = "f"
            # Error
            else:
                logger.error("Invalid args for cmd Remove")
                response = "e\nInvalid args for cmd Remove"
        # Error
        else:
            logger.error("Unknown cmd")
            response = "e\nUnknown cmd"
        return response

    def render_GET(self, request):
        response = 'Only POST request is supported'
        logger.error("GET request is not supported." + \
            " Only POST request is supported")

        return response

    def render_POST(self, request):
        response = ""

        logger.info('Received a new request from the client')

        try:
            # Process the message encoding
            encoding = request.getHeader('Content-Type')
            data = request.content.read().decode('utf-8')

            if encoding == 'text/plain; charset=utf-8':
                response = self._process_request(data)
            else:
                response = 'UNKNOWN_ERROR: unknown message encoding'
                return response

        except:
            logger.exception('exception while decoding http request %s',
                             request.path)
            response = 'UNKNOWN_ERROR: unable to decode incoming request '
            return response

        # Send back the results
        try:
            logger.info('response[%s]: %s', encoding, response.encode('utf-8'))
            request.setHeader('content-type', encoding)
            request.setResponseCode(http.OK)
            return response.encode('utf-8')

        except:
            logger.exception('unknown exception while processing request %s',
                             request.path)
            response = 'UNKNOWN_ERROR: unknown exception processing ' + \
                'http request {0}'.format(request.path)
            return response
def LocalMain(config) :

    if config.get('KvStorage') is None:
        logger.error("Kv Storage path is missing")
        sys.exit(-1)

    KvHelper = KvStorage()
    KvHelper.open((TCFHOME + '/' + config['KvStorage']['StoragePath']))
    
    if not input_json_str and not input_json_dir:
       logger.error("JSON input file is not provided")
       exit(1)
    
    if not output_json_file_name:
        logger.error("JSON output file is not provided")
        exit(1)
    
    if not server_uri:
        logger.error("Server URI is not provided")
        exit(1)
        
    logger.info('execute work order')
    uri_client = GenericServiceClient(server_uri) 
    
    if input_json_dir:
        directory = os.fsencode(input_json_dir)
        files = os.listdir(directory)
            
        for file in sorted(files) :
            logger.info("------------------Input file name: %s ---------------\n",file.decode("utf-8"))
            input_json_str1 = enclave_helper.read_json_file((directory.decode("utf-8") + file.decode("utf-8")))
            logger.info("*********Request Json********* \n%s\n", input_json_str1)
            response = uri_client._postmsg(input_json_str1)
            logger.info("**********Received Response*********\n%s\n", response)
            
    else :
        j=json.loads(input_json_str)
        
        if(j['method'] == "WorkOrderGetResult"):
            response = {}
            response['id'] =  j['params']['workOrderId']
            response["outData"] = "Processed response"
            KvHelper.set("wo-responses", str(j['params']['workOrderId']), json.dumps(response))
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response)
            
            j['params']['workOrderId'] = "101"
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response)
            
            j['params']['workOrderId'] = "121"
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response)
            
        else:
            id = 100
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
            logger.info("Test adding new time stamps entries")
            for x in range(5):
                j['params']['workOrderId'] = id + x
                input_str = json.dumps(j)
                logger.info('input str %s', input_str)
                response = uri_client._postmsg(input_str)
                logger.info("Received Response : %s , \n \n ", response)
            
                logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
                
            logger.info("Work order id exists")
            id = 100    
            for x in range(5):
                j['params']['workOrderId'] = id + x
                input_str = json.dumps(j)
                logger.info('input str %s', input_str)
                response = uri_client._postmsg(input_str)
                logger.info("Received Response : %s , \n \n ", response);
            
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
                
            logger.info("Test max count reached and buys status")
            id = 105
            for x in range(10):
                j['params']['workOrderId'] = id + x
                input_str = json.dumps(j)
                logger.info('input str %s', input_str)
                response = uri_client._postmsg(input_str)
                logger.info("Received Response : %s , \n \n ", response);
                
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
            
            logger.info("Adding a work order id 109 into processed table")
            KvHelper.set("wo-processed", "109", "109")
            
            logger.info("Sending a new request with work order id %s", id + x)
            j['params']['workOrderId'] = id + x
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response);
            
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
            
            work_orders = KvHelper.lookup("wo-scheduled")
            for wo_id in work_orders:
                KvHelper.remove("wo-scheduled", wo_id)
            
            logger.info("adding 3 entries into processing scheduled and processed table to test boot flow")
            KvHelper.set("wo-scheduled", "100", input_str)
            KvHelper.set("wo-processing", "101", input_str)
            KvHelper.set("wo-processed", "102", input_str)
            
            logger.info("restart tcf listener and verify it adds to its internal list during boot up")

    exit(0)