summaryrefslogtreecommitdiffstats
path: root/tags/native-sca-1.0.incubating-M3/runtime/extensions/python/src/tuscany/sca/python/sca_module.cpp
blob: bd34549f8abfbb0c8194e11cfa35380d0f890a8b (plain)
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/* $Rev$ $Date$ */

#include <string>
#include <iostream>
#include <sstream>

// undefine _DEBUG so Python does not need it's debug dll
#ifdef _DEBUG
#undef _DEBUG
#define _SCA_PYTHON_DEBUG
#endif
#include <Python.h>
#ifdef _SCA_PYTHON_DEBUG
#define _DEBUG
#endif

#include "commonj/sdo/SDO.h"

#include "PythonServiceProxy.h"
#include "tuscany/sca/util/Logging.h"
#include "tuscany/sca/core/Exceptions.h"
#include "tuscany/sca/core/SCARuntime.h"
#include "tuscany/sca/model/Component.h"
#include "tuscany/sca/model/Reference.h"
#include "tuscany/sca/model/ReferenceType.h"
#include "tuscany/sca/model/ServiceBinding.h"
#include "tuscany/sca/core/Operation.h"

using namespace std;
using namespace commonj::sdo;
using namespace tuscany::sca;
using namespace tuscany::sca::model;

static PyObject* scaError;

/**
* Prints out PyObject and dir(PyObject)
* for debugging purposes
*/
static void printPyObject(char* prefix, char* name, PyObject* pObj)
{
    PyObject* pObjRepr = PyObject_Repr(pObj);   
    PyTypeObject* type = pObj->ob_type;
    loginfo("%s printPyObject (%s) %s = %s", prefix, type->tp_name, name, PyString_AsString(pObjRepr));
    Py_XDECREF(pObjRepr);

    if(pObj != NULL)
    {
        PyObject* pObjDir = PyObject_Dir(pObj);    
        PyObject* pObjDirRepr = PyObject_Repr(pObjDir);
        loginfo("%s printPyObject dir(%s): %s", prefix, name, PyString_AsString(pObjDirRepr));
        Py_DECREF(pObjDirRepr);
        Py_DECREF(pObjDir);
    }
}

static PyObject* sca_locateservice(PyObject *self, PyObject *args)
{
    logentry();
    
    // Get the service name
    PyObject* pServiceName = PyTuple_GetItem(args, 0);

    // Import the SCA python-extension module
    PyObject* pModuleName = PyString_FromString("sca_proxy");
    PyObject* sca_proxy_module = PyImport_Import(pModuleName);
    Py_DECREF(pModuleName);

    if(!sca_proxy_module)
    {
        if(PyErr_Occurred())
        {
            PyErr_Print();
        }
        string msg = "Failed to load the sca_proxy Python module - has it been successfully installed?\nReferences from Python components will not be supported";
        logerror(msg.c_str());
    }
    else
    {
        // Get the sca_proxy class
        PyObject* sca_proxy_class = PyObject_GetAttrString(sca_proxy_module, "sca_proxy_class");

        PyObject* scaArgs = PyTuple_New(2);
        PyTuple_SetItem(scaArgs, 0, pServiceName);
        Py_INCREF(Py_True);
        PyTuple_SetItem(scaArgs, 1, Py_False);

        // Create the instance of the scaReference class
        PyObject* sca_proxy_classInstance = PyInstance_New(sca_proxy_class, scaArgs, NULL);
        Py_DECREF(scaArgs);

        return sca_proxy_classInstance;
    }

    Py_INCREF(Py_None);
    return Py_None;
}


static tuscany::sca::python::PythonServiceProxy* getServiceProxy(PyObject *args)
{
    logentry();

    tuscany::sca::python::PythonServiceProxy* serviceProxy = NULL;
    SCARuntime* runtime = SCARuntime::getCurrentRuntime();

    // The first argument holds the name
    string name;
    PyObject* pName = PyTuple_GetItem(args, 0);
    if(pName && PyString_Check(pName))
    {
        name = PyString_AsString(pName);
    }
    if(name.size() > 0)
    {
        loginfo("Service/Reference name is %s", name.c_str());
    }
    else
    {
        string msg = "Service/Reference name has not been set";
        logwarning(msg.c_str());
        PyErr_SetString(scaError, msg.c_str());
        return NULL;
    }

    // The second argument is a boolean
    PyObject* isReference = PyTuple_GetItem(args, 1);

    // Get the serviceProxy from the reference or service name provided
    if(PyObject_IsTrue(isReference))
    {
        Component* component = runtime->getCurrentComponent();    
        Reference* ref = component->findReference(name);
        if(!ref)
        {
            string msg = "Could not find the reference: "+name;
            logwarning(msg.c_str());
            PyErr_SetString(scaError, msg.c_str());

            return NULL;
        }

        ReferenceBinding* refBinding = ref->getBinding();
        serviceProxy = (tuscany::sca::python::PythonServiceProxy*) refBinding->getServiceProxy();
    }
    else
    {
        Component* component = runtime->getDefaultComponent();    
        Composite* composite = (Composite*)component->getType();
        Service* service = composite->findComponentService(name);

        if(!service)
        {
            string msg = "Could not find service: "+name;
            logwarning(msg.c_str());
            PyErr_SetString(scaError, msg.c_str());
            return NULL;
        }

        serviceProxy = new tuscany::sca::python::PythonServiceProxy(service);
    }

    return serviceProxy;
}


static PyObject* sca_invoke(PyObject *self, PyObject *args)
{
    logentry();

    tuscany::sca::python::PythonServiceProxy* pythonServiceProxy = getServiceProxy(args);
    if(!pythonServiceProxy)
    {
        return NULL;
    } 

    // Get the component from the reference or service provided
    Component* component = NULL; 
    SCARuntime* runtime = SCARuntime::getCurrentRuntime();

    PyObject* isReference = PyTuple_GetItem(args, 1);   
    if(PyObject_IsTrue(isReference))
    {
        component = runtime->getCurrentComponent(); 
    }
    else
    {
        component = runtime->getDefaultComponent();
    }

    // Get the name of the operation to invoke
    string operationName;
    PyObject* opName = PyTuple_GetItem(args, 2);
    if(opName && PyString_Check(opName))
    {
        operationName = PyString_AsString(opName);
    }

    if(operationName.size() > 0)
    {
        loginfo("sca_invoke Operation name: %s", operationName.c_str());
    }
    else
    {
        string msg = "Operation name has not been set";
        logwarning(msg.c_str());
        PyErr_SetString(scaError, msg.c_str());
        return NULL;
    }

    // Create the Operation object
    Operation operation(operationName.c_str());

    // Load up the xml.etree.ElementTree module for dealing with SDO params and return values
    PyObject* elementTreeModuleName = PyString_FromString("xml.etree.ElementTree"); 
    PyObject* elementTreeModule = PyImport_Import(elementTreeModuleName);                        

    if(elementTreeModule == NULL)
    {
        // pre-Python2.5? - try to get an installed elementtree package
        elementTreeModuleName = PyString_FromString("elementtree.ElementTree"); 
        elementTreeModule = PyImport_Import(elementTreeModuleName); 
    }
    if(elementTreeModule == NULL)
    {
        // Still null - throw a warning but carry on - user may not need XML
        logwarning("Could not load Python ElementTree module - is it installed? SDO and XML will not be supported");
    }

    // Parameters are the fourth argument
    PyObject* paramTuple = PyTuple_GetItem(args, 3);
    unsigned int numberOfArgs = (unsigned int) PyTuple_Size(paramTuple);
    loginfo("sca_invoke %d arg parameters supplied", numberOfArgs);
    
    // Keyword parameters (AKA named arguments) are the fifth argument
    PyObject* keywordParamDict = PyTuple_GetItem(args, 4);
    loginfo("sca_invoke %d keyword parameters supplied", PyDict_Size(keywordParamDict));
    
    PyObject* paramKeys = PyDict_Keys(keywordParamDict);   

    // Go through all the supplied parameters (args and keyword args)
    for(unsigned int i=0; i < (numberOfArgs + PyList_Size(paramKeys)); i++)
    {
        string* paramName;
        PyObject* param;

        if(i < PyTuple_Size(paramTuple))
        {
            param = PyTuple_GetItem(paramTuple, i);
            paramName = new string();
        }
        else
        {
            PyObject* key = PyList_GetItem(paramKeys, i-numberOfArgs);
            param = PyDict_GetItem(keywordParamDict, key);
            paramName = new string(PyString_AsString(key));
        }

        if(PyInt_Check(param))
        {
            loginfo("Int param %d %s: %d", i, (*paramName).c_str(), PyInt_AsLong(param));
            long* intData = new long;
            *intData = PyInt_AsLong(param);
            operation.addParameter(*paramName, intData);
        }
        else if(PyBool_Check(param))
        {
            loginfo("Bool param %d %s: %d", i, (*paramName).c_str(), (param == Py_True));
            bool* boolData = new bool;
            *boolData = (param == Py_True);
            operation.addParameter(*paramName, boolData);
        }
        else if(PyLong_Check(param))
        {
            loginfo("Long param %d %s: %l", i, (*paramName).c_str(), PyLong_AsLong(param));
            long* longData = new long;
            *longData = PyLong_AsLong(param);
            operation.addParameter(*paramName, longData);
        }
        else if(PyFloat_Check(param))
        {
            loginfo("Float param %d %s: %f", i, (*paramName).c_str(), PyFloat_AsDouble(param));
            double* doubleData = new double;
            *doubleData = PyFloat_AsDouble(param);
            operation.addParameter(*paramName, doubleData);
        }
        else if(PyString_Check(param))
        {
            loginfo("String param %d %s: %s", i, (*paramName).c_str(), PyString_AsString(param));
            const char** stringData = new const char*; 
            *stringData = PyString_AsString(param);
            operation.addParameter(*paramName, stringData);
        }
        else
        {
            PyObject* pIsElement = Py_False;
            if(elementTreeModule != NULL)
            {
                // Get the xml.etree.ElementTree.iselement function
                PyObject* elementTreeIsElementFunc = PyObject_GetAttrString(elementTreeModule, "iselement");

                // Call the iselement() function with pValue to check it
                pIsElement = PyObject_CallFunction(elementTreeIsElementFunc, "O", param);
            }

            if(PyObject_IsTrue(pIsElement) == 1)
            {
                // pValue is an xml.etree.ElementTree.Element - convert to SDO
                PyObject* elementTreeToStringFunc = PyObject_GetAttrString(elementTreeModule, "tostring");
                PyObject* pElemString = PyObject_CallFunction(elementTreeToStringFunc, "O", param);
                char* data = PyString_AsString(pElemString);
                loginfo("SDO param %d %s: %s", i, (*paramName).c_str(), data);

                loginfo("Converting Python ElementTree to SDO DataObject: %s", data);

                Composite* composite = component->getComposite();                                   
                XMLHelper* xmlHelper = composite->getXMLHelper();
                XMLDocumentPtr xmlDoc = xmlHelper->load(data);

                DataObjectPtr* dataObjectData = new DataObjectPtr;
                if (xmlDoc != NULL)
                {
                    *dataObjectData = xmlDoc->getRootDataObject();
                }
                else
                {
                    *dataObjectData = NULL;
                }
                if (*dataObjectData != NULL)
                {
                    operation.addParameter(*paramName, dataObjectData);
                }
                else
                {
                    string msg = "xml.etree.ElementTree.Element could not be converted to a DataObject";
                    logerror(msg.c_str());
                    PyErr_SetString(scaError, msg.c_str());
                    return NULL;
                }
                Py_DECREF(elementTreeToStringFunc);
                Py_DECREF(pElemString);
            }
            else
            {

                PyObject* paramRepr = PyObject_Repr(param); 
                PyObject* paramType = PyObject_Type(param);             
                PyObject* paramTypeRepr = PyObject_Repr(paramType);    
                
                string msg = "sca_invoke Param ";
                msg += i;
                msg += "is of unknown type (";
                msg += PyString_AsString(paramTypeRepr);
                msg += ") and has repr: ";
                msg += PyString_AsString(paramRepr);
    
                logerror(msg.c_str());
                PyErr_SetString(scaError, msg.c_str());
                
                Py_DECREF(paramTypeRepr);
                Py_DECREF(paramType);
                Py_DECREF(paramRepr);

                return NULL;
            }
        }
    }
   
    PyObject* returnValue = NULL;

    try
    {
        // Invoke the wired service
        pythonServiceProxy->invokeService(operation);
    }
    catch(TuscanyRuntimeException& ex)
    {
        string msg = "Exception whilst invoking the ";
        msg += operationName.c_str();
        msg += " operation on an SCA service/reference: ";
        msg += ex.getEClassName();
        msg += ": ";
        msg += ex.getMessageText();
        logwarning(msg.c_str());
        PyErr_SetString(scaError, msg.c_str());
        return NULL;
    }
    catch(...)
    {
        string msg = "Exception whilst invoking the ";
        msg += operationName.c_str();
        msg += " operation on an SCA service/reference";

        logwarning(msg.c_str());
        PyErr_SetString(scaError, msg.c_str());
        return NULL;
    }


    switch(operation.getReturnType())
    {
        case Operation::BOOL: 
            {
                if(*(bool*)operation.getReturnValue())
                {
                    returnValue = Py_True;
                }
                else
                {
                    returnValue = Py_False;
                }
                break;
            }
        case Operation::SHORT: 
            {
                returnValue = PyInt_FromLong(*(short*)operation.getReturnValue());
                break;
            }
        case Operation::LONG: 
            {
                returnValue = PyLong_FromLong(*(long*)operation.getReturnValue());
                break;
            }
        case Operation::USHORT: 
            {
                returnValue = PyInt_FromLong(*(unsigned short*)operation.getReturnValue());
                break;
            }
        case Operation::ULONG: 
            {
                returnValue = PyLong_FromLong(*(unsigned long*)operation.getReturnValue());
                break;
            }
        case Operation::FLOAT: 
            {
                returnValue = PyFloat_FromDouble(*(float*)operation.getReturnValue());
                break;
            }
        case Operation::DOUBLE: 
            {
                returnValue = PyFloat_FromDouble(*(double*)operation.getReturnValue());
                break;
            }
        case Operation::LONGDOUBLE: 
            {
                returnValue = PyFloat_FromDouble(*(long double*)operation.getReturnValue());
                break;
            }
        case Operation::CHARS: 
            {
                returnValue = PyString_FromString(*(char**)operation.getReturnValue());
                break;
            }
        case Operation::STRING: 
            {
                returnValue = PyString_FromString((*(string*)operation.getReturnValue()).c_str());
                break;
            }
        case Operation::DATAOBJECT: 
            {
                if(elementTreeModule != NULL)
                {
                    DataObjectPtr dob = *(DataObjectPtr*)operation.getReturnValue();

                    // Convert a DataObject to a xml.etree.ElementTree Element object
                    Composite* composite = component->getComposite();                                    
                    XMLHelper* xmlHelper = composite->getXMLHelper();
                    char* str = xmlHelper->save(
                        dob,
                        dob->getType().getURI(),
                        dob->getType().getName());                                    

                    loginfo("Converting SDO DataObject to Python ElementTree: %s", str);

                    // Get the xml.etree.ElementTree.XML function
                    PyObject* elementTreeXMLFunc = PyObject_GetAttrString(elementTreeModule, "XML");

                    // Call the XML() function with the XML string 
                    returnValue = PyObject_CallFunction(elementTreeXMLFunc, "s", str);

                    Py_DECREF(elementTreeXMLFunc);
                }
                else
                {
                    logwarning("Could not convert SDO DataObject to Python ElementTree as ElementTree module could not be loaded. Returning NONE");
                    Py_INCREF(Py_None);
                    returnValue = Py_None;
                }
                break;
            }
        default:
            {
                Py_INCREF(Py_None);
                returnValue = Py_None;
            }

    }

    Py_XDECREF(elementTreeModuleName); 
    Py_XDECREF(elementTreeModule);                        

    return returnValue;
}
static PyMethodDef ModuleMethods[] = 
{
    {"locateservice", (PyCFunction) sca_locateservice, METH_VARARGS, "Locates an SCA service & returns an sca_proxy_class instance"},
    {"invoke", (PyCFunction) sca_invoke, METH_VARARGS, "Invoke an operation on an SCA service or reference"},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

PyMODINIT_FUNC initsca(void)
{
    logentry();

    // Create a new module 
    PyObject* module = Py_InitModule("sca", ModuleMethods);
    
    scaError = PyErr_NewException("sca.error", NULL, NULL);
    Py_INCREF(scaError);
    PyModule_AddObject(module, "error", scaError);
}