Ejemplo n.º 1
0
def main(function_name):
    config = ConfigParser()
    config.read('sapnwrfc.cfg')
    params_connection = config._sections['connection']

    try:
        connection = Connection(**params_connection)
        func_desc = connection.get_function_description(function_name)
        print (u"Parameters of function: {0}".format(function_name))

        parameter_keys = [u'name', u'parameter_type', u'direction',
                          u'nuc_length', u'uc_length', u'decimals',
                          u'default_value', u'optional',
                          u'type_description', u'parameter_text']
        parameter_widths = [20, 17, 11, 10, 9, 9, 15, 10, 15, 20]
        for key, width in zip(parameter_keys, parameter_widths):
            sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
        sys.stdout.write(u"\n")

        for parameter in sorted(func_desc.parameters, key=parameter_key_function):
            for key, width in zip(parameter_keys, parameter_widths):
                if key == u'type_description' and parameter[key] is not None:
                    sys.stdout.write(
                        u"{0}".format(parameter[key].name).ljust(width) + u" "
                    )
                else:
                    sys.stdout.write(
                        u"{0}".format(parameter[key]).ljust(width) + u" "
                    )
            sys.stdout.write(u"\n")
            type_desc = parameter['type_description']
            if type_desc is not None:
                # type_desc of class TypeDescription
                field_keys = [u'name', u'field_type', u'nuc_length',
                              u'nuc_offset', u'uc_length', u'uc_offset',
                              u'decimals', u'type_description']
                field_widths = [20, 17, 10, 10, 9, 9, 10, 15]

                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} (n/uc_length={0.nuc_length}/{0.uc_length})--\n".format(type_desc))
                for key, width in zip(field_keys, field_widths):
                    sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
                sys.stdout.write(u"\n")

                for field_description in type_desc.fields:
                    for key, width in zip(field_keys, field_widths):
                        sys.stdout.write(u"{0}".format(field_description[key]).ljust(width) + u" ")
                    sys.stdout.write(u"\n")
                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} )-----------\n".format(type_desc))
            sys.stdout.write(u"-" * sum(parameter_widths) + u"\n")
        connection.close()

    except CommunicationError:
        print u"Could not connect to server."
        raise
    except LogonError:
        print u"Could not log in. Wrong credentials?"
        raise
    except (ABAPApplicationError, ABAPRuntimeError):
        print u"An error occurred."
        raise
Ejemplo n.º 2
0
def main(function_name):
    config = ConfigParser()
    config.read('sapnwrfc.cfg')
    params_connection = config._sections['connection']

    try:
        connection = Connection(**params_connection)
        func_desc = connection.get_function_description(function_name)
        print u"Parameters of function: {0}".format(function_name)

        parameter_keys = [u'name', u'parameter_type', u'direction',
                          u'nuc_length', u'uc_length', u'decimals',
                          u'default_value', u'optional',
                          u'type_description', u'parameter_text']
        parameter_widths = [20, 17, 11, 10, 9, 9, 15, 10, 15, 20]
        for key, width in zip(parameter_keys, parameter_widths):
            sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
        sys.stdout.write(u"\n")

        for parameter in sorted(func_desc.parameters, key=parameter_key_function):
            for key, width in zip(parameter_keys, parameter_widths):
                if key == u'type_description' and parameter[key] is not None:
                    sys.stdout.write(
                        u"{0}".format(parameter[key].name).ljust(width) + u" "
                    )
                else:
                    sys.stdout.write(
                        u"{0}".format(parameter[key]).ljust(width) + u" "
                    )
            sys.stdout.write(u"\n")
            type_desc = parameter['type_description']
            if type_desc is not None:
                # type_desc of class TypeDescription
                field_keys = [u'name', u'field_type', u'nuc_length',
                              u'nuc_offset', u'uc_length', u'uc_offset',
                              u'decimals', u'type_description']
                field_widths = [20, 17, 10, 10, 9, 9, 10, 15]

                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} (n/uc_length={0.nuc_length}/{0.uc_length})--\n".format(type_desc))
                for key, width in zip(field_keys, field_widths):
                    sys.stdout.write(u"{0}".format(key).ljust(width).upper() + u" ")
                sys.stdout.write(u"\n")

                for field_description in type_desc.fields:
                    for key, width in zip(field_keys, field_widths):
                        sys.stdout.write(u"{0}".format(field_description[key]).ljust(width) + u" ")
                    sys.stdout.write(u"\n")
                sys.stdout.write(u" " * 4 + u"-----------( Structure of {0.name} )-----------\n".format(type_desc))
            sys.stdout.write(u"-" * sum(parameter_widths) + u"\n")
        connection.close()

    except CommunicationError:
        print u"Could not connect to server."
        raise
    except LogonError:
        print u"Could not log in. Wrong credentials?"
        raise
    except (ABAPApplicationError, ABAPRuntimeError):
        print u"An error occurred."
        raise
Ejemplo n.º 3
0
config = ConfigParser()
config.read('sapnwrfc.cfg')


# Callback function
def my_stfc_connection(request_context, REQUTEXT=""):
    return {
        'ECHOTEXT':
        REQUTEXT,
        'RESPTEXT':
        u"Python server here. Connection attributes are: "
        u"User '{user}' from system '{sysId}', client '{client}', "
        u"host '{partnerHost}'".format(
            **request_context['connection_attributes'])
    }


# Open a connection for retrieving the metadata of 'STFC_CONNECTION'
params_connection = config._sections['connection']
conn = Connection(**params_connection)
func_desc_stfc_connection = conn.get_function_description("STFC_CONNECTION")

# Instantiate server with gateway information for registering, and
# install a function.
params_gateway = config._sections['gateway']
server = Server(**params_gateway)
server.install_function(func_desc_stfc_connection, my_stfc_connection)
print "--- Server registration and serving ---"
server.serve(20)
Ejemplo n.º 4
0

def my_stfc_changing(
        request_context,
        **kwargs):  # TODO: Maybe only expect import/changing/tables values.
    print("my_stfc_changing was called with arguments: {}".format(kwargs))
    start_value = kwargs['START_VALUE']
    counter = kwargs['COUNTER']
    return {
        'START_VALUE': start_value,
        'COUNTER': counter + 2,
        'RESULT': start_value + 2 * counter
    }


func_desc_stfc_changing = conn.get_function_description("STFC_CHANGING")
server.install_function(func_desc_stfc_changing, my_stfc_changing)


def my_raise_error(request_context, REQUTEXT):
    ERRTYPE = REQUTEXT
    if ERRTYPE == 'EXCEPTION':
        raise ABAPApplicationError(key='BAD_EXCEPTION_HAPPENED')
    elif ERRTYPE == 'EXCEPTION_MESSAGE':
        raise ABAPApplicationError(
            key='BAD_EXCEPTION_W_MSG',
            msg_class='SR',  # message id or class
            msg_type='E',  # out of e.g. 'E', 'A' or 'X'
            msg_number='007',  # 3 char numeric
            msg_v1='V1 text'  # 50 char
        )
Ejemplo n.º 5
0
        'ECHOTEXT': REQUTEXT,
        'RESPTEXT': u"Local server here."
    }
# func_desc_stfc_connection = conn.get_function_description("STFC_CONNECTION")
# server.install_function(func_desc_stfc_connection, my_stfc_connection)

def my_stfc_changing(request_context, **kwargs): # TODO: Maybe only expect import/changing/tables values.
    print "my_stfc_changing was called with arguments: {}".format(kwargs)
    start_value = kwargs['START_VALUE']
    counter = kwargs['COUNTER']
    return {
        'START_VALUE': start_value,
        'COUNTER': counter + 2,
        'RESULT': start_value + 2*counter
    }
func_desc_stfc_changing = conn.get_function_description("STFC_CHANGING")
server.install_function(func_desc_stfc_changing, my_stfc_changing)

def my_raise_error(request_context, REQUTEXT):
    ERRTYPE = REQUTEXT
    if ERRTYPE == 'EXCEPTION':
        raise ABAPApplicationError(key='BAD_EXCEPTION_HAPPENED')
    elif ERRTYPE == 'EXCEPTION_MESSAGE':
        raise ABAPApplicationError(key='BAD_EXCEPTION_W_MSG',
            msg_class='SR', # message id or class
            msg_type='E', # out of e.g. 'E', 'A' or 'X'
            msg_number='007', # 3 char numeric
            msg_v1='V1 text' # 50 char
        )
    elif ERRTYPE == 'MESSAGE':
        raise ABAPRuntimeError(
Ejemplo n.º 6
0
def main(function_name):
    config = ConfigParser()
    config.read("sapnwrfc.cfg")
    params_connection = config._sections["connection"]

    try:
        connection = Connection(**params_connection)
        func_desc = connection.get_function_description(function_name)
        print("Parameters of function: {0}".format(function_name))

        parameter_keys = [
            "name",
            "parameter_type",
            "direction",
            "nuc_length",
            "uc_length",
            "decimals",
            "default_value",
            "optional",
            "type_description",
            "parameter_text",
        ]
        parameter_widths = [20, 17, 11, 10, 9, 9, 15, 10, 15, 20]
        for key, width in zip(parameter_keys, parameter_widths):
            sys.stdout.write("{0}".format(key).ljust(width).upper() + " ")
        sys.stdout.write("\n")

        for parameter in sorted(func_desc.parameters,
                                key=parameter_key_function):
            for key, width in zip(parameter_keys, parameter_widths):
                if key == "type_description" and parameter[key] is not None:
                    sys.stdout.write(
                        "{0}".format(parameter[key].name).ljust(width) + " ")
                else:
                    sys.stdout.write(
                        "{0}".format(parameter[key]).ljust(width) + " ")
            sys.stdout.write("\n")
            type_desc = parameter["type_description"]
            if type_desc is not None:
                # type_desc of class TypeDescription
                field_keys = [
                    "name",
                    "field_type",
                    "nuc_length",
                    "nuc_offset",
                    "uc_length",
                    "uc_offset",
                    "decimals",
                    "type_description",
                ]
                field_widths = [20, 17, 10, 10, 9, 9, 10, 15]

                sys.stdout.write(
                    " " * 4 +
                    "-----------( Structure of {0.name} (n/uc_length={0.nuc_length}/{0.uc_length})--\n"
                    .format(type_desc))
                for key, width in zip(field_keys, field_widths):
                    sys.stdout.write("{0}".format(key).ljust(width).upper() +
                                     " ")
                sys.stdout.write("\n")

                for field_description in type_desc.fields:
                    for key, width in zip(field_keys, field_widths):
                        sys.stdout.write(
                            "{0}".format(field_description[key]).ljust(width) +
                            " ")
                    sys.stdout.write("\n")
                sys.stdout.write(
                    " " * 4 +
                    "-----------( Structure of {0.name} )-----------\n".format(
                        type_desc))
            sys.stdout.write("-" * sum(parameter_widths) + "\n")
        connection.close()

    except CommunicationError:
        print("Could not connect to server.")
        raise
    except LogonError:
        print("Could not log in. Wrong credentials?")
        raise
    except (ABAPApplicationError, ABAPRuntimeError):
        print("An error occurred.")
        raise
Ejemplo n.º 7
0
class R3rfcconn(object):
    def __init__(self, r3user, r3pwd, r3ashost, r3sysnr, r3client):
        self.conn = Connection(user=r3user,
                               passwd=r3pwd,
                               ashost=r3ashost,
                               sysnr=r3sysnr,
                               client=r3client)

    def get_connection_attributes(self):
        return self.conn.get_connection_attributes()

    def get_function_description(self, func_name):
        return self.conn.get_function_description(func_name)

    def get_table_data(
            self,
            tablename: str,
            offset: int = 0,
            limit: int = 0,
            options: List = [],
            fields: List = [],
    ):
        read_table_fm = 'RFC_READ_TABLE'
        kwparam = {}
        kwparam['QUERY_TABLE'] = tablename
        kwparam['ROWSKIPS'] = offset
        kwparam['ROWCOUNT'] = limit
        kwparam['OPTIONS'] = options
        kwparam['FIELDS'] = fields
        result = self.conn.call(read_table_fm, **kwparam)
        return result

    def get_rfc_data(self, fm: str, **kwparam: dict):
        result = self.conn.call(fm, **kwparam)
        # return json.dumps(result, cls=JsonCustomEncoder)
        return result

    def get_server_wp_list(self, servername):
        '''
        get workprocess list and info by servername
        :param servername: s4ides1_DM0_00
        :return: 
        '''
        kwparam = {}
        kwparam['SRVNAME'] = servername
        kwparam['WITH_CPU'] = b'00'
        kwparam['WITH_MTX_INFO'] = 0
        kwparam['MAX_ELEMS'] = 0
        return self.get_rfc_data('TH_WPINFO', **kwparam)['WPLIST']

    def get_user_list(self):
        '''
        get SID overall wp info
        :return: 
        '''
        kwparam = {}
        return self.get_rfc_data('TH_USER_LIST', **kwparam)['USRLIST']

    def get_bkjob_status_count(self):
        '''
        tables: TBTCP,TBTCO and TBTCS, views: V_OP
        get per 15s by promethues define scrawl
        The statuses have the following meanings:

            Scheduled: not yet been released to run. P
            Released: released to run. S
            Ready: start date and time have come: awaiting execution.
            Active: currently running. R
            After a system failure, can indicate that a job was interrupted by the failure and must be manually restarted.
            
            Finished: successfully completed. F
            Aborted: not successfully completed. A
            
        :param servername: 
        :return: 
        '''

        job_finish = self.get_table_data(
            'V_OP',
            options=[
                f"STATUS EQ 'F' AND ENDDATE EQ '{date.today()}' AND ENDTIME GT '{(datetime.now()-timedelta(seconds=15)).strftime('%H%M%S')}'"
            ],
            fields=[
                'JOBNAME', 'STRTDATE', 'STRTTIME', 'ENDDATE', 'ENDTIME',
                'PRDMINS', 'PRDHOURS', 'STATUS'
            ])
        job_running = self.get_table_data('V_OP',
                                          options=[f"STATUS EQ 'R'"],
                                          fields=[
                                              'JOBNAME', 'STRTDATE',
                                              'STRTTIME', 'ENDDATE', 'ENDTIME',
                                              'PRDMINS', 'PRDHOURS', 'STATUS'
                                          ])
        job_cancel = self.get_table_data(
            'V_OP',
            options=[
                f"STATUS EQ 'A' AND ENDDATE EQ '{date.today()}' AND ENDTIME GT '{(datetime.now()-timedelta(seconds=15)).strftime('%H%M%S')}'"
            ],
            fields=[
                'JOBNAME', 'STRTDATE', 'STRTTIME', 'ENDDATE', 'ENDTIME',
                'PRDMINS', 'PRDHOURS', 'STATUS'
            ])
        return {
            "finish": len(job_finish['DATA']),
            "running": len(job_running['DATA']),
            "cancel": len(job_cancel['DATA'])
        }

    def get_dump_list(self):
        # date.today() - timedelta(1), DATE_TO = date.today(), TIME_FROM = '000000', TIME_TO = '235959')
        kwparam = {}
        kwparam['DATE_FROM'] = date.today()
        kwparam['TIME_FROM'] = b'000000'
        kwparam['DATE_TO'] = date.today()
        kwparam['TIME_TO'] = b'235959'
        try:
            return self.get_rfc_data('/SDF/GET_DUMP_LOG',
                                     **kwparam)['ET_E2E_LOG']
        except:
            return []

    def get_rfcresource_list(self, servername):
        '''
        need confirm
        :param servername: 
        :return: 
        '''
        kwparam = {}
        return self.get_rfc_data('RFC_SERVER_GROUP_RESOURCES', **kwparam)

    def get_transport_list(self):
        tablename = 'E070'
        return self.get_table_data(tablename)

    def get_st02_data(self):
        kwparam = {}
        st02data = self.get_rfc_data('SAPTUNE_GET_SUMMARY_STATISTIC')
        del st02data['TABLE_QUALITIES']
        del st02data['TABLE_STATISTIC']
        del st02data['TABLE_STATISTIC_64']
        del st02data['CURSOR_CACHE_INFO']
        del st02data['MODE_MEMORY_HISTORY']
        del st02data['INTERNAL_EXTERNAL_MODES_MEMORY']
        del st02data['BUFFER_STATISTIC_64']
        st02data_json = json.dumps(st02data, cls=DecimalEncoder)
        return json.loads(st02data_json)

    def get_st03_data_summary(self):
        kwparam = {}
        kwparam['READ_START_DATE'] = date.today()
        kwparam['READ_END_DATE'] = date.today()
        kwparam['READ_START_TIME'] = (datetime.now() -
                                      timedelta(seconds=60)).strftime('%H%M%S')
        kwparam['READ_END_TIME'] = (datetime.now() -
                                    timedelta(seconds=0)).strftime('%H%M%S')
        st03datadetail = self.get_rfc_data('SAPWL_SNAPSHOT_FROM_REMOTE_SYS',
                                           **kwparam)
        st03datadetail_json = json.dumps(st03datadetail['SUMMARY'],
                                         cls=DecimalEncoder)
        return json.loads(st03datadetail_json)

    def close(self):
        self.conn.close()
Ejemplo n.º 8
0
from pyrfc import Connection

import pickle

client = Connection(dest="MME")

fd = client.get_function_description("BAPI_USER_GET_DETAIL")

print(fd)
Ejemplo n.º 9
0
import signal
import sys



config = ConfigParser()
config.read('sapnwrfc.cfg')

# Callback function
def my_stfc_connection(request_context, REQUTEXT=""):
    return {
        'ECHOTEXT': REQUTEXT,
        'RESPTEXT': u"Python server here. Connection attributes are: "
                    u"User '{user}' from system '{sysId}', client '{client}', "
                    u"host '{partnerHost}'".format(**request_context['connection_attributes'])
    }

# Open a connection for retrieving the metadata of 'STFC_CONNECTION'
params_connection = config._sections['connection']
conn = Connection(**params_connection)
func_desc_stfc_connection = conn.get_function_description("STFC_CONNECTION")

# Instantiate server with gateway information for registering, and
# install a function.
params_gateway = config._sections['gateway']
server = Server(**params_gateway)
server.install_function(func_desc_stfc_connection, my_stfc_connection)
print "--- Server registration and serving ---"
server.serve(20)