source: branches/branch-1.4/zoo-project/zoo-kernel/service_internal_python.c @ 822

Last change on this file since 822 was 539, checked in by djay, 10 years ago

Fix yaml service naming. Add javax javaxx optional sections in the main.cfg #105.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 15.3 KB
Line 
1/**
2 * Author : Gérald FENOY
3 *
4 * Copyright (c) 2009-2014 GeoLabs SARL
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25#include "service_internal_python.h"
26
27struct module_state {
28    PyObject *error;
29};
30
31#if PY_MAJOR_VERSION >= 3
32#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
33#define PyInt_FromLong PyLong_FromLong
34#define PyInt_AsLong PyLong_AsLong
35#define PyString_FromString PyUnicode_FromString
36#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
37#define PyString_Check PyUnicode_Check
38#define PyString_AsString _PyUnicode_AsString
39#define PyString_Size PyUnicode_GetSize
40#else
41#define GETSTATE(m) (&_state)
42static struct module_state _state;
43#endif
44
45static PyObject* ZooError;
46
47PyMethodDef zooMethods[] = {
48  {"_", PythonTranslate, METH_VARARGS, "Translate a string using the zoo-services textdomain."},
49  {"update_status", PythonUpdateStatus, METH_VARARGS, "Update status percentage of a running process."},
50  {NULL, NULL, 0, NULL} /* tempt not the blade, all fear the sentinel */
51};
52
53#if PY_MAJOR_VERSION >= 3
54
55static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
56  Py_VISIT(GETSTATE(m)->error);
57  return 0;
58}
59
60static int myextension_clear(PyObject *m) {
61  Py_CLEAR(GETSTATE(m)->error);
62  return 0;
63}
64
65static struct PyModuleDef moduledef = {
66  PyModuleDef_HEAD_INIT,
67  "zoo",
68  NULL,
69  sizeof(struct module_state),
70  zooMethods,
71  NULL,
72  myextension_traverse,
73  myextension_clear,
74  NULL
75};
76#endif
77
78PyMODINIT_FUNC init_zoo(){
79  PyObject *tmp,*d;
80  PyObject *module = 
81#if PY_MAJOR_VERSION >= 3
82    PyModule_Create(&moduledef);
83#else
84    Py_InitModule("zoo", zooMethods);
85#endif
86  if (module == NULL){
87#if PY_MAJOR_VERSION >= 3
88    return NULL;
89#else
90    return;
91#endif
92  }
93
94  struct module_state *st = GETSTATE(module);
95
96  d = PyModule_GetDict(module);
97  tmp = PyInt_FromLong(3);
98  PyDict_SetItemString(d, "SERVICE_SUCCEEDED", tmp);
99  Py_DECREF(tmp);
100
101  tmp = PyInt_FromLong(4);
102  PyDict_SetItemString(d, "SERVICE_FAILED", tmp);
103  Py_DECREF(tmp);
104
105  tmp = PyString_FromString(ZOO_VERSION);
106  PyDict_SetItemString(d, "VERSION", tmp);
107  Py_DECREF(tmp);
108
109  ZooError = PyErr_NewException((char*)"zoo.error", NULL, NULL);
110  Py_INCREF(ZooError);
111  PyModule_AddObject(module, "error", ZooError);
112#if PY_MAJOR_VERSION >= 3
113  return module;
114#endif
115}
116
117int zoo_python_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
118  char *pythonpath;
119  char *python_path;
120  maps* m=*main_conf;
121  maps* inputs=*real_inputs;
122  maps* outputs=*real_outputs;
123  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
124  char *ntmp=tmp0->value;
125  map* tmp=NULL;
126  int hasToClean=0;
127  tmp=getMapFromMaps(*main_conf,"env","PYTHONPATH");
128#ifdef DEBUG
129  fprintf(stderr,"PYTHON SUPPORT \n");
130#endif
131  if(tmp!=NULL){
132#ifdef DEBUG
133    fprintf(stderr,"PYTHON SUPPORT (%i)\n",strlen(tmp->value));
134#endif
135    python_path=(char*)malloc((strlen(tmp->value))*sizeof(char));
136    sprintf(python_path,"%s",tmp->value);
137    hasToClean=1;
138  }
139  else{
140    python_path=(char*)".";
141  }
142  tmp=NULL;
143  tmp=getMap(request,"metapath");
144  if(tmp!=NULL && strcmp(tmp->value,"")!=0){
145    pythonpath=(char*)malloc((4+strlen(python_path)+strlen(ntmp)+strlen(tmp->value))*sizeof(char));
146#ifdef WIN32
147  sprintf(pythonpath,"%s/%s/;%s",ntmp,tmp->value,python_path);
148#else
149  sprintf(pythonpath,"%s/%s/:%s",ntmp,tmp->value,python_path);
150#endif
151  }
152  else{
153    pythonpath=(char*)malloc((2+strlen(python_path)+strlen(ntmp))*sizeof(char));
154#ifdef WIN32
155    sprintf(pythonpath,"%s;%s",ntmp,python_path);
156#else
157    sprintf(pythonpath,"%s:%s",ntmp,python_path);
158#endif
159  }
160#ifdef DEBUG
161    fprintf(stderr,"PYTHONPATH=%s\n",pythonpath);
162#endif
163#ifndef WIN32
164  setenv("PYTHONPATH",pythonpath,1);
165#else
166  SetEnvironmentVariable("PYTHONPATH",pythonpath);
167  char* toto=(char*)malloc((strlen(pythonpath)+12)*sizeof(char));
168  sprintf(toto,"PYTHONPATH=%s",pythonpath);
169  putenv(toto);
170  free(toto);
171#endif
172  if(hasToClean>0)
173    free(python_path);
174  free(pythonpath);
175
176  PyThreadState *mainstate;
177#if PY_MAJOR_VERSION >= 3
178  PyImport_AppendInittab("zoo", init_zoo);
179#else
180  PyEval_InitThreads();
181#endif
182  Py_Initialize();
183#if PY_MAJOR_VERSION >= 3
184  PyEval_InitThreads();
185  PyImport_ImportModule("zoo");
186#else
187  init_zoo();
188#endif
189  mainstate = PyThreadState_Swap(NULL);
190  PyEval_ReleaseLock();
191  PyGILState_STATE gstate;
192  gstate = PyGILState_Ensure();
193  PyObject *pName, *pModule, *pFunc;
194  tmp=getMap(s->content,"serviceProvider");
195  map* mp=getMap(request,"metapath");
196  if(tmp!=NULL){
197    if(mp!=NULL && strlen(mp->value)>0){
198      char *mps=zStrdup(mp->value);
199      int i,len=strlen(mps);
200      int j=0;
201      for(i=0;i<len;i++){
202        if(mps[i]=='/'){
203          mps[i]='.';
204        }
205      }
206      char *mn=(char*)malloc((strlen(mps)+strlen(tmp->value)+2)*sizeof(char));
207      sprintf(mn,"%s.%s",mps,tmp->value);
208      pName = PyString_FromString(mn);
209      free(mn);
210      free(mps);
211    }
212    else{
213      pName = PyString_FromString(tmp->value);
214    }
215  }
216  else{
217    map* err=createMap("text","Unable to parse serviceProvider please check your zcfg file.");
218    addToMap(err,"code","NoApplicableCode");
219    printExceptionReportResponse(m,err);
220    exit(-1);
221  }
222  pModule = PyImport_Import(pName);
223  int res=SERVICE_FAILED;
224  if (pModule != NULL) {
225    pFunc=PyObject_GetAttrString(pModule,s->name);
226    if (pFunc && PyCallable_Check(pFunc)){
227      PyObject *pValue;
228      PyDictObject* arg1=PyDict_FromMaps(m);
229      PyDictObject* arg2=PyDict_FromMaps(inputs);
230      PyDictObject* arg3=PyDict_FromMaps(outputs);
231      PyObject *pArgs=PyTuple_New(3);
232      if (!pArgs)
233        return -1;
234      PyTuple_SetItem(pArgs, 0, (PyObject *)arg1);
235      PyTuple_SetItem(pArgs, 1, (PyObject *)arg2);
236      PyTuple_SetItem(pArgs, 2, (PyObject *)arg3);
237      pValue = PyObject_CallObject(pFunc, pArgs);
238      if (pValue != NULL) {
239        res=PyInt_AsLong(pValue);
240        freeMaps(real_outputs);
241        free(*real_outputs);
242        freeMaps(main_conf);
243        free(*main_conf);
244        *main_conf=mapsFromPyDict(arg1);
245        *real_outputs=mapsFromPyDict(arg3);
246#ifdef DEBUG
247        fprintf(stderr,"Result of call: %i\n", PyInt_AsLong(pValue));
248        dumpMaps(inputs);
249        dumpMaps(*real_outputs);
250#endif
251      }else{     
252        PyObject *ptype,*pvalue, *ptraceback;
253        PyErr_Fetch(&ptype, &pvalue, &ptraceback);
254        PyObject *trace=PyObject_Str(pvalue);
255        char pbt[10240];
256        if(PyString_Check(trace))
257          sprintf(pbt,"TRACE : %s",PyString_AsString(trace));
258        else
259          fprintf(stderr,"EMPTY TRACE ?");
260        trace=NULL;
261        trace=PyObject_Str(ptype);
262        if(PyString_Check(trace)){
263          char *tpbt=zStrdup(pbt);
264          sprintf(pbt,"%s\n%s",tpbt,PyString_AsString(trace));
265          free(tpbt);
266        }
267        else
268          fprintf(stderr,"EMPTY TRACE ?");
269       
270        char *tpbt=zStrdup(pbt);
271        pName = PyString_FromString("traceback");
272        pModule = PyImport_Import(pName);
273        pArgs = PyTuple_New(1);
274        PyTuple_SetItem(pArgs, 0, ptraceback);
275        pFunc = PyObject_GetAttrString(pModule,"format_tb");
276        pValue = PyObject_CallObject(pFunc, pArgs);
277        trace=NULL;
278        trace=PyObject_Str(pValue);
279        if(PyString_Check(trace))
280          sprintf(pbt,"%s\nUnable to run your python process properly. Please check the following messages : %s",tpbt,PyString_AsString(trace));
281        else
282          sprintf(pbt,"%s \n Unable to run your python process properly. Unable to provide any futher informations.",tpbt);
283        free(tpbt);
284        map* err=createMap("text",pbt);
285        addToMap(err,"code","NoApplicableCode");
286        printExceptionReportResponse(m,err);
287        res=-1;
288      }
289    }
290    else{
291      char tmpS[1024];
292      sprintf(tmpS, "Cannot find the %s function in the %s file.\n", s->name, tmp->value);
293      map* tmps=createMap("text",tmpS);
294      printExceptionReportResponse(m,tmps);
295      res=-1;
296    }
297  } else{
298    char tmpS[1024];
299    sprintf(tmpS, "Python module %s cannot be loaded.\n", tmp->value);
300    map* tmps=createMap("text",tmpS);
301    printExceptionReportResponse(m,tmps);
302    if (PyErr_Occurred())
303      PyErr_Print();
304    PyErr_Clear();
305    res=-1;
306  } 
307#if PY_MAJOR_VERSION < 3
308  PyGILState_Release(gstate);
309  PyEval_AcquireLock();
310#endif
311  PyThreadState_Swap(mainstate);
312  Py_Finalize();
313  return res;
314}
315
316PyDictObject* PyDict_FromMaps(maps* t){
317  PyObject* res=PyDict_New( );
318  maps* tmp=t;
319  while(tmp!=NULL){
320    PyObject* value=(PyObject*)PyDict_FromMap(tmp->content);
321    PyObject* name=PyString_FromString(tmp->name);
322    if(PyDict_SetItem(res,name,value)<0){
323      fprintf(stderr,"Unable to set map value ...");
324      return NULL;
325    }
326    Py_DECREF(name);
327    tmp=tmp->next;
328  } 
329  return (PyDictObject*) res;
330}
331
332PyDictObject* PyDict_FromMap(map* t){
333  PyObject* res=PyDict_New( );
334  map* tmp=t;
335  int hasSize=0;
336  map* isArray=getMap(tmp,"isArray");
337  map* size=getMap(tmp,"size");
338  map* tmap=getMapType(tmp);
339  while(tmp!=NULL){
340    PyObject* name=PyString_FromString(tmp->name);
341    if(strcasecmp(tmp->name,"value")==0) {
342      if(isArray!=NULL){
343        map* len=getMap(tmp,"length");
344        int cnt=atoi(len->value);
345        PyObject* value=PyList_New(cnt);
346        PyObject* mvalue=PyList_New(cnt);
347        PyObject* svalue=PyList_New(cnt);
348
349        for(int i=0;i<cnt;i++){
350         
351          map* vMap=getMapArray(tmp,"value",i);     
352          map* sMap=getMapArray(tmp,"size",i);
353
354          if(vMap!=NULL){
355           
356            PyObject* lvalue;
357            PyObject* lsvalue;
358            if(sMap==NULL){
359              lvalue=PyString_FromString(vMap->value);
360              lsvalue=Py_None;
361            }
362            else{   
363              lvalue=PyString_FromStringAndSize(vMap->value,atoi(sMap->value));
364              lsvalue=PyString_FromString(sMap->value);
365              hasSize=1;
366            }
367
368            if(PyList_SetItem(value,i,lvalue)<0){
369              fprintf(stderr,"Unable to set key value pair...");
370              return NULL;
371            } 
372            if(PyList_SetItem(svalue,i,lsvalue)<0){
373              fprintf(stderr,"Unable to set key value pair...");
374              return NULL;
375            } 
376          }
377         
378          map* mMap=getMapArray(tmp,tmap->name,i);
379          PyObject* lmvalue;
380          if(mMap!=NULL){
381            lmvalue=PyString_FromString(mMap->value);
382          }else
383            lmvalue=Py_None;
384         
385          if(PyList_SetItem(mvalue,i,lmvalue)<0){
386              fprintf(stderr,"Unable to set key value pair...");
387              return NULL;
388          } 
389         
390        }
391
392        if(PyDict_SetItem(res,name,value)<0){
393          fprintf(stderr,"Unable to set key value pair...");
394          return NULL;
395        }
396        if(PyDict_SetItem(res,PyString_FromString(tmap->name),mvalue)<0){
397          fprintf(stderr,"Unable to set key value pair...");
398          return NULL;
399        }
400        if(hasSize>0)
401          if(PyDict_SetItem(res,PyString_FromString("size"),svalue)<0){
402            fprintf(stderr,"Unable to set key value pair...");
403            return NULL;
404          }
405      }
406      else if(size!=NULL){
407        PyObject* value=PyString_FromStringAndSize(tmp->value,atoi(size->value));
408        if(PyDict_SetItem(res,name,value)<0){
409          Py_DECREF(value);
410          fprintf(stderr,"Unable to set key value pair...");
411          return NULL;
412        }
413        Py_DECREF(value);
414      }
415      else{
416        PyObject* value=PyString_FromString(tmp->value);
417        if(PyDict_SetItem(res,name,value)<0){
418          Py_DECREF(value);
419          fprintf(stderr,"Unable to set key value pair...");
420          return NULL;
421        }
422        Py_DECREF(value);
423      }
424    }
425    else{
426      if(PyDict_GetItem(res,name)==NULL){
427        PyObject* value=PyString_FromString(tmp->value);
428        if(PyDict_SetItem(res,name,value)<0){
429          Py_DECREF(value);
430          fprintf(stderr,"Unable to set key value pair...");
431          return NULL;
432        }
433        Py_DECREF(value);
434      }
435    }
436    Py_DECREF(name);
437    tmp=tmp->next;
438  }
439  return (PyDictObject*) res;
440}
441
442maps* mapsFromPyDict(PyDictObject* t){
443  maps* res=NULL;
444  maps* cursor=res;
445  PyObject* list=PyDict_Keys((PyObject*)t);
446  int nb=PyList_Size(list);
447  int i;
448  for(i=0;i<nb;i++){
449#ifdef DEBUG
450    fprintf(stderr,">> parsing maps %d\n",i);
451#endif
452    PyObject* key=PyList_GetItem(list,i);
453    PyObject* value=PyDict_GetItem((PyObject*)t,key);
454#ifdef DEBUG
455    fprintf(stderr,">> DEBUG VALUES : %s => %s\n",
456            PyString_AsString(key),PyString_AsString(value));
457#endif
458    cursor=(maps*)malloc(MAPS_SIZE);
459    cursor->name=PyString_AsString(key);
460    cursor->content=mapFromPyDict((PyDictObject*)value);
461#ifdef DEBUG
462    dumpMap(cursor->content);
463#endif
464    cursor->next=NULL;
465    if(res==NULL)
466      res=dupMaps(&cursor);
467    else
468      addMapsToMaps(&res,cursor);
469    freeMap(&cursor->content);
470    free(cursor->content);
471    free(cursor);
472    Py_DECREF(key);
473#ifdef DEBUG
474    dumpMaps(res);
475    fprintf(stderr,">> parsed maps %d\n",i);
476#endif
477  }
478  Py_DECREF(list);
479  return res;
480}
481
482map* mapFromPyDict(PyDictObject* t){
483  map* res=NULL;
484  PyObject* list=PyDict_Keys((PyObject*)t);
485  int nb=PyList_Size(list);
486  int i;
487  for(i=0;i<nb;i++){
488    PyObject* key=PyList_GetItem(list,i);
489    PyObject* value=PyDict_GetItem((PyObject*)t,key);
490#ifdef DEBUG
491    fprintf(stderr,">> DEBUG VALUES : %s => %s\n",
492            PyString_AsString(key),PyString_AsString(value));
493#endif
494   
495    if(strcmp(PyString_AsString(key),"value")==0){
496      char *buffer=NULL;
497      Py_ssize_t size;
498#if PY_MAJOR_VERSION >= 3
499      buffer=_PyUnicode_AsStringAndSize(value,&size);
500#else
501      PyString_AsStringAndSize(value,&buffer,&size);
502#endif
503      addToMapWithSize(res,"value",buffer,size);
504    }else{
505      char* lkey=PyString_AsString(key);
506      char* lvalue=PyString_AsString(value);
507      if(res!=NULL){
508        if(PyString_Size(value)>0)
509          addToMap(res,lkey,lvalue);
510      }
511      else{
512        if(PyString_Size(value)>0)
513          res=createMap(lkey,lvalue);
514      }
515    }
516  }
517  Py_DECREF(list);
518  return res;
519}
520
521PyObject*
522PythonTranslate(PyObject* self, PyObject* args)
523{
524  char *str;
525  if (!PyArg_ParseTuple(args, "s", &str)){
526#ifdef DEBUG
527    fprintf(stderr,"Incorrect arguments to update status function");
528#endif
529    return NULL;
530  }
531  return PyString_FromString(_ss(str));
532}
533
534PyObject*
535PythonUpdateStatus(PyObject* self, PyObject* args)
536{
537  maps* conf;
538  PyObject* confdict;
539  int istatus;
540  char* status;
541  if (!PyArg_ParseTuple(args, "O!i", &PyDict_Type, &confdict, &istatus)){
542#ifdef DEBUG
543    fprintf(stderr,"Incorrect arguments to update status function");
544#endif
545    return NULL;
546  }
547  if (istatus < 0 || istatus > 100){
548     PyErr_SetString(ZooError, "Status must be a percentage.");
549     return NULL;
550  }else{
551     char tmpStatus[4];
552     snprintf(tmpStatus, 4, "%i", istatus);
553     status = zStrdup(tmpStatus);
554  }
555  /* now update the map */
556  {
557    PyObject* lenv = PyMapping_GetItemString(confdict, (char *)"lenv");
558    if (lenv && PyMapping_Check(lenv)){
559      PyObject* valobj = PyString_FromString(status);
560      PyMapping_SetItemString(lenv, (char *)"status", valobj);
561      Py_DECREF(valobj);
562    }
563    Py_DECREF(lenv);
564  }
565  conf = mapsFromPyDict((PyDictObject*)confdict);
566  if (getMapFromMaps(conf,"lenv","status") != NULL){
567    if(status!=NULL){
568      setMapInMaps(conf,"lenv","status",status);
569      free(status);
570    }
571    else
572      setMapInMaps(conf,"lenv","status","15");
573    _updateStatus(conf);
574  }
575  freeMaps(&conf);
576  free(conf);
577  Py_RETURN_NONE;
578}
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png