source: branches/prototype-v0/zoo-project/zoo-kernel/service_internal.c @ 862

Last change on this file since 862 was 862, checked in by djay, 6 years ago

Add the capability to publish heatmap or any templated mapfile using the epecific msInclude and msLayer keys for an output. For MapServer? published output, define 4096 as the default maxsize and use pixel width or height for raster files. use the correct MapServer? imagemode depending on GDALGetRasterDataType (MS_IMAGEMODE_BYTE for GDT_Byte, MS_IMAGEMODE_INT16 for GDT_Int16 and MS_IMAGEMODE_FLOAT32 for GDT_Float32). Create a text file (.maps) listing every mapfiles created for a MapServer? published output (or inputs) using saveMapNames function. Fixes in ulinet, use uuid for naming temporary files. Add dialect input to the ogr2ogr service. Use the .maps file for removing a file from the DeleteData? service

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 22.5 KB
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 * Copyright (c) 2009-2015 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#define _LARGEFILE64_SOURCE 1
26#ifdef USE_MS
27#include "service_internal_ms.h"
28#else
29#include "cpl_vsi.h"
30#endif
31#include "service_internal.h"
32
33#ifndef TRUE
34#define TRUE 1
35#endif
36#ifndef FALSE
37#define FALSE -1
38#endif
39
40#define ERROR_MSG_MAX_LENGTH 1024
41
42/**
43 * Lock a file for read, write and upload.
44 * @param conf the main configuration maps
45 * @param filename the file to lock
46 * @param mode define access: 'r' for read, 'w' for write
47 * @return a new zooLock structure on sucess, NULL on failure
48 */
49struct zooLock* lockFile(maps* conf,const char* filename,const char mode){
50  struct stat f_status;
51  int itn=0;
52  int s;
53  struct zooLock* myLock=(struct zooLock*)malloc(sizeof(struct flock)+sizeof(FILE*)+sizeof(char*));
54  int len=6;
55  char *template="%s.lock";
56  int res=-1;
57 retryLockFile:
58  myLock->filename=(char*)malloc((strlen(filename)+len)*sizeof(char));
59  sprintf(myLock->filename,"%s.lock",filename);
60  s=stat(myLock->filename, &f_status);
61  if(s==0 && mode!='r'){
62    if(itn<ZOO_LOCK_MAX_RETRY){
63      itn++;
64      fprintf(stderr,"(%d) Wait for write lock on %s, tried %d times (sleep) ... \n",getpid(),myLock->filename,itn);
65      fflush(stderr);
66      sleep(5);
67      free(myLock->filename);
68      goto retryLockFile;
69    }else{
70      free(myLock->filename);
71      free(myLock);
72      return NULL;
73    }
74  }else{
75    char local_mode[3];
76    memset(local_mode,0,3);
77    if(mode=='w')
78      sprintf(local_mode,"%c+",mode);
79    else
80      sprintf(local_mode,"%c",mode);
81    myLock->lockfile=fopen(myLock->filename,local_mode);
82    char tmp[512];
83    sprintf(tmp,"%d",getpid());
84    if(myLock->lockfile==NULL){
85      myLock->lockfile=fopen(myLock->filename,"w+");
86      fwrite(tmp,sizeof(char),strlen(tmp),myLock->lockfile);
87      fflush(myLock->lockfile);
88      fclose(myLock->lockfile);
89      myLock->lockfile=fopen(myLock->filename,local_mode);
90    }/*else
91       fprintf(stderr,"%s %d %d\n",__FILE__,__LINE__,(myLock->lockfile==NULL));*/
92    if(mode!='r'){
93      fwrite(tmp,sizeof(char),strlen(tmp),myLock->lockfile);
94      fflush(myLock->lockfile);
95    }
96    int cnt=0;
97    if(mode=='r'){
98      myLock->lock.l_type = F_RDLCK;
99    }else
100      myLock->lock.l_type = F_WRLCK;
101    myLock->lock.l_whence = 0;
102    myLock->lock.l_start = 0;
103    myLock->lock.l_len = strlen(tmp)*sizeof(char);
104    while (true) {
105      if((res=fcntl(fileno(myLock->lockfile), F_SETLK, &(myLock->lock)))==-1 &&
106         (errno==EAGAIN || errno==EACCES)){
107        if(cnt >= ZOO_LOCK_MAX_RETRY){
108          char message[51];       
109          sprintf(message,"Unable to get the lock after %d attempts.\n",cnt);
110          setMapInMaps(conf,"lenv","message",message);
111          fclose(myLock->lockfile);
112          free(myLock->filename);
113          free(myLock);
114          return NULL;
115        }
116        fprintf(stderr,"(%d) Wait for lock on  %s, tried %d times ... \n",getpid(),myLock->filename,cnt);
117        fflush(stderr);
118        sleep(1);
119        cnt++;
120      }else
121        break;
122    }
123    if(res<0){
124      char *tmp;
125      if(errno==EBADF)
126        tmp="Either: the filedes argument is invalid; you requested a read lock but the filedes is not open for read access; or, you requested a write lock but the filedes is not open for write access.";
127      else
128        if(errno==EINVAL)
129          tmp="Either the lockp argument doesn’t specify valid lock information, or the file associated with filedes doesn’t support locks.";
130        else
131          tmp="The system has run out of file lock resources; there are already too many file locks in place.";
132      fprintf(stderr,"Unable to get the lock on %s due to the following error: %s\n",myLock->filename,tmp);
133      return NULL;
134    }
135    return myLock;
136  }
137}
138
139/**
140 * Remove a lock.
141 * @param conf the main configuration maps
142 * @param s the zooLock structure
143 * @return 0 on success, -1 on failure.
144 */
145int unlockFile(maps* conf,struct zooLock* s){
146  int res=-1;
147  if(s!=NULL){
148    s->lock.l_type = F_UNLCK;
149    res=fcntl(fileno(s->lockfile), F_SETLK, &s->lock);
150    if(res==-1)
151      return res;
152    // Check if there is any process locking a file and delete the lock if not.
153    s->lock.l_type = F_WRLCK;
154    if(fcntl(fileno(s->lockfile), F_GETLK, &s->lock)!=-1 && s->lock.l_type == F_UNLCK){
155      unlink(s->filename);
156    }
157    fclose(s->lockfile);
158    free(s->filename);
159    free(s);
160  }
161  return res;
162}
163
164#ifndef RELY_ON_DB
165#include <dirent.h>
166
167/**
168 * Read the sid file attached of a service if any
169 *
170 * @param conf the maps containing the setting of the main.cfg file
171 * @param pid the service identifier (usid key from the [lenv] section)
172 * @return the reported status char* (temporary/final result)
173 */
174char* getStatusId(maps* conf,char* pid){
175  map* r_inputs = getMapFromMaps (conf, "main", "tmpPath");
176  char* fbkpid =
177    (char *)
178    malloc ((strlen (r_inputs->value) + strlen (pid) + 7) * sizeof (char));
179  sprintf (fbkpid, "%s/%s.sid", r_inputs->value, pid);
180  FILE* f0 = fopen (fbkpid, "r");
181  if(f0!=NULL){
182    long flen;
183    char *fcontent;
184    fseek (f0, 0, SEEK_END);
185    flen = ftell (f0);
186    fseek (f0, 0, SEEK_SET);
187    fcontent = (char *) malloc ((flen + 1) * sizeof (char));
188    fread(fcontent,flen,1,f0);
189    fcontent[flen]=0;
190    fclose(f0);
191    return fcontent;
192  }else
193    return NULL;
194}
195
196/**
197 * Acquire the global lock
198 *
199 * @param conf the maps containing the setting of the main.cfg file
200 * @return a semid
201 */
202semid acquireLock(maps* conf){
203  semid lockid;
204  int itn=0;
205 toRetry1:
206  lockid=getShmLockId(conf,1);
207  if(
208#ifdef WIN32
209     lockid==NULL
210#else
211     lockid<0
212#endif
213     ){
214#ifdef WIN32
215    return NULL;
216#else
217    return -1;
218#endif
219  }
220  if(lockShm(lockid)<0){
221#ifdef WIN32
222      return NULL;
223#else
224    if(itn<ZOO_LOCK_MAX_RETRY){
225      itn++;
226      goto toRetry1;
227    }else
228      return -1;
229#endif
230  }else
231    return lockid;
232}
233
234/**
235 * Read the cache file of a running service
236 *
237 * @param conf the maps containing the setting of the main.cfg file
238 * @param pid the service identifier (usid key from the [lenv] section)
239 * @return the reported status char* (temporary/final result)
240 */
241char* _getStatusFile(maps* conf,char* pid){
242  map* tmpTmap = getMapFromMaps (conf, "main", "tmpPath");
243
244  struct dirent *dp;
245  DIR *dirp = opendir(tmpTmap->value);
246  char fileName[1024];
247  int hasFile=-1;
248  if(dirp!=NULL){
249    char tmp[128];
250    sprintf(tmp,"_%s.xml",pid);
251    while ((dp = readdir(dirp)) != NULL){
252#ifdef DEBUG
253      fprintf(stderr,"File : %s searched : %s\n",dp->d_name,tmp);
254#endif
255      if(strstr(dp->d_name,"final_")==0 && strstr(dp->d_name,tmp)!=0){
256        sprintf(fileName,"%s/%s",tmpTmap->value,dp->d_name);
257        hasFile=1;
258        break;
259      }
260    }
261  }
262  if(hasFile>0){
263    semid lockid;
264    char* stat=getStatusId(conf,pid);
265    if(stat!=NULL){
266      setMapInMaps(conf,"lenv","lid",stat);
267      lockid=acquireLock(conf);
268      if(lockid<0)
269        return NULL;
270    }
271
272    //FILE* f0 = fopen (fileName, "r");
273    // knut: open file in binary mode to avoid conversion of line endings (yielding extra bytes) on Windows platforms
274    FILE* f0 = fopen(fileName, "rb"); 
275    if(f0!=NULL){
276      fseek (f0, 0, SEEK_END);
277      long flen = ftell (f0);
278      fseek (f0, 0, SEEK_SET);
279      char *tmps1 = (char *) malloc ((flen + 1) * sizeof (char));
280      fread(tmps1,flen,1,f0);
281      tmps1[flen]=0;
282      fclose(f0);
283      if(stat!=NULL){
284        unlockShm(lockid);
285        free(stat);
286      }
287      return tmps1;
288    }
289    else{
290      if(stat!=NULL){
291        unlockShm(lockid);
292        free(stat);
293      }
294      return NULL;
295    }
296  }
297  else
298    return NULL;
299}
300
301/**
302 * Get the ongoing status of a running service
303 *
304 * @param conf the maps containing the setting of the main.cfg file
305 * @param pid the service identifier (usid key from the [lenv] section)
306 * @return the reported status char* (MESSAGE|POURCENTAGE)
307 */
308char* _getStatus(maps* conf,char* lid){
309  map* r_inputs = getMapFromMaps (conf, "main", "tmpPath");
310  char* fbkpid =
311    (char *)
312    malloc ((strlen (r_inputs->value) + strlen (lid) + 9) * sizeof (char));
313  sprintf (fbkpid, "%s/%s.status", r_inputs->value, lid);
314  FILE* f0 = fopen (fbkpid, "r");
315  if(f0!=NULL){   
316    semid lockid = NULL;
317    char* stat;
318    long flen;
319    stat=getStatusId(conf,lid);
320    if(stat!=NULL){
321      setMapInMaps(conf,"lenv","lid",stat);
322      lockid=acquireLock(conf);
323      if(lockid<0)
324        return NULL;
325    }
326    fseek (f0, 0, SEEK_END);
327    flen = ftell (f0);
328    if(flen>0){
329      char *fcontent;
330      fseek (f0, 0, SEEK_SET);
331      fcontent = (char *) malloc ((flen + 1) * sizeof (char));
332      fread(fcontent,flen,1,f0);
333      fcontent[flen]=0;
334      fclose(f0);
335      free(fbkpid);
336      if(stat!=NULL){
337#ifndef WIN32
338        removeShmLock(conf,1);
339#else
340        unlockShm(lockid);
341#endif
342        free(stat);
343      }
344      return fcontent;
345    }
346    fclose(f0);
347    free(fbkpid);
348    if(stat!=NULL){
349      removeShmLock(conf,1);
350      free(stat);
351    }
352    return NULL;
353  }else{
354    free(fbkpid);
355    char* stat=getStatusId(conf,lid);
356    setMapInMaps(conf,"lenv","lid",stat);
357    removeShmLock(conf,1);
358    return NULL;
359  }
360}
361
362/**
363 * Stop handling status repport.
364 *
365 * @param conf the map containing the setting of the main.cfg file
366 */
367void unhandleStatus(maps *conf){
368  map* r_inputs = getMapFromMaps (conf, "main", "tmpPath");
369  map* usid = getMapFromMaps (conf, "lenv", "usid");
370  char* fbkpid =
371    (char *) malloc ((strlen (r_inputs->value) + strlen (usid->value) + 9) 
372                     * sizeof (char));
373  sprintf (fbkpid, "%s/%s.status", r_inputs->value, usid->value);
374  unlink(fbkpid);
375  free(fbkpid);
376}
377
378/**
379 * Update the current status of the running service.
380 *
381 * @see acquireLock, lockShm
382 * @param conf the map containing the setting of the main.cfg file
383 * @return 0 on success, -2 if shmget failed, -1 if shmat failed
384 */
385int _updateStatus(maps *conf){
386       
387  map* r_inputs = getMapFromMaps (conf, "main", "tmpPath");
388  map* sid = getMapFromMaps (conf, "lenv", "usid");
389 
390  char* fbkpid =
391    (char *)
392    malloc ((strlen (r_inputs->value) + strlen (sid->value) + 9) * sizeof (char));
393  sprintf (fbkpid, "%s/%s.status", r_inputs->value, sid->value);
394  map* status=getMapFromMaps(conf,"lenv","status");
395  map* msg=getMapFromMaps(conf,"lenv","message");
396  if(status!=NULL && msg!=NULL &&
397     status->value!=NULL && msg->value!=NULL && 
398     strlen(status->value)>0 && strlen(msg->value)>1){   
399    semid lockid = NULL;
400       
401    char* stat=getStatusId(conf,sid->value);
402    if(stat!=NULL){
403      lockid=acquireLock(conf);
404      if(lockid<0){
405        dumpMap(status);
406        return ZOO_LOCK_ACQUIRE_FAILED;
407      }
408    }
409    FILE* fstatus=fopen(fbkpid,"w");
410    if(fstatus!=NULL){
411      fprintf(fstatus,"%s|%s",status->value,msg->value);
412      fflush(fstatus);
413      fclose(fstatus);
414    }
415    if(stat!=NULL){
416      unlockShm(lockid);
417      free(stat);
418    }
419  }
420
421  return 0;
422}
423
424#endif
425
426#ifdef WIN32
427
428#define SHMEMSIZE 4096
429
430size_t getKeyValue(maps* conf, char* key, size_t length){
431  if(conf==NULL) {
432    strncpy(key, "700666", length);
433    return strlen(key);
434  }
435 
436  map *tmpMap=getMapFromMaps(conf,"lenv","lid");
437  if(tmpMap==NULL)
438    tmpMap=getMapFromMaps(conf,"lenv","osid");
439
440  if(tmpMap!=NULL){
441    snprintf(key, length, "zoo_sem_%s", tmpMap->value);     
442  }
443  else {
444    strncpy(key, "-1", length);
445  }
446  return strlen(key);
447}
448
449
450semid getShmLockId(maps* conf, int nsems){
451  semid sem_id;
452  char key[MAX_PATH];
453  getKeyValue(conf, key, MAX_PATH);
454 
455  sem_id = CreateSemaphore( NULL, nsems, nsems+1, key);
456  if(sem_id==NULL){
457#ifdef DEBUG
458    fprintf(stderr,"Semaphore failed to create: %s\n", getLastErrorMessage());
459#endif
460    return NULL;
461  }
462#ifdef DEBUG
463  fprintf(stderr,"%s Accessed !\n",key);
464#endif
465  return sem_id;
466}
467
468int removeShmLock(maps* conf, int nsems){
469  semid sem_id=getShmLockId(conf,1);
470  if (CloseHandle(sem_id) == 0) {
471#ifdef DEBUG
472    fprintf(stderr,"Unable to remove semaphore: %s\n", getLastErrorMessage());
473#endif
474    return -1;
475  }
476#ifdef DEBUG
477  fprintf(stderr,"%d Removed !\n",sem_id);
478#endif
479  return 0;
480}
481
482int lockShm(semid id){
483  DWORD dwWaitResult=WaitForSingleObject(id,INFINITE);
484  switch (dwWaitResult){
485    case WAIT_OBJECT_0:
486      return 0;
487      break;
488    case WAIT_TIMEOUT:
489      return -1;
490      break;
491    default:
492      return -2;
493      break;
494  }
495  return 0;
496}
497
498int unlockShm(semid id){
499  if(!ReleaseSemaphore(id,1,NULL)){
500    return -1;
501  }
502  return 0;
503}
504
505static LPVOID lpvMemG = NULL;      // pointer to shared memory
506static HANDLE hMapObjectG = NULL;  // handle to file mapping
507
508
509char* getStatus(int pid){
510  char *lpszBuf=(char*) malloc(SHMEMSIZE*sizeof(char));
511  int i=0;
512  LPWSTR lpszTmp=NULL;
513  LPVOID lpvMem = NULL;
514  HANDLE hMapObject = NULL;
515  BOOL fIgnore,fInit;
516  char tmp[1024];
517  sprintf(tmp,"%d",pid);
518  if(hMapObject==NULL)
519    hMapObject = CreateFileMapping( 
520                                   INVALID_HANDLE_VALUE,   // use paging file
521                                   NULL,                   // default security attributes
522                                   PAGE_READWRITE,         // read/write access
523                                   0,                      // size: high 32-bits
524                                   4096,                   // size: low 32-bits
525                                   TEXT(tmp));   // name of map object
526  if (hMapObject == NULL){
527#ifdef DEBUG
528    fprintf(stderr,"ERROR on line %d\n",__LINE__);
529#endif
530    return "-1";
531  }
532  if((GetLastError() != ERROR_ALREADY_EXISTS)){
533#ifdef DEBUG
534    fprintf(stderr,"ERROR on line %d\n",__LINE__);
535    fprintf(stderr,"READING STRING S %s\n", getLastErrorMessage());
536#endif
537    fIgnore = UnmapViewOfFile(lpvMem); 
538    fIgnore = CloseHandle(hMapObject);
539    return "-1";
540  }
541  fInit=TRUE;
542  if(lpvMem==NULL)
543    lpvMem = MapViewOfFile( 
544                           hMapObject,     // object to map view of
545                           FILE_MAP_READ,  // read/write access
546                           0,              // high offset:  map from
547                           0,              // low offset:   beginning
548                           0);             // default: map entire file
549  if (lpvMem == NULL){
550#ifdef DEBUG
551    fprintf(stderr,"READING STRING S %d\n",__LINE__);
552    fprintf(stderr,"READING STRING S %s\n", getLastErrorMessage());
553#endif
554    return "-1"; 
555  }
556  lpszTmp = (LPWSTR) lpvMem;
557  while (*lpszTmp){
558    lpszBuf[i] = (char)*lpszTmp;
559    *lpszTmp++; 
560    lpszBuf[i+1] = '\0'; 
561    i++;
562  }
563  return (char*)lpszBuf;
564}
565
566#else
567/**
568 * Number of time to try to access a semaphores set
569 * @see getShmLockId
570 */
571#define MAX_RETRIES 10
572
573#ifndef __APPLE__
574/**
575 * arg for semctl system calls.
576 */
577union semun {
578  int val; //!< value for SETVAL
579  struct semid_ds *buf; //!< buffer for IPC_STAT & IPC_SET
580  ushort *array; //!< array for GETALL & SETALL
581};
582#endif
583
584/**
585 * Set in the pre-allocated key the zoo_sem_[OSID] string
586 * where [OSID] is the lid (if any) or osid value from the [lenv] section.
587 *
588 * @param conf the map containing the setting of the main.cfg file
589 */
590int getKeyValue(maps* conf){
591  if(conf==NULL)
592     return 700666;
593  map *tmpMap=getMapFromMaps(conf,"lenv","lid");
594  if(tmpMap==NULL)
595    tmpMap=getMapFromMaps(conf,"lenv","osid");
596  int key=-1;
597  if(tmpMap!=NULL)
598    key=atoi(tmpMap->value);
599  return key;
600}
601
602/**
603 * Try to create or access a semaphore set.
604 *
605 * @see getKeyValue
606 * @param conf the map containing the setting of the main.cfg file
607 * @param nsems number of semaphores
608 * @return a semaphores set indentifier on success, -1 in other case
609 */
610int getShmLockId(maps* conf, int nsems){
611    int i;
612    union semun arg;
613    struct semid_ds buf;
614    struct sembuf sb;
615    semid sem_id;
616    int key=getKeyValue(conf);
617   
618    sem_id = semget(key, nsems, IPC_CREAT | IPC_EXCL | 0666);
619
620    if (sem_id >= 0) { /* we got it first */
621        sb.sem_op = 1; 
622        sb.sem_flg = 0;
623        arg.val=1;
624        for(sb.sem_num = 0; sb.sem_num < nsems; sb.sem_num++) { 
625            /* do a semop() to "free" the semaphores. */
626            /* this sets the sem_otime field, as needed below. */
627            if (semop(sem_id, &sb, 1) == -1) {
628                int e = errno;
629                semctl(sem_id, 0, IPC_RMID); /* clean up */
630                errno = e;
631                return -1; /* error, check errno */
632            }
633        }
634    } else if (errno == EEXIST) { /* someone else got it first */
635        int ready = 0;
636
637        sem_id = semget(key, nsems, 0); /* get the id */
638        if (sem_id < 0) return sem_id; /* error, check errno */
639
640        /* wait for other process to initialize the semaphore: */
641        arg.buf = &buf;
642        for(i = 0; i < MAX_RETRIES && !ready; i++) {
643            semctl(sem_id, nsems-1, IPC_STAT, arg);
644            if (arg.buf->sem_otime != 0) {
645#ifdef DEBUG
646              fprintf(stderr,"Semaphore acquired ...\n");
647#endif
648              ready = 1;
649            } else {
650#ifdef DEBUG
651              fprintf(stderr,"Retry to access the semaphore later ...\n");
652#endif
653              zSleep(1000);
654            }
655        }
656        errno = ZOO_LOCK_ACQUIRE_FAILED;
657        if (!ready) {
658#ifdef DEBUG
659          fprintf(stderr,"Unable to access the semaphore ...\n");
660#endif
661          errno = ETIME;
662          return -1;
663        }
664    } else {
665        return sem_id; /* error, check errno */
666    }
667#ifdef DEBUG
668    fprintf(stderr,"%d Created !\n",sem_id);
669#endif
670    return sem_id;
671}
672
673/**
674 * Try to remove a semaphore set.
675 *
676 * @param conf the map containing the setting of the main.cfg file
677 * @param nsems number of semaphores
678 * @return 0 if the semaphore can be removed, -1 in other case.
679 */
680int removeShmLock(maps* conf, int nsems){
681  union semun arg;
682  int sem_id=getShmLockId(conf,nsems);
683  if (semctl(sem_id, 0, IPC_RMID, arg) == -1) {
684#ifdef DEBUG
685    perror("semctl remove");
686#endif
687    return -1;
688  }
689#ifdef DEBUG
690  fprintf(stderr,"Semaphore removed!\n");
691#endif
692  return 0;
693}
694
695/**
696 * Lock a semaphore set.
697 *
698 * @param id the semaphores set indetifier
699 * @return 0 if the semaphore can be locked, -1 in other case.
700 */
701int lockShm(int id){
702  struct sembuf sb;
703  sb.sem_num = 0;
704  sb.sem_op = -1;  /* set to allocate resource */
705  sb.sem_flg = SEM_UNDO;
706  if (semop(id, &sb, 1) == -1){
707#ifdef DEBUG
708    perror("semop lock");
709#endif
710    return -1;
711  }
712  return 0;
713}
714
715/**
716 * unLock a semaphore set.
717 *
718 * @param id the semaphores set indetifier
719 * @return 0 if the semaphore can be locked, -1 in other case.
720 */
721int unlockShm(int id){
722  struct sembuf sb;
723  sb.sem_num = 0;
724  sb.sem_op = 1;  /* free resource */
725  sb.sem_flg = SEM_UNDO;
726  if (semop(id, &sb, 1) == -1) {
727#ifdef DEBUG
728    perror("semop unlock");
729#endif
730    return -1;
731  }
732  return 0;
733}
734
735/**
736 * Get the current status of the running service.
737 *
738 * @see getKeyValue, getShmLockId, lockShm
739 * @param pid the semaphores
740 * @return 0 on success, -2 if shmget failed, -1 if shmat failed
741 */
742char* getStatus(int pid){
743  int shmid;
744  key_t key;
745  void *shm;
746  key=pid;
747  if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
748#ifdef DEBUG
749    fprintf(stderr,"shmget failed in getStatus\n");
750#endif
751  }else{
752    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
753#ifdef DEBUG
754      fprintf(stderr,"shmat failed in getStatus\n");
755#endif
756    }else{
757      char *ret=strdup((char*)shm);
758      shmdt((void *)shm);
759      return ret;
760    }
761  }
762  return (char*)"-1";
763}
764
765#endif
766
767/**
768 * Update the status of an ongoing service
769 *
770 * @param conf the maps containing the settings of the main.cfg file
771 * @param percentCompleted percentage of completude of execution of the service
772 * @param message information about the current step executed
773 * @return the value of _updateStatus
774 * @see _updateStatus
775 */
776int updateStatus( maps* conf, const int percentCompleted, const char* message ){
777  char tmp[4];
778  snprintf(tmp,4,"%d",percentCompleted);
779  setMapInMaps( conf, "lenv", "status", tmp );
780  setMapInMaps( conf, "lenv", "message", message);
781  return _updateStatus( conf );
782}
783
784/**
785 * Access an input value
786 *
787 * @param inputs the maps to search for the input value
788 * @param parameterName the input name to fetch the value
789 * @param numberOfBytes the resulting size of the value to add (for binary
790 *  values), -1 for basic char* data
791 * @return a pointer to the input value if found, NULL in other case.
792 */
793char* getInputValue( maps* inputs, const char* parameterName, size_t* numberOfBytes){
794  map* res=getMapFromMaps(inputs,parameterName,"value");
795  if(res!=NULL){
796    map* size=getMapFromMaps(inputs,parameterName,"size");
797    if(size!=NULL){
798      *numberOfBytes=(size_t)atoi(size->value);
799      return res->value;
800    }else{
801      *numberOfBytes=strlen(res->value);
802      return res->value;
803    }
804  }
805  return NULL;
806}
807
808/**
809 * Read a file using the GDAL VSI API
810 *
811 * @param conf the maps containing the settings of the main.cfg file
812 * @param dataSource the datasource name to read
813 * @warning make sure to free resources returned by this function
814 */
815char *readVSIFile(maps* conf,const char* dataSource){
816    VSILFILE * fichier=VSIFOpenL(dataSource,"rb");
817    VSIStatBufL file_status;
818    VSIStatL(dataSource, &file_status);
819    if(fichier==NULL){
820      char tmp[1024];
821      sprintf(tmp,"Failed to open file %s for reading purpose. File seems empty %lld.",
822              dataSource,file_status.st_size);
823      setMapInMaps(conf,"lenv","message",tmp);
824      return NULL;
825    }
826    char *res1=(char *)malloc(file_status.st_size*sizeof(char));
827    VSIFReadL(res1,1,file_status.st_size*sizeof(char),fichier);
828    res1[file_status.st_size-1]=0;
829    VSIFCloseL(fichier);
830    VSIUnlink(dataSource);
831    return res1;
832}
833
834/**
835 * Set an output value
836 *
837 * @param outputs the maps to define the output value
838 * @param parameterName the output name to set the value
839 * @param data the value to set
840 * @param numberOfBytes size of the value to add (for binary values), -1 for
841 *  basic char* data
842 * @return 0
843 */
844int  setOutputValue( maps* outputs, const char* parameterName, char* data, size_t numberOfBytes ){
845  if(numberOfBytes==-1){
846    setMapInMaps(outputs,parameterName,"value",data);
847  }else{
848    char size[1024];
849    map* tmp=getMapFromMaps(outputs,parameterName,"value");
850    if(tmp==NULL){
851      setMapInMaps(outputs,parameterName,"value","");
852      tmp=getMapFromMaps(outputs,parameterName,"value");
853    }
854    free(tmp->value);
855    tmp->value=(char*) malloc((numberOfBytes+1)*sizeof(char));
856    memcpy(tmp->value,data,numberOfBytes);
857    sprintf(size,"%lu",numberOfBytes);
858    setMapInMaps(outputs,parameterName,"size",size);
859  }
860  return 0;
861}
862
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