source: trunk/zoo-project/zoo-kernel/service_internal_python.c @ 835

Last change on this file since 835 was 790, checked in by djay, 8 years ago

Add support for nested inputs and outputs.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 21.9 KB
RevLine 
[579]1/*
[1]2 * Author : Gérald FENOY
3 *
[453]4 * Copyright (c) 2009-2014 GeoLabs SARL
[1]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
[579]27/**
28 * The state for the zoo Python module
29 */
[392]30struct module_state {
[579]31   PyObject *error;
[392]32};
33
34#if PY_MAJOR_VERSION >= 3
35#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
[453]36#define PyInt_FromLong PyLong_FromLong
37#define PyInt_AsLong PyLong_AsLong
38#define PyString_FromString PyUnicode_FromString
39#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
40#define PyString_Check PyUnicode_Check
41#define PyString_AsString _PyUnicode_AsString
42#define PyString_Size PyUnicode_GetSize
[392]43#else
44#define GETSTATE(m) (&_state)
45static struct module_state _state;
46#endif
47
[579]48/**
49 * The exception for the zoo Python module
50 */
[368]51static PyObject* ZooError;
52
[579]53/**
54 * Function definitions for the zoo Python Module
55 *
56 * Define the following functions available from a service loaded and running
57 * from the ZOO-Kernel Python environment:
58 *  - "_" corresponding to the PythonTranslate function
59 *  - "updte_status" corresponding to the PythonUpdateStatus function
60 * @see PythonTranslate, PythonUpdateStatus
61 */
[368]62PyMethodDef zooMethods[] = {
[376]63  {"_", PythonTranslate, METH_VARARGS, "Translate a string using the zoo-services textdomain."},
[368]64  {"update_status", PythonUpdateStatus, METH_VARARGS, "Update status percentage of a running process."},
65  {NULL, NULL, 0, NULL} /* tempt not the blade, all fear the sentinel */
66};
67
[392]68#if PY_MAJOR_VERSION >= 3
69
70static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
71  Py_VISIT(GETSTATE(m)->error);
72  return 0;
73}
74
75static int myextension_clear(PyObject *m) {
76  Py_CLEAR(GETSTATE(m)->error);
77  return 0;
78}
79
80static struct PyModuleDef moduledef = {
81  PyModuleDef_HEAD_INIT,
82  "zoo",
83  NULL,
84  sizeof(struct module_state),
85  zooMethods,
86  NULL,
87  myextension_traverse,
88  myextension_clear,
89  NULL
90};
91#endif
92
[579]93/**
94 * Function to create and initialize the zoo Python module
95 *
96 * @return the Python module (for Python versions < 3, nothing for version >=3)
97 */
[368]98PyMODINIT_FUNC init_zoo(){
99  PyObject *tmp,*d;
[392]100  PyObject *module = 
101#if PY_MAJOR_VERSION >= 3
102    PyModule_Create(&moduledef);
103#else
104    Py_InitModule("zoo", zooMethods);
105#endif
106  if (module == NULL){
107#if PY_MAJOR_VERSION >= 3
108    return NULL;
109#else
[368]110    return;
[392]111#endif
112  }
113
114  struct module_state *st = GETSTATE(module);
115
[368]116  d = PyModule_GetDict(module);
117  tmp = PyInt_FromLong(3);
118  PyDict_SetItemString(d, "SERVICE_SUCCEEDED", tmp);
119  Py_DECREF(tmp);
120
121  tmp = PyInt_FromLong(4);
122  PyDict_SetItemString(d, "SERVICE_FAILED", tmp);
123  Py_DECREF(tmp);
124
[465]125  tmp = PyString_FromString(ZOO_VERSION);
126  PyDict_SetItemString(d, "VERSION", tmp);
127  Py_DECREF(tmp);
128
[490]129  ZooError = PyErr_NewException((char*)"zoo.error", NULL, NULL);
[368]130  Py_INCREF(ZooError);
131  PyModule_AddObject(module, "error", ZooError);
[392]132#if PY_MAJOR_VERSION >= 3
133  return module;
134#endif
[368]135}
136
[579]137/**
[580]138 * Load a Python module then run the function corresponding to the service
[579]139 * by passing the conf, inputs and outputs parameters by reference.
140 *
141 * @param main_conf the conf maps containing the main.cfg settings
142 * @param request the map containing the HTTP request
143 * @param s the service structure
144 * @param real_inputs the maps containing the inputs
145 * @param real_outputs the maps containing the outputs
146 */
[1]147int zoo_python_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
[451]148  char *pythonpath;
149  char *python_path;
[1]150  maps* m=*main_conf;
151  maps* inputs=*real_inputs;
152  maps* outputs=*real_outputs;
[392]153  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
154  char *ntmp=tmp0->value;
[1]155  map* tmp=NULL;
[451]156  int hasToClean=0;
[1]157  tmp=getMapFromMaps(*main_conf,"env","PYTHONPATH");
[63]158#ifdef DEBUG
[9]159  fprintf(stderr,"PYTHON SUPPORT \n");
[63]160#endif
[1]161  if(tmp!=NULL){
[63]162#ifdef DEBUG
[9]163    fprintf(stderr,"PYTHON SUPPORT (%i)\n",strlen(tmp->value));
[63]164#endif
[9]165    python_path=(char*)malloc((strlen(tmp->value))*sizeof(char));
166    sprintf(python_path,"%s",tmp->value);
[451]167    hasToClean=1;
[1]168  }
169  else{
[784]170    map* cwdMap=getMapFromMaps(*main_conf,"main","servicePath");
171    if(cwdMap!=NULL)
172      python_path=cwdMap->value;
173    else
174      python_path=(char*)".";
[1]175  }
176  tmp=NULL;
177  tmp=getMap(request,"metapath");
[392]178  if(tmp!=NULL && strcmp(tmp->value,"")!=0){
179    pythonpath=(char*)malloc((4+strlen(python_path)+strlen(ntmp)+strlen(tmp->value))*sizeof(char));
[1]180#ifdef WIN32
[451]181  sprintf(pythonpath,"%s/%s/;%s",ntmp,tmp->value,python_path);
[1]182#else
[451]183  sprintf(pythonpath,"%s/%s/:%s",ntmp,tmp->value,python_path);
[1]184#endif
[392]185  }
186  else{
187    pythonpath=(char*)malloc((2+strlen(python_path)+strlen(ntmp))*sizeof(char));
[1]188#ifdef WIN32
189    sprintf(pythonpath,"%s;%s",ntmp,python_path);
190#else
[392]191    sprintf(pythonpath,"%s:%s",ntmp,python_path);
[1]192#endif
[392]193  }
[67]194#ifdef DEBUG
[9]195    fprintf(stderr,"PYTHONPATH=%s\n",pythonpath);
[67]196#endif
[1]197#ifndef WIN32
198  setenv("PYTHONPATH",pythonpath,1);
199#else
200  SetEnvironmentVariable("PYTHONPATH",pythonpath);
[364]201  char* toto=(char*)malloc((strlen(pythonpath)+12)*sizeof(char));
202  sprintf(toto,"PYTHONPATH=%s",pythonpath);
203  putenv(toto);
[451]204  free(toto);
[1]205#endif
[451]206  if(hasToClean>0)
207    free(python_path);
[1]208  free(pythonpath);
[9]209
[295]210  PyThreadState *mainstate;
[392]211#if PY_MAJOR_VERSION >= 3
212  PyImport_AppendInittab("zoo", init_zoo);
213#else
[295]214  PyEval_InitThreads();
[392]215#endif
[1]216  Py_Initialize();
[392]217#if PY_MAJOR_VERSION >= 3
218  PyEval_InitThreads();
219  PyImport_ImportModule("zoo");
220#else
[368]221  init_zoo();
[392]222#endif
[295]223  mainstate = PyThreadState_Swap(NULL);
224  PyEval_ReleaseLock();
225  PyGILState_STATE gstate;
226  gstate = PyGILState_Ensure();
[1]227  PyObject *pName, *pModule, *pFunc;
228  tmp=getMap(s->content,"serviceProvider");
[505]229  map* mp=getMap(request,"metapath");
230  if(tmp!=NULL){
231    if(mp!=NULL && strlen(mp->value)>0){
232      char *mps=zStrdup(mp->value);
233      int i,len=strlen(mps);
234      int j=0;
235      for(i=0;i<len;i++){
236        if(mps[i]=='/'){
237          mps[i]='.';
238        }
239      }
240      char *mn=(char*)malloc((strlen(mps)+strlen(tmp->value)+2)*sizeof(char));
241      sprintf(mn,"%s.%s",mps,tmp->value);
242      pName = PyString_FromString(mn);
243      free(mn);
244      free(mps);
245    }
246    else{
247      pName = PyString_FromString(tmp->value);
248    }
249  }
[9]250  else{
[576]251    errorException (m, "Unable to parse serviceProvider please check your zcfg file.", "NoApplicableCode", NULL);
[9]252    exit(-1);
253  }
[1]254  pModule = PyImport_Import(pName);
255  int res=SERVICE_FAILED;
256  if (pModule != NULL) {
257    pFunc=PyObject_GetAttrString(pModule,s->name);
258    if (pFunc && PyCallable_Check(pFunc)){
[114]259      PyObject *pValue;
[1]260      PyDictObject* arg1=PyDict_FromMaps(m);
261      PyDictObject* arg2=PyDict_FromMaps(inputs);
262      PyDictObject* arg3=PyDict_FromMaps(outputs);
263      PyObject *pArgs=PyTuple_New(3);
[114]264      if (!pArgs)
265        return -1;
[1]266      PyTuple_SetItem(pArgs, 0, (PyObject *)arg1);
267      PyTuple_SetItem(pArgs, 1, (PyObject *)arg2);
268      PyTuple_SetItem(pArgs, 2, (PyObject *)arg3);
269      pValue = PyObject_CallObject(pFunc, pArgs);
270      if (pValue != NULL) {
271        res=PyInt_AsLong(pValue);
[9]272        freeMaps(real_outputs);
273        free(*real_outputs);
[59]274        freeMaps(main_conf);
275        free(*main_conf);
[57]276        *main_conf=mapsFromPyDict(arg1);
[9]277        *real_outputs=mapsFromPyDict(arg3);
[1]278#ifdef DEBUG
279        fprintf(stderr,"Result of call: %i\n", PyInt_AsLong(pValue));
280        dumpMaps(inputs);
[364]281        dumpMaps(*real_outputs);
[1]282#endif
[9]283      }else{     
[576]284        PythonZooReport(m,tmp->value,0);
[295]285        res=-1;
[1]286      }
287    }
288    else{
289      char tmpS[1024];
[295]290      sprintf(tmpS, "Cannot find the %s function in the %s file.\n", s->name, tmp->value);
[576]291      errorException(m,tmpS,"NoApplicableCode",NULL);
[295]292      res=-1;
[1]293    }
294  } else{
[576]295    PythonZooReport(m,tmp->value,1);
[295]296    res=-1;
[1]297  } 
[392]298#if PY_MAJOR_VERSION < 3
[295]299  PyGILState_Release(gstate);
[478]300  PyEval_AcquireLock();
[392]301#endif
[295]302  PyThreadState_Swap(mainstate);
[1]303  Py_Finalize();
304  return res;
305}
306
[579]307/**
[580]308 * Report Python error which may occur on loading the Python module or at
[579]309 * runtime.
310 *
311 * @param m the conf maps containing the main.cfg settings
312 * @param module the service name
313 * @param load 1 if the Python module was not loaded yet
314 */
[576]315void PythonZooReport(maps* m,const char* module,int load){
316  PyObject *pName, *pModule, *pFunc;
317  PyObject *ptype, *pvalue, *ptraceback,*pValue,*pArgs;
318  PyErr_Fetch(&ptype, &pvalue, &ptraceback);
319  char *pStrErrorMessage = PyString_AsString(pvalue);
320  char *tmp0=_("Python module %s cannot be loaded. Message: %s\n");
321 
322  PyObject *trace=PyObject_Str(pvalue);
323  char *pbt=NULL;
324  if(PyString_Check(trace)){
325    pbt=(char*)malloc((7+strlen(PyString_AsString(trace))+1)*sizeof(char));
326    sprintf(pbt,"TRACE: %s",PyString_AsString(trace));
327  }
328  else
329    fprintf(stderr,"EMPTY TRACE ?");
330 
331  trace=NULL;
332 
333  trace=PyObject_Str(ptype);
334  if(PyString_Check(trace)){
335    char *tpbt=zStrdup(pbt);
336    if(pbt!=NULL)
337      free(pbt);
338    pbt=(char*)malloc((1+strlen(tpbt)+strlen(PyString_AsString(trace))+1)*sizeof(char));
339    sprintf(pbt,"%s\n%s",tpbt,PyString_AsString(trace));
340    free(tpbt);
341  }
342  else
343    fprintf(stderr,"EMPTY TRACE ?");
344 
345  if(ptraceback!=NULL){
346    char *tpbt=zStrdup(pbt);
347    pName = PyString_FromString("traceback");
348    pModule = PyImport_Import(pName);
349    pArgs = PyTuple_New(1);
350    PyTuple_SetItem(pArgs, 0, ptraceback);
351    pFunc = PyObject_GetAttrString(pModule,"format_tb");
352    pValue = PyObject_CallObject(pFunc, pArgs);
353    trace=NULL;
354    trace=PyObject_Str(pValue);
355    if(PyString_Check(trace)){
356      if(pbt!=NULL)
357        free(pbt);
[790]358      char* format=_("%s\nUnable to run your python process properly. Please check the following messages : %s");
359      pbt=(char*)malloc((strlen(format)+strlen(tpbt)+strlen(PyString_AsString(trace))+1)*sizeof(char));
360      sprintf(pbt,format,tpbt,PyString_AsString(trace));
[576]361    }
362    else{
363      if(pbt!=NULL)
364        free(pbt);
[790]365      char* format=_("%s \n Unable to run your python process properly. Unable to provide any further information.");
366      pbt=(char*)malloc((strlen(format)+strlen(tpbt)+strlen(PyString_AsString(trace))+1)*sizeof(char));
367      sprintf(pbt,format,tpbt);
[576]368    }
369    free(tpbt);
370  }
371  if(load>0){
372    char *tmpS=(char*)malloc((strlen(tmp0)+strlen(module)+strlen(pbt)+1)*sizeof(char));
373    sprintf(tmpS,tmp0,module,pbt);
374    errorException(m,tmpS,"NoApplicableCode",NULL);
375    free(tmpS);
376  }else
377    errorException(m,pbt,"NoApplicableCode",NULL);
378  free(pbt);
379}
380
[579]381/**
382 * Convert a maps to a Python dictionary
383 *
384 * @param t the maps to convert
385 * @return a new PyDictObject containing the converted maps
386 * @see PyDict_FromMap
[781]387 * @warning make sure to free resources returned by this function
[579]388 */
[1]389PyDictObject* PyDict_FromMaps(maps* t){
390  PyObject* res=PyDict_New( );
391  maps* tmp=t;
392  while(tmp!=NULL){
[295]393    PyObject* value=(PyObject*)PyDict_FromMap(tmp->content);
[790]394    if(tmp->child!=NULL){
395      PyObject* cname=PyString_FromString("child");
396      PyObject* childs=(PyObject*)PyDict_FromMaps(tmp->child);
397      if(PyDict_SetItem(value,cname,childs)<0){
398        fprintf(stderr,"Unable to set map value ...");
399        return NULL;
400      } 
401      Py_DECREF(cname);
402    }
[453]403    PyObject* name=PyString_FromString(tmp->name);
[295]404    if(PyDict_SetItem(res,name,value)<0){
405      fprintf(stderr,"Unable to set map value ...");
406      return NULL;
[1]407    }
[295]408    Py_DECREF(name);
[1]409    tmp=tmp->next;
410  } 
411  return (PyDictObject*) res;
412}
413
[579]414/**
415 * Convert a map to a Python dictionary
416 *
417 * @param t the map to convert
418 * @return a new PyDictObject containing the converted maps
[781]419 * @warning make sure to free resources returned by this function
[579]420 */
[1]421PyDictObject* PyDict_FromMap(map* t){
422  PyObject* res=PyDict_New( );
423  map* tmp=t;
[360]424  int hasSize=0;
425  map* isArray=getMap(tmp,"isArray");
[58]426  map* size=getMap(tmp,"size");
[360]427  map* tmap=getMapType(tmp);
[1]428  while(tmp!=NULL){
[453]429    PyObject* name=PyString_FromString(tmp->name);
[360]430    if(strcasecmp(tmp->name,"value")==0) {
431      if(isArray!=NULL){
432        map* len=getMap(tmp,"length");
433        int cnt=atoi(len->value);
434        PyObject* value=PyList_New(cnt);
435        PyObject* mvalue=PyList_New(cnt);
436        PyObject* svalue=PyList_New(cnt);
437
438        for(int i=0;i<cnt;i++){
439         
440          map* vMap=getMapArray(tmp,"value",i);     
441          map* sMap=getMapArray(tmp,"size",i);
442
443          if(vMap!=NULL){
444           
445            PyObject* lvalue;
446            PyObject* lsvalue;
447            if(sMap==NULL){
448              lvalue=PyString_FromString(vMap->value);
449              lsvalue=Py_None;
450            }
[453]451            else{   
[360]452              lvalue=PyString_FromStringAndSize(vMap->value,atoi(sMap->value));
453              lsvalue=PyString_FromString(sMap->value);
454              hasSize=1;
455            }
456
457            if(PyList_SetItem(value,i,lvalue)<0){
458              fprintf(stderr,"Unable to set key value pair...");
459              return NULL;
460            } 
461            if(PyList_SetItem(svalue,i,lsvalue)<0){
462              fprintf(stderr,"Unable to set key value pair...");
463              return NULL;
464            } 
465          }
466         
467          map* mMap=getMapArray(tmp,tmap->name,i);
468          PyObject* lmvalue;
469          if(mMap!=NULL){
470            lmvalue=PyString_FromString(mMap->value);
471          }else
472            lmvalue=Py_None;
473         
474          if(PyList_SetItem(mvalue,i,lmvalue)<0){
475              fprintf(stderr,"Unable to set key value pair...");
476              return NULL;
477          } 
478         
479        }
480
481        if(PyDict_SetItem(res,name,value)<0){
482          fprintf(stderr,"Unable to set key value pair...");
483          return NULL;
484        }
485        if(PyDict_SetItem(res,PyString_FromString(tmap->name),mvalue)<0){
486          fprintf(stderr,"Unable to set key value pair...");
487          return NULL;
488        }
489        if(hasSize>0)
490          if(PyDict_SetItem(res,PyString_FromString("size"),svalue)<0){
491            fprintf(stderr,"Unable to set key value pair...");
492            return NULL;
493          }
494      }
495      else if(size!=NULL){
[453]496        PyObject* value=PyString_FromStringAndSize(tmp->value,atoi(size->value));
[59]497        if(PyDict_SetItem(res,name,value)<0){
[471]498          Py_DECREF(value);
[295]499          fprintf(stderr,"Unable to set key value pair...");
500          return NULL;
[43]501        }
[471]502        Py_DECREF(value);
[58]503      }
[59]504      else{
[453]505        PyObject* value=PyString_FromString(tmp->value);
[59]506        if(PyDict_SetItem(res,name,value)<0){
[471]507          Py_DECREF(value);
[295]508          fprintf(stderr,"Unable to set key value pair...");
509          return NULL;
[43]510        }
[471]511        Py_DECREF(value);
[59]512      }
513    }
514    else{
[360]515      if(PyDict_GetItem(res,name)==NULL){
[453]516        PyObject* value=PyString_FromString(tmp->value);
[360]517        if(PyDict_SetItem(res,name,value)<0){
[471]518          Py_DECREF(value);
[360]519          fprintf(stderr,"Unable to set key value pair...");
520          return NULL;
521        }
[471]522        Py_DECREF(value);
[43]523      }
[59]524    }
525    Py_DECREF(name);
[1]526    tmp=tmp->next;
527  }
528  return (PyDictObject*) res;
529}
530
[579]531/**
532 * Convert a Python dictionary to a maps
533 *
534 * @param t the PyDictObject to convert
535 * @return a new maps containing the converted PyDictObject
[781]536 * @warning make sure to free resources returned by this function
[579]537 */
[1]538maps* mapsFromPyDict(PyDictObject* t){
539  maps* res=NULL;
[682]540  maps* cursor=NULL;
[1]541  PyObject* list=PyDict_Keys((PyObject*)t);
542  int nb=PyList_Size(list);
543  int i;
[682]544  PyObject* key;
545  PyObject* value;
[1]546  for(i=0;i<nb;i++){
547#ifdef DEBUG
548    fprintf(stderr,">> parsing maps %d\n",i);
549#endif
[682]550    key=PyList_GetItem(list,i);
551    value=PyDict_GetItem((PyObject*)t,key);
[1]552#ifdef DEBUG
553    fprintf(stderr,">> DEBUG VALUES : %s => %s\n",
554            PyString_AsString(key),PyString_AsString(value));
555#endif
[790]556    cursor=createMaps(PyString_AsString(key));
[295]557    cursor->content=mapFromPyDict((PyDictObject*)value);
[790]558    PyObject* cname=PyString_FromString("child");
559    PyObject* childs=PyDict_GetItem((PyObject*)value,cname);
560    if(childs!=NULL)
561      cursor->child=mapsFromPyDict((PyDictObject*)childs);
562    Py_DECREF(cname);
[1]563#ifdef DEBUG
[295]564    dumpMap(cursor->content);
[1]565#endif
566    cursor->next=NULL;
567    if(res==NULL)
[59]568      res=dupMaps(&cursor);
[1]569    else
570      addMapsToMaps(&res,cursor);
[59]571    freeMap(&cursor->content);
572    free(cursor->content);
573    free(cursor);
[1]574#ifdef DEBUG
575    dumpMaps(res);
576    fprintf(stderr,">> parsed maps %d\n",i);
577#endif
578  }
[505]579  Py_DECREF(list);
[1]580  return res;
581}
582
[579]583/**
[738]584 * Convert a Python dictionary to a maps
585 *
586 * @param t the PyDictObject to convert
587 * @return a new maps containing the converted PyDictObject
588 * @warning make sure to free resources returned by this function
589 */
590maps* _mapsFromPyDict(PyDictObject* t){
591       
592        PyObject* list = PyDict_Keys((PyObject*)t); // new ref 
593        int nb = PyList_Size(list);     
594       
595        if (nb < 1) {
596                Py_DECREF(list);
597                return NULL;
598        }
599
600        maps* ptr = (maps*) malloc(MAPS_SIZE);
601        maps* res = ptr;       
602       
603        PyObject* key;
604        PyObject* value;
605       
606        for(int i = 0; i < nb; i++) {
607               
608                key = PyList_GetItem(list,i); // borrowed ref
609                value = PyDict_GetItem((PyObject*) t, key); // borrowed ref
610               
611                ptr->name = zStrdup(PyString_AsString(key));
612                ptr->content = mapFromPyDict((PyDictObject*) value);
613               
614                ptr->next = i < nb - 1 ? (maps*) malloc(MAPS_SIZE) : NULL;
615                ptr = ptr->next;
616        }
617        Py_DECREF(list);
618
619        return res;
620} // mapsFromPyDict
621
622/**
[579]623 * Convert a Python dictionary to a map
624 *
625 * @param t the PyDictObject to convert
626 * @return a new map containing the converted PyDictObject
[781]627 * @warning make sure to free resources returned by this function
[579]628 */
[1]629map* mapFromPyDict(PyDictObject* t){
630  map* res=NULL;
631  PyObject* list=PyDict_Keys((PyObject*)t);
632  int nb=PyList_Size(list);
633  int i;
[682]634  PyObject* key;
635  PyObject* value;
[1]636  for(i=0;i<nb;i++){
[682]637    key=PyList_GetItem(list,i);
638    value=PyDict_GetItem((PyObject*)t,key);
[1]639#ifdef DEBUG
640    fprintf(stderr,">> DEBUG VALUES : %s => %s\n",
641            PyString_AsString(key),PyString_AsString(value));
642#endif
[790]643    if(strncmp(PyString_AsString(key),"child",5)!=0){
644      if(strncmp(PyString_AsString(key),"value",5)==0){
645        char *buffer=NULL;
646        Py_ssize_t size;
[392]647#if PY_MAJOR_VERSION >= 3
[790]648        if(PyBytes_Check(value)){
649          size=PyBytes_Size(value);
650          buffer=PyBytes_AsString(value);
[682]651        }
[790]652        else
653          if(PyUnicode_Check(value) && PyUnicode_READY(value) == 0){
654            buffer=PyUnicode_AsUTF8AndSize(value,&size);
655          }
656          else{
[738]657#ifdef DEBUG
[790]658            fprintf(stderr,"Unsupported return value.");
[738]659#endif
[790]660            return NULL;
661          }
[392]662#else
[790]663        PyString_AsStringAndSize(value,&buffer,&size);
[738]664#endif     
[790]665        res = addToMapWithSize(res,PyString_AsString(key),buffer,size);
666      }else{
667        char* lkey=PyString_AsString(key);
668        char* lvalue=PyString_AsString(value);
669        if(res!=NULL){
670          if(PyString_Size(value)>0)
671            addToMap(res,lkey,lvalue);
672        }
673        else{
674          if(PyString_Size(value)>0)
675            res=createMap(lkey,lvalue);
676        }
[392]677      }
[67]678    }
[1]679  }
[505]680  Py_DECREF(list);
[1]681  return res;
682}
[368]683
[579]684/**
[738]685 * Convert a Python dictionary to a map
686 *
687 * @param t the PyDictObject to convert
688 * @return a new map containing the converted PyDictObject
689 * @warning make sure to free resources returned by this function
690 */
691map* _mapFromPyDict(PyDictObject* t) {
692       
693        PyObject* list = PyDict_Keys((PyObject*) t); // new ref
694        int nb = PyList_Size(list);
695       
696        if (nb < 1) {
697                Py_DECREF(list);
698                return NULL;
699        }       
700       
701        map* ptr = (map*) malloc(MAP_SIZE);
702        map* res = ptr;
703       
704        PyObject* key;
705        PyObject* value;
706        char *buffer = NULL;
707        Py_ssize_t size;
708        for(int i = 0; i < nb; i++) {
709               
710                key = PyList_GetItem(list, i); // borrowed ref
711                value = PyDict_GetItem((PyObject*) t, key); // borrowed ref             
712                               
713                ptr->name = zStrdup(PyString_AsString(key));           
714                map* msize = NULL;
715               
716        #if PY_MAJOR_VERSION >= 3
717                if (PyBytes_Check(value)) {
718                // value is byte array
719                        size = PyBytes_Size(value);                             
720                        buffer = PyBytes_AsString(value); // pointer to internal buffer
721                        char sz[32];
722                        sprintf(sz, "%d", (int) size); 
723                        msize = createMap("size", sz);                 
724                }
725                else if (PyUnicode_Check(value) && PyUnicode_READY(value) == 0) {
726                // value is string object               
727                        buffer = PyUnicode_AsUTF8AndSize(value, &size);
728                        size++;
729                }
730                else {
731                        printf("Type not recognized\n");
732                        // error handling
733                        // ...
734                }
735        #else   
736                PyString_AsStringAndSize(value, &buffer, &size);
737                size++;
738                // to do: handle byte arrays
739        #endif
740               
741                ptr->value = (char*) malloc(size); // check for NULL pointer
742                memmove(ptr->value, buffer, size);
743                       
744                if (msize != NULL) {
745                        ptr->next = msize;
746                        ptr = ptr->next;
747                }                                               
748               
749                ptr->next = i < nb - 1 ? (map*) malloc(MAP_SIZE) : NULL;
750                ptr = ptr->next;
751        }       
752        Py_DECREF(list);
753                       
754        return res;
755} // mapFromPyDict
756
757/**
[580]758 * Use the ZOO-Services messages translation function from the Python
[579]759 * environment
760 *
761 * @param self the Python object on which we can run the method
762 * @param args the Python arguments given from the Python environment
[581]763 * @return a new Python string containing the translated value
[579]764 * @see _ss
765 */
[368]766PyObject*
[376]767PythonTranslate(PyObject* self, PyObject* args)
768{
769  char *str;
770  if (!PyArg_ParseTuple(args, "s", &str)){
771#ifdef DEBUG
772    fprintf(stderr,"Incorrect arguments to update status function");
773#endif
774    return NULL;
775  }
776  return PyString_FromString(_ss(str));
777}
778
[579]779/**
780 * Update the ongoing status of a running service from the Python environment
781 *
782 * @param self the Python object on which we can run the method
783 * @param args the Python arguments given from the Python environment
784 * @return None to the Python environment
785 * @see _updateStatus
786 */
[376]787PyObject*
[368]788PythonUpdateStatus(PyObject* self, PyObject* args)
789{
790  maps* conf;
791  PyObject* confdict;
792  int istatus;
[624]793  char* status=NULL;
[368]794  if (!PyArg_ParseTuple(args, "O!i", &PyDict_Type, &confdict, &istatus)){
795#ifdef DEBUG
796    fprintf(stderr,"Incorrect arguments to update status function");
797#endif
[624]798    Py_RETURN_NONE;
[368]799  }
800  if (istatus < 0 || istatus > 100){
801     PyErr_SetString(ZooError, "Status must be a percentage.");
[624]802     Py_RETURN_NONE;
[368]803  }else{
804     char tmpStatus[4];
805     snprintf(tmpStatus, 4, "%i", istatus);
[453]806     status = zStrdup(tmpStatus);
[368]807  }
[624]808  // create a local copy and update the lenv map
[368]809  conf = mapsFromPyDict((PyDictObject*)confdict);
[624]810  if(status!=NULL){
811    setMapInMaps(conf,"lenv","status",status);
812    free(status);
[368]813  }
[624]814  else
815    setMapInMaps(conf,"lenv","status","15");
816  _updateStatus(conf);
[368]817  freeMaps(&conf);
818  free(conf);
819  Py_RETURN_NONE;
820}
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