source: trunk/zoo-project/zoo-kernel/service_internal.c @ 951

Last change on this file since 951 was 945, checked in by djay, 5 years ago

Fix the issue with JavaScript? support and GDAL profile service

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