File: Server.cc

package info (click to toggle)
gnuift 0.1.14%2Bds-1
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 5,632 kB
  • ctags: 2,973
  • sloc: cpp: 15,867; sh: 8,281; ansic: 1,812; perl: 1,007; php: 651; makefile: 483; lisp: 344
file content (716 lines) | stat: -rw-r--r-- 18,435 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
/*---------------------------------------------------------------------------

  Program name : Server.cc                   			        
							
  Function : An example MRML server

  Creation Date : July 1999						

  Author : Wolfgang Mller

  (some very small parts (< 200 lines)
   of this code still stem from 
   Jilali Raki's MREP based server)
 									
  Last modification: December 2001 (don't count on this date)


  defines: _NON_BLOCKING: if !=0 then the socket will be used as a non-blocking one
           __GIFT_NEW_OPERATOR_NEW 
	                  use my own memory management

  ---------------------------------------------------------------------------*/

//use stuff by Wolfgang which has not yet been "released" to the group
#define WOLFGANG_DEVELOPER
#include <exception> // standard exceptions
using namespace std;

#ifdef __GIFT_NEW_OPERATOR_NEW
//  this is a self-made memory manager
#include "libMRML/include/CDebuggingMemoryManager.h"
//  this is for replacing the new() operator
#include "libMRML/include/myNew.h"
CDebuggingMemoryManager gMemManager(MEMSIZE);
#endif

#define _GNU_SOURCE
#include <getopt.h>

#include <stdlib.h>
#include <cassert>
#include <iostream>
#include <fstream>

// mutual excludes for
// multithreading
#include "libMRML/include/CMutex.h"
extern CMutex* gMutex;

#ifdef __GIFT_NEW_IS_MALLOC
void* operator new(size_t s){
//   assert(s<10000000);
//   if(s>10000000){
//     cout << ">" << flush;
//   }else{
//     if(s>100000){
//       cout << "!" << flush;
//     }else{
//       if(s>1000){
// 	cout << "" << flush;
//       }else{
// 	cout << "." << flush;
//       }
//     }
//   }
  if(gMutex){
    gMutex->lock();
  }
  void *lResult(malloc(s));
  if(gMutex){
    gMutex->unlock();
  }
  return lResult;
}
void* operator new[](size_t s){
  return operator new(s);
}
void operator delete(void * inToBeDeleted){
  if(gMutex){
    gMutex->lock();
  }
  free(inToBeDeleted);
  if(gMutex){
    gMutex->unlock();
  }
}
void operator delete[](void* inToBeDeleted){ 
  delete(inToBeDeleted); 
} 
#endif

// the gift exceptions
#include "../gift-config.h"
#include "libMRML/include/GIFTExceptions.h"

// c++ standard library stuff
#include <functional>
#include <iostream>
#include <algorithm>
#include <string>
//c standard functions
#include <cstdio>
#include <stdlib.h>
#include <cmath>

//Sockets
#include <ctime>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
//to be more specific: internet sockets
#include <arpa/inet.h>
#include <netinet/tcp.h>
//will we need the line below?
//#include <linux/socket.h>

//the expat xml parser by J.Clark
//#include "expat/xmlparse/xmlparse.h"
#include <expat.h>
//a class for using xpat attributes in a nice way
#include "libMRML/include/CAttributeList.h"

//for making distance matrices
#include "libGIFTAcURL2FTS/include/CAcURL2FTS.h"

//This is mrml+gift specific
#include "libMRML/include/mrml_const.h" //important constants for parsing
#include "libMRML/include/CAccessorAdminCollection.h"
#include "libMRML/include/CSessionManager.h"
#include "libMRML/include/CAccessor.h" // distance matrix
//for debugging
#define _DEBUG
#define _NON_BLOCKING 0

#include "libMRML/include/CCommunicationHandler.h"

#ifdef __GIFT_SERVER_TREADS__
#define  __GIFT_USES_THREADS__
#endif

#ifdef __NO_GIFT_SERVER_THREADS__
#undef  __GIFT_USES_THREADS__
#endif

#include "processMessage.h"
#include "CProcessMessageParameters.h"

//#undef  __GIFT_USES_THREADS__ // for debugging
long PORT = 12789; /* port number: this line, for example, is by J. Raki ;-)*/

/***********************************************************************
 itoa								
									
 Function : Converts integer to String using sprintf
									
 Input    : Integer 

 Return   : String 

 ***********************************************************************/
extern string itoa (int val,int length) ;

extern string dtoa (double val) ;//..maybe this line is also by J. Raki ;-)



extern string gGIFTHome;
//waiting that everything has arrived
extern void waitWriteStream(int inWritingSocket);
extern void waitReadStream(int inReadingSocket);

extern void waitExceptionStream(int inExceptioningSocket);


/***********************************************************************
  sendMessage								
  
  Function : Send a message through the stream s 	
  
  Input    : Socket stream s, number of objects to send

  Return   : 0 if no error else -1
  ***********************************************************************/

#undef _DEBUG

bool sendMessage(int inSocket,
		 string inString,
		 ostream& outLogFile);

/***********************************************************************
  ReadMessage								
  
  Function : read the message coming from the Java Applet using the 
  communication protocol	
  
  Input    : Socket stream s  
			     			
  Return   : 0 if no error else -1
  ***********************************************************************/
bool asyncReadChar(int inSocket,char* outChar);


int readMessage(int inSocket,
		string& outMessage);


#define WITH_GENERATE_DISTANCE_MATRIX
#ifdef WITH_GENERATE_DISTANCE_MATRIX

void generateDistanceMatrix(const string& inBaseDir,
			    const string& inOutputName,
			    const string& inAlgorithm,
			    const string& inCollection,
			    int inSkip,
			    int inTo){
  cout << "Starting generateDistanceMatrix " << inAlgorithm << inCollection << inSkip << inTo << endl;
  map<string,int> lURLToPosition;

  string lOutputName=inOutputName
    +string(".Algorithm")
    +inAlgorithm
    +string(".Collection")
    +inCollection
    +".bin";
    

  CSessionManager lSessionManager(inBaseDir+"/gift-sessions.mrml",
				  inBaseDir+"/gift-config.mrml",
				  inBaseDir+"/gift-i18n.xml"
				  );
  cout << "hier 0" << endl;
  // open a session
  string lSessionID(lSessionManager.newSession("DistanceMatrixMaker",""));
  cout << "hier 1" << endl;
  // configure the session
  CAlgorithm* lConfig(new CAlgorithm("adefault",
				     0));
  assert(lConfig);
  lConfig->addAttribute(mrml_const::algorithm_id,
			inAlgorithm);
  lConfig->addAttribute(mrml_const::algorithm_type,
			inAlgorithm);
  lConfig->addAttribute(mrml_const::collection_id,
			inCollection);
  cout << "hier 1" << endl;
  lSessionManager.setAlgorithm(lSessionID,
			       lConfig);
  cout << "hier 2" << endl;

  // fstream::in+fstream::out would cast to int IMPLICITLY
  fstream lMatrix(lOutputName.c_str(),
		  fstream::in|fstream::out);

  cout << "----------------------------------------"
       << endl
       << "I am generating a distance matrix"
       << endl
       << "Using the algorithm:  " << inAlgorithm
       << endl
       << "Using the collection: " << inCollection << ","
       << endl
       << "I am skipping the first " << inSkip << " lines."
       << endl
       << "I am ending before the  " << inTo << "th  line"
       << endl
       << "----------------------------------------"
       << endl;

  cout << "----------------------------------------"
       << endl
       << "Getting a list of all IDs in the collection"
       << endl
       << "SessionID: " << lSessionID
       << endl
       << "AlgorithmID: " << inAlgorithm
       << endl
       << "CollectionID: " << inCollection
       << endl;


  /*
    Get an accessor. We need this for getting at a list
    of all the images. Mabe we do this later using 
    a meta data query and coming from the outside.
  */

  CAccessorAdminCollection lAccessorAdminCollection(inBaseDir+"/gift-config.mrml");
  CAccessorAdmin& lProxy(lAccessorAdminCollection.getProxy(inCollection));
  assert(&lProxy);
  CAcURL2FTS* lAccessor=(CAcURL2FTS*)lProxy.openAccessor("url2fts");
  assert(lAccessor);
  list<CAccessorElement> lAccessorElements; 
  lAccessor->getAllAccessorElements(lAccessorElements);
  
  if(lAccessorElements.size()){
    
    //for guaranteeing a sequence of rising IDs (probably obsolete)
    lAccessorElements.sort(CSortByID_CAE());
    
    int lSize=lAccessorElements.size();
    
    
    
    //write the translator if nothing to be skipped
    {
      ofstream lTranslator(string(lOutputName+".trans").c_str());
      int lLine=0;
      for(list<CAccessorElement>::const_iterator i=lAccessorElements.begin();
	  i!=lAccessorElements.end();
	  i++){
	lTranslator << i->getID()
		    << " "
		    << lLine
		    << endl;
	lURLToPosition[i->getURL()]=lLine;
	lLine++;
      }
      inTo-=inSkip;
    }
    
    
    
    
    //skip the beginning
    {
      for(int i=0;
	  i<inSkip;
	  i++){
	lAccessorElements.pop_front();
      }
    }
    
    //skip the beginning also in the matrix
    lMatrix.seekp(lSize * inSkip * sizeof(float));
    
    
    int lCount=0;
    for(list<CAccessorElement>::const_iterator i=lAccessorElements.begin();
	i!=lAccessorElements.end() && lCount<inTo;
	i++,lCount++){

      
      cout    << "----------------------------------------"
	      << endl
	      << "querying for: " 
	      << i->getID()
	      << ": "
	      << i->getURL()
	      << endl;
      
      CXMLElement lQuery(mrml_const::query_step,0);
      lQuery.addAttribute(mrml_const::algorithm_id,
			  inAlgorithm);
      lQuery.addAttribute(mrml_const::result_size,
			  long(0x7fffffff));//simply get everything
      lQuery.addAttribute(mrml_const::result_cutoff,
			  0.0);//and do not cut anything off
      
      CXMLElement* lUserRelevanceList=new CXMLElement(mrml_const::user_relevance_element_list,
						      0);
      assert(lUserRelevanceList);
      
      CXMLElement* lUserRelevanceElement=new CXMLElement(mrml_const::user_relevance_element,
							 0);
      lUserRelevanceElement->addAttribute(mrml_const::user_relevance,
					  1.0);
      lUserRelevanceElement->addAttribute(mrml_const::image_location,
					  i->getURL());

      lQuery.addChild(lUserRelevanceList);
      lQuery.addChild(lUserRelevanceElement);
      lQuery.moveUp();
      lQuery.moveUp();
      
      string lXML;

      lQuery.toXML(lXML);
      
      cout << "XML:" 
	   << lXML
	   << endl
	   << "----------------------------------------"
	   << endl;
      
      CXMLElement* lResult=lSessionManager
	.query(lSessionID,
	       lQuery);
      
      {
	  string lString;
	  lResult->toXML(lString);
	  cout << lString 
	       << endl;
      }

      float lOutVector[lSize];
      {//fill lOutVecor with zeroes
	for(float* p=lOutVector;
	    p!=lOutVector+lSize;
	    *(p++)=0){}
      }
      
      float lZero=0.0;
      int lLastPosition=0;
      
      for(CXMLElement::lCChildren::iterator k=lResult->child_list_begin();
       	  k!=lResult->child_list_end();
       	  k++){
	      for(CXMLElement::lCChildren::iterator j=(*k)->child_list_begin();
		  j!=(*k)->child_list_end();
		  j++){
		  string lURL=(*j)->stringReadAttribute(mrml_const::image_location).second;
		  double lRelevanceLevel=(*j)->doubleReadAttribute(mrml_const::calculated_similarity).second;
		  
		  lOutVector[lURLToPosition[lURL]]=lRelevanceLevel;
		  
		  cout << endl << "[" << lURLToPosition[lURL] << "__" << lRelevanceLevel << "]" << flush;
	      }
      }
      
      lMatrix.write((char*)lOutVector,sizeof(float)*lSize);
      lMatrix << flush;
      delete lResult;
      
      cout << endl
	   << "----------------------------------------"
	   << "Writing " << sizeof(float)*lSize << " Bytes" << endl

	   << "Still to go:" << inTo-lCount-1 << " lines."
	   << endl
	   << "----------------------------------------"
	   << endl;

    }
    lMatrix.close();
  }else{

  }
}
#endif


 
#include "CMultiServer.h"
#include "CTCPSocket.h"

class CSFGift:public CSocket::CServeFunction{
  /** */
  ofstream& mLogFile;
  /** */
  CSessionManager& mSessionManager;
public:
  /** */
  CSFGift(CSessionManager& inSessionManager,
	  ofstream& inLogFile):
    mSessionManager(inSessionManager),
    mLogFile(inLogFile){
  };
  /** */  
  bool operator()(int inSocketDescriptor){
    cout << "Accepted Connection!" << endl << flush;

    
    string lAddress;
    {
      struct sockaddr  lName;
      socklen_t lNameLen(sizeof(lName));
      if(!getpeername(inSocketDescriptor, 
		      &lName, 
		      &lNameLen)){
	lAddress="Peer INET Address: " + string(inet_ntoa(((sockaddr_in*)(&lName))->sin_addr));
	cout << "Accepted from address [" << lAddress << "]" << endl;
      } 
    }

    CProcessMessageParameters* 
      lProcessMessageParameters(new 
				CProcessMessageParameters(mSessionManager,
							  lAddress,
							  mLogFile,
							  inSocketDescriptor));
#ifdef  __GIFT_USES_THREADS__
#warning "threading used"
    pthread_t lThread;
    int lErrorNumber(0);
    if(lErrorNumber=pthread_create(&lThread, NULL, &processMessage,lProcessMessageParameters)){
      cerr << "Error in creating new thread: "
	   << strerror(lErrorNumber) << endl
	   << "Doing normal function call instead"
	   << endl;
      processMessage(lProcessMessageParameters);
    }else{
      cout << "Successfully created new message processing thread"
	   << endl;
      if(lErrorNumber=pthread_detach(lThread)){
	cerr << "Error in detaching thread: "
	     << strerror(lErrorNumber) << endl;
      }else{
	cout << "Successfully detached thread"
	     << endl;
      }
    }
#else
#warning "threading blocked"
    cout << "calling processMessage (no thread)" << endl;
    processMessage(lProcessMessageParameters);
    cout << "returned processMessage (no thread)" << endl;
#endif
  }
};


static void displayHelp()
{
  cout << PACKAGE << "-" << VERSION << endl
       << "Usage (server):              gift [--port <Port>] [--datadir <Configuration-Directory>] [--no-random-seed]" << endl;
#ifdef WITH_GENERATE_DISTANCE_MATRIX
  cout << "making distance matrices:    gift --generate-matrix [--datadir <Configuration-Directory>] <Algorithm> <Collection> <from> <to>" << endl;
#endif
  cout << endl << endl;
}

/***********************************************************************
  main								
  
  Function : waits for and accepts a connection from a Java Applet. 
  Receives the request from the client and according the 
  request, sends the answer to the client.	

  Socket opening code snipped from J.Raki

  ***********************************************************************/	       
int main(int argc, char **argv){
  gMutex=0;
  gMutex=new CMutex();

  gGIFTHome=string(getenv("GIFT_HOME")?getenv("GIFT_HOME"):getenv("HOME")?getenv("HOME"):".");

  static struct option long_options[] = 
  {
    {"port", 	       required_argument, 0, 'p'},
    {"datadir",        required_argument, 0, 'd'},
    {"help",           no_argument,       0, 'h'},
    {"no-random-seed", no_argument,       0, 'r'},
#ifdef WITH_GENERATE_DISTANCE_MATRIX
    {"generate-matrix",no_argument,       0, 'g'},
#endif
    { 0,               0,                 0,  0 }
  };

  bool doRandom = true;
  bool generateMatrix = false;

  while ( 1 ) {
    int c = getopt_long( argc, argv, "p:d:rgh", long_options, NULL );
    if ( c == -1 )
      break;

    switch ( c ) {
     case 'd':
        gGIFTHome = string(optarg) + string("/");
        break;

      case 'p':
        PORT=atoi(optarg);
        break;

      case 'r':
        doRandom = false;
        break;

       case 'g':
        generateMatrix = true;
        break;
 
     case 'h':
        displayHelp();
        ::exit(0);

      case '?':
      default:
        break;
  }
  }

  if(!generateMatrix){
    cout << "GIFT:Starting Server" << endl;
  }else{
    cout << "GIFT:Generating distance matrix" << endl;
  }

  int idx = optind;
  if ( !generateMatrix ) {
    if ( idx < argc ) // more arguments -> backwards compat
      PORT = atoi(argv[idx++]);
    if ( idx < argc )
      gGIFTHome = string(argv[idx++]) + string("/");
  }


  if ( doRandom ) {
    cerr << "Random number generator has been seeded with " 
	 << getpid() << endl;
    srand(getpid());
  } else {
    cerr << "Warning: the random generator stays unseeded" << endl;
  }

  ofstream lPortFile;
  {
    string lPortFileName=gGIFTHome+"/gift-port.txt";
    lPortFile.open(lPortFileName.c_str());
    assert(lPortFile);
  }

  // the communication handler for this application
  // class definition is just above in this file
  CSessionManager gSessionManager(gGIFTHome+"/gift-sessions.mrml",
				  gGIFTHome+"/gift-config.mrml",
				  gGIFTHome+"/gift-i18n.xml"
				  );
  ofstream gLogFile(string(gGIFTHome+"/gift-log.mrml").c_str(),
		    ios::app);

  {
    time_t lNow(time(0));
    gLogFile << endl
	     << "<!-- This instance of the GIFT was started on -->" << endl
	     << "<!-- " <<  string(ctime(&lNow)) << " -->" << endl
	     << "<!-- PID " << long(getpid()) << " -->" << endl
	     << endl;
  }
  
#ifdef WITH_GENERATE_DISTANCE_MATRIX
  if( generateMatrix ){
    if ( idx + 4 != argc ) {
      cerr << endl << "Wrong number of parameters for generating the distance matrix." << endl;
      displayHelp();
      ::exit(1);
    }

    //exit(0);
    generateDistanceMatrix(gGIFTHome,
			   string("DistanceMatrix"),
			   string(argv[idx]),
			   string(argv[idx + 1]),
			   atoi(argv[idx + 2]),
			   atoi(argv[idx + 3]));
    exit(0);
  }
#endif

  cout << "----------------------------------------"
       << endl
       << "The current configuration directory is: "
       << gGIFTHome
       << endl;

  cout << "----------------------------------------"
       << endl
       << "Opening port " << PORT
       << endl
       << "----------------------------------------"
       << endl;


  try{
    CMultiServer lServer;
    CTCPSocket lSocket1("",PORT);
    CTCPSocket lSocket2("",PORT+1);

    // write out the ports
    lPortFile << PORT << endl;
    lPortFile << PORT+1 << endl;
    lPortFile.close();
    // close that file

    CSFGift    lServeFunction(gSessionManager,gLogFile);
    lSocket1.setServeFunction((&lServeFunction));
    lSocket2.setServeFunction((&lServeFunction));
    lServer.addSocket(&lSocket1);
    lServer.addSocket(&lSocket2);
    lServer.serve();
  }
  catch(GIFTException& inCaught){
    cout << "Caught inServer Main:"
	 << inCaught
	 << endl
	 << flush;
  }
  catch(GIFTException* inCaught){
    cout << "Caught inServer Main:"
	 << *inCaught
	 << endl
	 << flush;
  }
  catch(exception& inCaught){
    cout << "Caught inServer Main:"
	 << inCaught.what()
	 << endl
	 << flush;
  }
  catch(...){
    cout << "there was an unknown exception" <<endl
	 << flush;
  }
  //return 0;
  delete gMutex;
  return 0;
}