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

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

HPC support update. Add inputs for create options in Gdal_Dem.

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