2012-06-10

Using XBP to manage SAP jobs from PHP

SAP XBP vs 3, is the API for accessing SAP background processes. XBP requires you to log on to the XMI-XBP subsystem. XMI= External Monitor Interface , XBP= External Interface for Background Processing . This sounds awful complicated but It is not that complex. You logon to the XBP subsystem by calling 'BAPI_XMI_LOGON'  this is a normal BAPI call and then you just proceed with the XBP BAPI functions you like to use.

Before you proceed you should learn about XMI and XBP .

Calling the XMI and XBP BAPIs from PHP is no different from calling any other BAPIs or RFC functions from PHP. First you need to install an interface between PHP and SAP. Google on SAPRFC by Eduard Koucky, this project looks dead to me, but Axel  Bangert seems to have picked up SAPRFC. Piers Harding have created a Unicode aware interface SAPNWRFC.  You should Google around and pick the right interface for you. (I’m slowly migrating from SAPRFC to SAPNWRFC. Examples in this post are using Koucky’s original  SAPRFC, which is the simpler interface to use.)

I have written a   job scheduler in PHP , there I have created some functions of my own on top of the SAPRFC and SAPNWRFC interfaces, for logging on to SAP and calling SAP BAPI and RFC functions. The examples here are using my scheduler and my interface functions. Before you proceed you should enjoy my post   extract data from SAP , here you can learn a very useful technique how to use SAP’s transaction SE37 to set up call to SAP functions and transform the in- and out-put parameters to my job scheduler in PHP.

I use the SAP XBP interface to monitor SAP batch jobs or background processes, i.e. I check if SAP jobs have run (successfully) before I kick off my external PHP jobs. (XBP is not limited to monitor you can fully manage background processes in SAP via XBP.) Here is another example .

This somewhat artifical example loads all SAP jobs with names starting with ‘TOO’ into MySQL, if the job ‘TRPX_LE_WRHSEMONITOR_ALL’ was run successfully the during the last 2 days. Then an Excel sheet is created and mailed.

The important pieces of code here are:

the prereq, which checks if job(s) are run in SAP.

<xmi><session>XBP</session></xmi>, explicit log on to XMI/XBP

<schedule name='BatchList' logmsg='Automagically load of SAP rfc output  into mysql table(s)'>

        <tag><name>DW_DB</name><value>test</value></tag> <!-- MySql database -->

         <!-- only run if SAP job executed ok the last 2day -->

         <prereq type='sap' jobname='TRPX_LE_WRHSEMONITOR_ALL' username='*' executed='now-2d'/>

        

        <job name='get_Jobs' type='script' data='sap2.php'>

                <sap>

                        <xmi><session>XBP</session></xmi>

                        <rfc>

                                <name>BAPI_XBP_JOB_SELECT</name>

                                <import>

                                        ('EXTERNAL_USER_NAME',$sapContact['xmi']['EXTERNAL_USER_NAME'])

                                        ,('SELECTION','AL')

                                        ,('JOB_SELECT_PARAM',array('JOBNAME'=>'TOO*',     'USERNAME'=>'*','ABORTED'=>'X','FINISHED'=>'X','ACTIVE'=>'X', 'FROM_DATE'=>@TODAY))                                                                                 </import>

                        </rfc>

                </sap>

                <script><sql>

                <autoload>replace</autoload><database>@DW_DB</database><truncate>yes</truncate>

                <table>JOB_HEAD=tooJobHeads</table><tableX>SELECTED_JOBS</tableX>

                </sql></script>

        </job>

        <job name='generate_report' type='sql'>

                <sql>

                        USE @DW_DB;

                        SELECT *  from tooJobHeads;

                </sql>

                <sqlconverter>

                        <name>sqlconverter_ExcelBasic.php</name>

                        <target>report</target>

                </sqlconverter>

        </job>

        <job name='send_mail' type='sendmail'>

                <mailer>phpmailer</mailer>

                <recipients>lasse@mysite.se</recipients>

                <subject>Fyi: batch jobs and XMI</subject>

                <div>

                Hi,

                This is an artificial example but it shows the Sap connectivity implemented in ACTADW.

                

                The mail you recieved contains two attachments this file (schedule.xml) and an SAP job status report.

                The schedule.xml file contains all commands necessary:

                        1 Check that the Sap job TRPX_LE_WRHSEMONITOR_ALL is sucessfully executed during the                        last 2 days, otherwise the execution is intercepted.

                                                2 Extract the information from SAP.

                        3 Load  the extract  into ACTADW.

                        4 Create a report.

                        5 Create this mail and send it.

                Lars Johansson

                </div>

                <attachment>

                        <name>batchStatus.XLS</name><file>@J_generate_report/report0.XLS</file>

                </attachment>

                <attachment>

                        <name>schedule.xml</name><file>/dw/schedule/example10.xml</file>

                </attachment>

        </job>

</schedule>

 

The PHP code for Logon to XMI

/**

*  This function logs on to the Sap XMI subsystem

*

* Before you log on to the SAP XMI subsystem, you should log on to SAP with {@link connect2sap()}, and before you

* disconnect from SAP you should log off from XMI with {@link sapXmiLogoff()}.

*

* Syntax: <samp><xmi session='XAL'/></samp>

* @todo update SAP3.php

* @see sapXmiLogoff()

* @param array $context

* @param object $sap Handle to saprfc interface

* @return string $sessionid The XMI sessionid

* @uses callSapFunction()

*/

function sapXmiLogon($context,&$sap,$xmiType='XBP'){

        $log = $GLOBALS['log'];

        $log->enter('Info');

        if (!$sap) return FALSE;

        $sapContact = $context['sapinfo'];

        switch ($xmiType) {

        case('XBP'):

                $fce=callSapFunction($sap,'BAPI_XMI_LOGON',array(

                        array('import','EXTCOMPANY',$sapContact['xmi']['EXTCOMPANY'])

                        ,array('import','EXTPRODUCT',$sapContact['xmi']['EXTPRODUCT'])

                        ,array('import','INTERFACE','XBP')

                        ,array('import','VERSION','3.0')

                        ));

        break;

                default:

                $log->logit('Error',"Unknown SAP XMI session type=$xmiType");

                return FALSE;

        }

        if ($fce->GetStatus() == SAPRFC_OK) {

                $log->logit('Info',sprintf("SAP XMI session established sessionid=%s",$fce->SESSIONID));

        } else {

                return FALSE;

        }

        $sessionid = $fce->SESSIONID;

        $fce->close();

        return $sessionid;

}

And the code to evaluate the SAP prereq at the beginning of the the XML schedule example ‘BatchList’ above.

/**

*  This function evaluates a Sap job predecessor by calling BAPI_XBP_JOB_SELECT

*

* The parm 'SINCE' allows a more relaxed call to BAPI_XBP_JOB_SELECT.

* <samp>

* <stmt type='sap' JOBNAME='TRPX_LE_WRHSEMONITOR_ALL' USERNAME='*' SINCE='now-1d'/>

* </samp>

* Parm 'SINCE' calls {@link tagday.php} to convert the argument to a point in time, which is translated into

* the parameters 'FROM_DATE' and 'FROM_TIME'. The FINISHED parameter will also be set ('X') as default.

*

* Parms to BAPI_XBP_JOB_SELECT: <br>

* 1  JOBNAME Background job name

* 2  USERNAME Initiator of job/step scheduling

* 3  FROM_DATE Planned Start Date for Background Job

* 4  FROM_TIME Planned start time for background Job

* 5  TO_DATE Planned Start Date for Background Job

* 6  TO_TIME Planned start time for background Job

* 7  NO_DATE Selection flag for jobs without start date

* 8  WITH_PRED Selection flag for jobs with start after predecessor

* 9  EVENTID Background Processing Event

* 10 EVENTPARM Background Event Parameters (Such as, Jobname/Jobcount)

* 11 PRELIM State of Background Job

* 12 SCHEDUL State of Background Job

* 13 READY State of Background Job

* 14 RUNNING State of Background Job

* 15 FINISHED State of Background Job

* 16 ABORTED State of Background Job

*

* @param array $context

* @param array $cb this is $schedule for schedule prereqs and $job for job prereqs

* @param array $stmt the schedule prerequisit statement

* @param object $sap Handle to saprfc interface

* @return int $jobcount no of executed predecessor jobs with status finished|complete, caller can test for TRUE

* @uses callSapFunction()

* @uses tagday.php

*/

function checkSapPredecessor($context,$cb,$stmt,&$sap){

        $log = $GLOBALS['log'];

        $log->enter('Info');

        if (!$sap) return FALSE;

        if(!array_key_exists('JOBNAME',$stmt)) return TRUE;

// We only check if sap is alive, and if we pass here sap is responding so...

        $sapContact = $context['sapinfo'];

        $jsp = array_intersect_key(array_change_key_case($stmt, CASE_UPPER)

                ,array('JOBNAME' => '','USERNAME' => '','FROM_DATE' => '','FROM_TIME' => '','TO_DATE' => ''

                ,'TO_TIME' => '','NO_DATE' => '','WITH_PRED' => '','EVENTID' => '','EVENTPARM' => ''

                ,'PRELIM' => '','SCHEDUL' => '','READY' => '','RUNNING' => '','FINISHED' => '','ABORTED' => ''

                ));

        if(array_key_exists('SINCE',$stmt) or array_key_exists('since',$stmt)){ //relaxed form

            $script = 'tagday.php';

            $proc = $context['opsproclib'];

            $parm = 'YmdHis'.$stmt['SINCE'];

            $log->logit('Info',"Calling $proc$script with parm=$parm");

/**

* Require tagday.php to evaluate the executed statement

*/

            $dtStr = require("$proc$script");

            $fromDate = substr($dtStr,0,8);

            $fromTime = substr($dtStr,8,6);

            if(!array_key_exists('FROM_DATE',$jsp)) $jsp['FROM_DATE'] = $fromDate;

            if(!array_key_exists('FROM_TIME',$jsp)) $jsp['FROM_TIME'] = $fromTime;

            if(!array_key_exists('FINISHED',$jsp)) $jsp['FINISHED'] = 'X';

            if(!array_key_exists('USERNAME',$jsp)) $jsp['USERNAME'] = '*';

        }

        $log->logit('Info',vsprintf("Enter checkSap %s, %s, %s, %s, %s", $jsp));

            $log->mode('None'); //We do not wish to see SAP empty selections warning messages

            $fce=callSapFunction($sap,'BAPI_XBP_JOB_SELECT',array(

                    array('import','EXTERNAL_USER_NAME',$sapContact['xmi']['EXTERNAL_USER_NAME'])

                    ,array('import','SELECTION','AL')

                    ,array('import','JOB_SELECT_PARAM',$jsp)

                    ));

            $log->reset('mode'); // Reset log to original verbose mode

        if ($fce->GetStatus() == SAPRFC_OK || $fce->GetStatus() == '99') {

                $jobcount = 0;

                $fce->JOB_HEAD->Reset();

                while ( $fce->JOB_HEAD->Next() ) {

                        $jobcount++;

                }

        } else {

                return FALSE;

        }

        if(!$jobcount) $log->logit('Note',sprintf("SAP predecessor job %s not executed successfully after $fromDate $fromTime",$stmt['jobname']));

        return $jobcount;

}

2012-06-09

Replicating MySQL with Rsync

In a previous post  I wrote about replicating Business Intelligence information to Local Area Networks satellites. A BI satellite is a database server with replicated BI information from a master BI system. The BI satellite must be affordable and simple to operate, otherwise you are unlikely to get funds for the satellite. And you need a backup a plan B, if which God forbid the satellite breaks down.

Our Business Intelligence system The Data Warehouse is designed with this in mind. The BI data is stored in a MySQL database, day2day reporting and the legal financial reporting is done by ODBC/Excel, which all users have on their PCs. So all we have to do is set up a simple Mysql database server and replicate the database(s) from the Master Data Warehouse to the satellite system. The master system is also the backup, if the satellite breaks down, we reroute the users to the master via the DSN entry.

Note! all user definitions must be identically defined in the master for this to work. This is a manual process I do not have a good solution for yet.

The satellite server

The ‘server’ for this particular satellite is a Dell Optiplex 790 with an Intel I3 processor 4GB RAM and  two 1TB SATA disks. On this computer I installed Ubuntu 12.04 LTS server with SSH and LAMP. I failed to install the second disk, my plan is to put /var  on the second disk, this is something I still have not figured out to how to do. I also installed phpMyAdmin on the server. This was my first install of an Ubuntu Linux, I had some initial problems (as the second disk), but most problems are solved and I have a working and tested prototype satellite system.

Replication

The absolute simplest way to replicate data is Rsync, a brilliant piece of software. Our Business Intelligence information is updated in controlled nightly (whatever that means when you are global) batch jobs. This means we do not have to use more complicated database replication schemes, we can replicate in controlled batches. The MySQL storage engine MyISAM is perfect for such replication since it uses the directory structure on disk as index to databases and tables. Just stop mysql, replicate and start mysql again. We like to initiate the replication from our master data warehouse when time is due. The satellite system decide where the data should go. This can be achieved by some simple shell scripts (not done yet) and a Rsync Daemon in the satellite server. This replication not only simple it is also self-healing. If something goes wrong, just replicate again.

Setup

The Rsync daemon is configured by three  files.

1  - The first file rsyncd.conf  contains the actual configuration. With some embarrassment I have to admit I do not understand all parameters yet.  (Go to everythinglinux.org  for a detailed explanation).

Note! the path parameter points directly into the MySql database SATDW

rsyncd.conf

pid file = /var/run/rsync.pid

log file = /urs/local/etc/rsyncd.log

lock file = /var/run/rsyncd.lock

[satwd]

            comment = Replica of the Data Warehouse

            path = /var/lib/mysql/SATDW/

            transfer logging = yes

            hosts allow =  nn.nn.nn.nn

            auth users = userid

            transfer logging = yes

            read only = no

            uid = mysql

            gid = mysql

            use chroot = yes

            strict modes = no

            secrets file = rsync.scrt

End-of-rsyncd.conf

2  -The next file rsync.motd  just contains a greeting message.

rsyncd.motd

Welcome to the Data Warehouse server Rsync Daemon    

End-of-rsyncd.motd

3  - The last file rsync.scrt  contains userid and passwords. Note! these userids are internal to Rsync daemon.

rsync.scrt

userid:password

End-of-rsync.scrt

With these three files defined its just to start up the Rsync Daemon and start replicate.

Replication

My first attempt was with one table.

rsync --stats --archive --delete -H /db/mysql/DW/table* userid@SATDW::satdw

Number of files: 4

Number of files transferred: 4

Total file size: 49600686 bytes

Total transferred file size: 49600686 bytes

Literal data: 49600686 bytes

Matched data: 0 bytes

File list size: 89

File list generation time: 0.001 seconds

File list transfer time: 0.000 seconds

Total bytes sent: 49607129

Total bytes received: 84

sent 49607129 bytes  received 84 bytes  62913.40 bytes/sec

total size is 49600686   speedup is 1.00

This was kind of depressing, it took some 17 minutes to replicate this one file the speed 62913.40 bytes/sec was all too slow. I added --compress to my replication

Compression, need for speed

rsync --stats --archive --delete --compress  -H /db/mysql/DW/table* userid@SATDW::satdw

This time I got:

Number of files: 4

Number of files transferred: 4

Total file size: 49600686 bytes

Total transferred file size: 49600686 bytes

Literal data: 49600686 bytes

Matched data: 0 bytes

File list size: 89

File list generation time: 0.001 seconds

File list transfer time: 0.000 seconds

Total bytes sent: 5438439

Total bytes received: 84

sent 5438439 bytes  received 84 bytes  59437.41 bytes/sec

total size is 49600686   speedup is 9.12

With compression the replication took about 90 seconds, much better, but not good enough. My Slave satellite concept will not work if I cannot double the transfer rate. It seems I only get about 60Kb/sec which is much less than expected. I will talk to the Network guys to see what they can do to speed things up. I suspect there is some kind of limitation enforced upon my replication. If I could get at least 100Kb/sec I think my replication will work. I expected +200Kb/sec so clearly this is a disappointment.  

Next

The next thing to do is to talk with the network guys, I need more speed. And then I have to automate the replication with some shell scripts. Then I write another post , I really hope this will fly :-|

 

2012-06-06

Business Intelligence in every LAN

I like Business Intelligence repositories hooked up in Local Area Networks not in Wide Area Networks. There is many good reasons for this, even in this day and age with global communications we have to consider bandwidth. According to Albert Einstein it will always be faster to send information 50 meters than across the world. And more important LAN access will not only provide faster response, but also more secure and consistent response times.
The best reason though - it’s a cool concept  - Business Intelligence in every LAN.

Cool concept

I designed our Business Intelligence system The Data Warehouse so it is
practically possible to implement a satellite in every LAN. It must be dirt
cheap to install a satellite system otherwise it will never happen. Just try to
tell the guys with the money
‘we need to invest +100,000€, so the production planners in the far away workshop can have decent response times for their what-if-analysis’ . That will never happen, maybe for the financial guys, but never for the production people. ( Business Intelligence  is more than financial analyses, this is often overlooked.) But if the satellite system costs less than 2000€, there is a better chance for the investment of a satellite.

Simple operations

It is also of great importance the operations of the satellite is simple. In an ideal
world you should only fire it up once and forget about it. In the real world
however it is not so simple, there are power outages, earthquakes and many other
unpleasanties that actually happen. But supervision and operations intervention
must be kept to a minimum. Very important.
The satellite is still not operational, but I have an idea how to set up a simple, effective and self-healing  replication between Osaka and Stockholm. You can cut corners with Business Intelligence systems. E.g. Business Intelligence data is mostly updated in controlled batch jobs, which implies replication can be done in controlled  background jobs,no need for continuous instant replication.
A Business Intelligence system done right can be down, it should not be necessary to have it online 24X7. The ERP systems probably have to be up 24X7, but not the BI system. This is one of the great things working with BI, you do not have to go up and fix problems in the middle of the night, it can wait until the morning :-)  I have spent many nights in server rooms (and outside) fixing urgent ERP problems, and that is not fun.
Rsync and MySQL
You want to initiate the Business Intelligence replication from the master system when
time is due, but the satellite system should decide where the data should go. The
replication should also be simple, fast and self-healing. And of course you need a backup.
I think I found a very nice way to achieve this by using Rsync and MySQL MyISAM databases and a little bit of bash shell programming. If I fail, I may have some explaining to do. I have already told my bosses I have a working solution, so they probably want to know why it do not work. I will post the details in a coming post .

2012-06-03

文字化け and three little piggies.

The Swedish alphabet has three national characters Å,Ä and Ö.

Å  = the vowel in y ou r, Ä  = the vowel in b ea r  (the animal), Ö  = the vowel  in S i r.

These three characters have haunted me throughout my IT career. I cannot recall how many times I created the 256 bit string with all hex combinations from ‘00’ to ‘ff’, and sent the string across lines between computers to verify the string is the same when it arrives at the receiving computer. In the IBM mainframe EBCDIC coding world you may think it will always work, but no  it does not. There is often nodes in between that do intermediate ‘translations’, and applications that have their own character translations.  When character translations did go wrong it was mostly due to ‘my’ three national characters Å,Ä,Ö or the three little piggies as I call them. But still it was relatively simple only 256 characters to keep track of and you could easily implement your own translate-tables in between. 1985 with the help of converted telex machines we transferred  data (program-to-program communication) between a IBM mainframe in Stockholm and one in Antwerp and of course the three little piggies showed their ugly faces.

Today we have better ways to communicate data than converted telex machines. ( In Unix they probably already had better communication in the 19th century. According to Unix guys, Unix is always better. )  Even if today’s communication facilities are better they are not less complicated, today we communicate not only with western Latin alphabets but with Cyrillic, Kanji, Katakana, Hanji etc. and we have Unicode to make this simple. But converting old encoding into Unicode is not simple and Unicode is not uncode but there are UTF8, UTF16 etc. there are a variety  of Unicode encodings. And how should you encode and decode character strings? E.g. I think we all have seen and are seeing double Unicode encodings on the web and in mails. If we in western Europe have problems with character encoding this is nothing with the problems others have. The Japanese have three alphabets, Kanji, Katakana and Romanji, and at least Kanji have two forms new and old. It must be hell to convert between these character representations. Consequently the Japanese  have a special word for  character conversion problems mojibake,  which I think means false character or something similar.

Today our Business intelligence application the Data Warehouse only support ASCII codes, but we will convert our data to UTF-8, to support other alphabets , since we are spreading the Data Warehouse to Japan and China. Russians complains they cannot use the Data Warehouse since Cyrillic shows as ‘X’. I became aware of this embarrassing fact just some month ago. In theory it looks simple to convert from ASCII to Unicode, but I fear it is very complex. We have to change the hole chain of tools  supporting all from extracting data from the source systems to our data storage which is MySQL. To me it does not look like MySQL excels in character encoding conversions, there are myriads of parameters involved in character conversions and the UTF-8 encoding which we will use is not the standard UTF-8. The next MySQL release 5.6 will introduce standard UTF-8 encoding. I fear I will end up with many unexpected ‘challenges’ or ‘possibilities’. If you dear reader have advice to give me please tell.

Extending Business Intelligence by a satellite Ubuntu LAMP server

I’m writing this post from Helsinki airport while waiting for my flight to Stockholm, after a week at our Osaka workshop Fuji Air Tools , where I installed an Ubuntu LAMP-server. This is my first install of Ubuntu server. I always used Mandriva Linux with a KDE graphical desktop. I really like Mandriva and KDE. But The future for Mandriva is a bit unsure and this server should be maintained by me from the other side of the world, so I thought I should go for a more popular Linux distro. These two Linux environments are very different. It’s like comparing DOS with Windows with one funny quirk, I’m going from Windows to DOS so to speak. Since I always used a very good graphical environment in Mandriva I never learned Linux commands and absolutely not the VI editor . I have once sworn to I would never use VI, an awful text based editor from anno dazumal.

Many years ago I worked as a IBM Mainframe systems programmer at a large outsourcing company, actually I was outsourced to this company. Anyway, we systems programmers decided we needed information about Linux, a Linux expert was hired for a one day presentation about Linux, and the moron started the day by saying ‘Now I will show you the best editor in the world, the VI editor’. After 10 minutes and about 100 three-finger pirouettes, half of us left the presentation. We had the fantastic SPF-editor which is light years ahead of the EDLIN like VI editor.

Fortunately Linux distros comes with the Nano editor  which is simpler to work with, you do not have to be a rocket scientist  to change a file with Nano. So I went to the other side of world to install a text based Linux distro  I had not seen before and a concept for replicating Mysql databases based on Rsync not used before and I intend to remote administer the server from home.

With the help from the local IT-guys, which had not worked with Linux before, they have an IBM I-series computers and MS Windows servers, I installed Ubuntu 12.04 LTS server with SSH and LAMP on a Dell Optiplex 790 with two hard disks. I failed to install the second disk, my plan is to put /var  on the second disk, this something I have to learn how to do when I come home. Neither could I make DNS lookups to work properly, I suspect the DNS setup is changed in Ubuntu 12.04, this too I have to fix from home. A very odd thing happened, I could not install the GRUB boot loader with the Japanese proxy, but I had to use a proxy in Sweden or no proxy at all! My gut feel is this is a timing problem in the Ubuntu install, the Japanese proxy responds to fast. At time of writing I have no clue how to replace the very distant and slow Swedish proxy with a fast responding Japanese proxy now when the install is done. The last piece of configuration setup an Rsync server, again I have to do this from home, the time run up for me. But when this is done, we should have local LAN response times  on the other side of the world. I pray please let this concept work,   we will see how it goes  the next coming weeks . I am certain unexpected problems like this one  will show up.

At last a very big thank you to the Fuji Air Tools IT team, these guys are great. They had loads of work on their shoulders, still they were very friendly and helpful. They had not worked with Linux and Mysql before, but they did the final install themselves.

     

P.s.

Being at Helsinki Airport, yes of course I have bought a bottle of black Salmiakki Vodka . But not for tonight. I’m so jet lagged alcohol would kill me, I just want to go home and sleep.      

2012-05-26

Replicate Business Intelligence Data across the globe

Working in a multinational company you sometimes end up in places you never dreamed of. I’m writing this from  a hotel room in Osaka; Japan. We have a factory here, and we are implementing SAP for purchasing, logistics and production planning, and accompanying SAP is our Business Intelligence system the Data Warehouse, (which is my responsibility). When testing response times from the Osaka plant ‘Fuji Air Tools’ half a year ago , the response times were slow. I was asked if we could do something to speed up response times. I hope this is  easy, we just install a local Data Warehouse server replica in the Osaka plant. Any decent workstation PC  will do since we will just replicate some MySql databases over to Osaka. My plan is to use a very simple Rsync replication scheme. Each day when time is due we just offline the ‘Osaka database ‘ and rsync it from the master in Stockholm.
Why not set up real time replication? I tried this a few times, but this is more complicated. Live replication must be monitored, and it inevitably will fail at some time in a way manual intervention is required. My Rsync replication is simple and self-healing if it which God forbid should fail. (Just rerun the rsync.)
I hear people say you cannot backup/copy/replicate a live database like that. You must at least flush the tables and block updates of the master during Rsync, otherwise you will have a corrupt replica. But I will Rsync until there is no differences between the replica and the master. This is a BI system and updates are mostly controlled background  jobs. My Rsync scheme will work well.

Doers and Thinkers.

I am of the opinion BI systems should be on Local  Area Networks not Wide  Area Networks. BI systems shuffle lot of data, response times will always be better in a LAN, and the band width can be used better than repeatedly send BI analysis queries, this is what the thinkers  do. What happens if I change… and then the thinker resubmit a similar query once again and thinkers result tables are often big.
You can divide Business Intelligence users into Doers  and Thinkers . Doers logs on early in the morning and use the BI system for their daily job. They run their reports, e.g. in a factory production planners and logisticians may analyze component shortages and  adjust today's production accordingly. Thinkers on the other hand come in later and work with issues like ‘What happen if we build a new plant in...’ . And they tend to not only browse through lot of data they also pick up a lot of data.

Scared of airports, not feared of flying.

This is not at all what I intended to write. I intended to write about my adventures in airports, with the title scared of airports not of flying. Coming to an airport is like descend into hell, I probably have a pulse rate like a soldier in combat. For me everything goes wrong, this time I started by losing my boarding cards. It is not until I’m on the airplane I can calm down.
You know these self-checking machines where you are supposed to type in your booking number, e-ticket number or whatever. I NEVER type the right number, I type the forms number, the date or something that these stupid machines do not recognize as me.
I do not like airports, it seems to be genetic .

2012-05-20

User triggered SAP data loading into a MySQL database from MS Excel

A strategy for real time reporting and loading of Business Intelligence Layer.

From an Excel sheet Button, a signal is sent to a Linux ETL system, that starts a process to fetch ‘delta data’ from a SAP system and update the Business Intelligence data storage in this case a MySQL database.

In a  previous post  I have written about the importance of  performant ETL  processes see   When fast is not enough , you may also want to look at extracting data from SAP  and schedule jobs with PHP . In this post  I will take this  a bit further. Here I show how you can do BI real time reporting with the help of a performant  ETL and Visual Basic in MS  Excel.
The example this post  is based on is a P roof of C oncept and there are still details not fully worked out. But testing so far has been successful.

The merge delta load method

A separate business intelligence (BI) system and real time reporting is easier said than done. Since the BI data is physically separated, there will always be latency, the time it takes to transfer data from the source system to the BI layer. The only way to achieve real time reporting is to do the reporting in the source ERP system. But there are strategies to minimize latency and achieve pseudo online reporting, where the latency is acceptable for the users. Normally you pull data from your source ERP systems at regular intervals, e.g. each night, week or month. To achieve realtime reporting you can increase the pull frequency e.g.  extract data each hour gives  better reconciliation than once a day. However the strain on the computer systems and networks increases with pull frequency and this method does not give online reporting.   The merge delta load method  first fetch data from the BI system and then fetch the delta data from the source ERP system and then merge the two data streams into the report. Although this method gives good real time reporting, there are several disadvantages with this method. It adds complexity to the client, since the client must be able to contact the ERP system and merge the report with ERP delta data. Each time the report is requested the delta data has to be extracted from the ERP system. This means all reports suffer from the response time delay of retrieving data from the source ERP system. Since the BI layer is not updated this delta load is growing with time until next BI layer update.
 
Figure 1a                                                                                                         
Figure 1a shows this scenario. If we now add a user as in Figure 1b we now double the delta extraction from the source ERP system as each user have to fetch the data for his/her report(s).
Figure 1b
With a large number of users this method may extract a lot of data over and over again from the ERP system. If we add another source ERP system as in Figure 1c, this solution becomes very messy. Now the BI client must be able to connect to different source systems and extract and merge all data streams with the base report. The merge delta load method is not very elegant and scales poorly.
Figure 1c

Another approach – user triggered Delta Load

In this example I have  taken another approach to real time reporting.  The merge delta load method is complex and requires special client software to delta load and merges different data streams. Another approach  is to run the ETL process more frequent. But this solution will potentially create a lot overhead by running lots of delta load ETL without any purpose at all. Instead of fire off frequent loads we let the user trigger the ETL. This solves the problem of running lots of meaningless ETL data loads, since we only run the ETL on user request. This way all users benefits from the delta load, data is only extracted once. Instead of retrieving delta data from the source ERP systems, the client sends a signal to the ETL system to start a delta load process  and when the ETL process is finished request the report (see Figure 2a).
 
Figure 2a
This request triggered  update will create a report that is almost real time provided the ETL process is fast. Unfortunately this method requires event based VBA programming in the Excel client, which is currently above the skill level of the author. There is a simple yet elegant way to overcome this technical problem, give the user an update button and let the user trigger the update.  
User triggering simplifies the real time reporting process but the workflow can be depicted the same way as request triggering, the only difference is data extraction from source systems only occur when requested by the user .When we add a user (Figure 2b) we start to see the benefits compared with the merge delta load (Figure 1b).
Figure 2b
No double delta loading since all data extraction updates the common BI layer only once, no matter how many users is added. Adding source systems does not change the picture much, see Figure 2c. We still got a simple and clean real time reporting process.  On the other hand user triggering requires a performant ETL process otherwise the response time will be slow and the report will be old and not real time.  User triggering also requires strict synchronization isolating of individual ETL updates. I will show how I have implemented user triggering for real time reporting.
Figure 2c

User triggered Delta Load  – an   example.

In this example we real time report COPA data from a  SAP system. The reporting is done within an Excel sheet.

The sheet

Figure 3
This is what the user sees when the Excel sheet is invoked. When the user trigger button is pressed a signal is sent to the ETL  to run the delta load  process (see Figure 2a). The ETL status field shows the start, stop and outcome of the last ETL run [1] . The ETL status field is ‘click’ sensitive, click it and the status is updated. In this prototype the ETL process is controlled manually, press the ‘Extract from SAP’ button to fire off the ETL process, click the ‘ETL status’ field to update the status. This is complex real time reporting reduced to a simple, practical and scalable solution. A button and a field    gives the user the power of real time reporting. (There is a lot more to this Excel sheet but that is outside the scope of this post .)

Under the hood

 There is more to it than the button and the field, there are a lot going on under the hood.  The status field is simple, when clicked it just retrieves the status from the ETL system  via a simple ODBC SQL request. The ‘extract’ button is trickier it must contact the   ETL engine which resides in a Linux server and send the signal ‘run Delta Load ’. First we establish a Secure Shell  connection to the Linux server using the Open Source PuTTY program Plink  then we just send the signal ‘run Delta Load’  and disconnect from Linux. The Excel  VBA code  that does the trick can be found in Appendix A.
The Delta Load  procedure is too large to discuss here. In Figure 4 you can see an abbreviated version outlining the job steps.
Figure 4
There is one line of special interest in the procedure, the <prereq type=’singleton’>  restricts the execution of the procedure, it must run alone. If a sibling process already runs this instance dies immediately.  Look at Figure 2 b . If both users send the ‘run ETL’ signal simultaneously one must yield, and this is what this <prereq> does. You can queue the request up by adding a wait to the <prereq>. Since one ETL run will serve all users, it is not necessary to run more than one ETL at a time. This is a very important  simplification, simultaneously updating of large amounts of data is not trivial, and it requires complex logic and slows down the execution.

Response time

The Excel sheet (Figure 3) is a report generator that slices and dices the SAP COPA data. Normally the response time is around one second for generating a report, this is quite a feat since there are a lot of COPA data. This is achieved by ‘in memory computing’. We try to keep data in memory by various caching techniques. When the COPA data is not in memory there may be an initial less than a minute delay [2] .  Since the ETL load time is added to the report response time (if you need an updated report) it is essential to keep the ETL load time low. ETL load statistics (see Appendix B) gives you can normally ETL load 2 to 3 thousand rows in 15 seconds. Two background ETL load jobs a day will keep maximum rows for additional user triggered ETL load below three thousand rows. This is probably a well balanced ETL load scheme. But in the end it is up to user to decide, it is simple to change the ‘background frequency’.

Appendix A – Excel VBA code sends ’run Delta load ’ signal.
Private Sub CommandButton2_Click()
    Dim resVar As Variant
    commspgmP = "C:\Program Files\PuTTY\plink.exe"
    commspgm = """" & commspgmP & """"
    'MsgBox commspgm
    If Dir(commspgmP) = "" Then
        MsgBox "You must install " & commspgmP & " to update BI!" & " http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html"
        Exit Sub
    End If
    hostuser = " -v -l viola -pw xxxxxx DWETLserver"
    cmdtxt = " /home/tooljn/dw/pgm/scriptS.php schedule=COPA_DeltaLoad02.xml logmode=w onscreen=no"
    resVar = Shell("cmd /c " & commspgm & hostuser & cmdtxt, vbMinimizedFocus)
'MsgBox commspgm & hostuser & cmdtxt & "  -  result=" & resVar
    Sleep (2000) ' Sleep for 2 seconds to allow BI update to commence before we...
    Call displayLastUpdate
End Sub
Comments to the code:
This is my first piece of VBA code and I have trial&error it until it worked, I do not know VBA well.
 The line hostuser = " -v -l viola -pw xxxxxx DWETLserver"   is not very elegant. You should  not have hard coded credentials! However in this case it’s benign, the user viola  cannot do anything else but run our ETL process COPA_DeltaLoad02.xml. Going into production this will be replaced by certificates. The user ‘viola’ is in honor of my late and very beloved granny Viola. She was from north of Sweden, her father was chief engineer of the Boden fortress  and an inventor. The German Wehrmacht tried to enlist him, but he declined, which I am grateful for, that made it possible for my grandfather (an orphan with no means from south of Sweden) to meet Viola. He served as a sergeant at the fortress. After marriage and my mother were born he had a motor cycle accident and he was relocated to Stockholm, administrating arms purchase at the Army HQ just 100 meters from my present flat (I’m looking at the building while writing this). I’m grateful for the accident because that made it possible for my father to meet my mother.  At that time he was an accountant, a job now generally replaced by Excel sheets.

Appendix B  - ETL De lta  load times

 The table in Appendix B shows statistics from real ETL runs. Here you can see that the example in this article took 5 minutes and 45 seconds to run and the performance was ~310 rows per second. The load velocity is depended on number of new lines (delta data) , concurrent network load  and the responsiveness of the source (SAP) system . The setup time [3]  is low, normally well below one second.  

   

To keep average response time acceptable we should probably schedule two back-ground ETL runs a day at 07.00 and noon for the (SAP COPA) data in this example. These ETL runs will have a negligible impact on the infrastructure landscape and keep user triggered loads to a maximum of a few thousand rows.  
Before you schedule the background jobs you should analyze data update pattern i.e. when updates occur and schedule on low activity hours like 07.00 and noon.

[1]  This particular ETL run took some 6 minutes. See Appendix B for details.
[2]  These figures are not measured, it is the authors biased opinion.
[3]  This includes send ‘run ETL signal’ and start up the ETL job in the BI layer. This also includes detection if there is anything to load, this is important you do not want to aggregate nonexistent data and reload already up to date BI cubes.