File: nws_memory.c

package info (click to toggle)
nws 2.11-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,700 kB
  • ctags: 2,820
  • sloc: ansic: 28,849; sh: 3,289; java: 1,205; makefile: 697; perl: 12
file content (1324 lines) | stat: -rw-r--r-- 34,029 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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
/* $Id: nws_memory.c,v 1.176 2004/11/05 21:40:02 graziano Exp $ */

#include "config_nws.h"

#include <errno.h>           /* errno */
#include <stdio.h>           /* sprintf() */
#include <unistd.h>          /* getopt() stat() */
#include <stdlib.h>
#include <string.h>          /* strchr() strstr() */

#include "protocol.h"
#include "nws_state.h"
#include "host_protocol.h"
#include "diagnostic.h"
#include "strutil.h"
#include "dnsutil.h"
#include "osutil.h"
#include "messages.h"
#include "nws_memory.h"
#include "skills.h"
#include "nws_db.h"

/*
 * This program implements the NWS memory host.  See nws_memory.h for supported
 * messages.
 */

#define KEEP_A_LONG_TIME 315360000.0

/* we keep a list of series we know about, so that we can register them
 * with the nameserver. We have 2: one for the orphaned series and one
 * for the registered series: the orphaned will disappears when the new
 * series kicks in. */
static registrations *mySeries;		/* where we keep series registrations */
static registrations *orphanedSeries;	/* where we keep series registrations */

/* performance data */
static double fetchTime;		/* time spent serving FETCH */
static double oldStoreTime;		/* time spent serving STORE */
static double storeTime;		/* time spent serving the new STORE */
static double autoFetchTime;		/* time spent serving autofetching */
static unsigned long fetchQuery;
static unsigned long oldStoreQuery;
static unsigned long storeQuery;

/*
 * Information about a registered auto-fetch request. The list of series
 * the client is interested in and the socket is kept here.
 */
typedef struct {
	registrations *reg;
	Socket clientSock;
} AutoFetchInfo;


/*
 * Module globals.  #autoFetches# is the list of registered auto-fetch requests
 * that we're still servicing; #autoFetchCount# is the length of this list.
 * #fileSize# contains the maximum number of records allowed in files.
 */
AutoFetchInfo *autoFetches = NULL;
static size_t autoFetchCount = 0;
static size_t fileSize;

/* select which backend to use to store data: so far localdir is the most
 * stable and tested one. */
typedef enum {LOCALDIR, NETLOGGER, POSTGRES} memType;
static memType backType = LOCALDIR;

/*
 * Called when an operation fails.  Cleans up any bad connections and, if we've
 * run out, frees up a connection so that others may connect.
 */
static void
CheckConnections(void) {
	if(CloseDisconnections() == 0) {
		CloseConnections(0, 1, 1);
	}
}

/*
 * this function goes through a string which contains states separated
 * by '\n' and check if they are valid registrations. It starts from the
 * end of the string, check if the name is in #good# (the good list of
 * registrations) otherwise it adds to #orphan#. Checks only #howMany#
 * entries at a time. Returns 1 if more entries need to be processed.
 */
static int
CheckOldNames(	char *names,
		registrations *good,
		registrations *orphan,
		int howMany) {
	char *where, *tmp;
	Object obj;
	int nskill, i, k, done;
	MeasuredResources m;
	KnownSkills t;

	/* sanity check */
	if (orphan == NULL || good == NULL) {
		ERROR("CheckOldNames: NULL parameter\n");
		return 0;
	}
	if (howMany < 0) {
		howMany = 10;
	}
	if (names == NULL) {
		/* we are done */
		return 0;
	}

	for (where = names + strlen(names); where > names; *(--where) = '\0') {
		/* look for the beginning of the filename */
		while (*where != '\n' && where > names) {
			where--;
		}
		where++;

		/* let's check if we have just a newline */
		if (strlen(where) <= 0) {
			continue;
		}

		/* let's check the filename/table */
		switch (backType) {
		case LOCALDIR:
			if (!CheckFileName(where)) {
				INFO1("CheckOldNames: %s is not a valid NWS filename\n", where);
				continue;
			}
			break;

		case POSTGRES:
			if (!CheckTable(where)) {
				INFO1("CheckOldNames: %s is not a valid NWS table\n", where);
				continue;
			}
			break;
		
		case NETLOGGER:
			INFO("CheckOldNames: not implemented for netlogger\n");
			return 0;
			break;
		}

		/* if the series is already registered in the good lists,
		 * we skip it */
		if (SearchForName(good, where, 1, &i)) {
			continue;
		}

		/* if we already have it in the orphaned series we skip: 
		 * we need it anyway to find where to insert the object */
		if (SearchForName(orphan, where, 1, &i)) {
			continue;
		}

		/* we need to insert it: let's create the object first
		 * then add it */
		obj = NewObject();
		AddNwsAttribute(&obj, "name", where);
		AddNwsAttribute(&obj, "memory", EstablishedRegistration());
		AddNwsAttribute(&obj, "objectclass", "nwsSeries");

		/* let's find which resource we are dealing with */
		for (m = 0; m < RESOURCE_COUNT; m++) {
			if (strstr(where, ResourceName(m)) != NULL) {
				break;
			}
		}
		if (m >= RESOURCE_COUNT) {
			INFO1("CheckOldNames: unknown resource in %s\n", where);
			continue;
		}

		/* now, we are checking if the resource as a target
		 * options: if so the target is at the end of the name,
		 * after the options. This is from Ye  code. Thanks Ye! */ 
		/* to do that let's find the skill responsible for the
		 * resource */
		done = 0;
		for (t = 0; t < SKILL_COUNT; t++) {
			const MeasuredResources *resources;

			if (!SkillResources(t, &resources, &nskill)) {
				INFO("CheckOldNames: failed to get info on skill\n");
				continue;
			}
			for (k = 0; k < nskill; k++) {
				if (resources[k] == m) {
					/* we found the right skill:
					 * let's get out of here */
					done = 1;
					break;
				}
			}
			if (done) {
				break;
			}
		}

		/* if we didn't find the skill, it's a very bad news. */
		if (t >= SKILL_COUNT) {
			WARN1("CheckOldNames: unable to find skill for resource %s\n", ResourceName(m));
			continue;
		}

		/* now let's look if we have a target option: clique
		 * control adds it. */
		if (SkillAvailableForControl(t, "", CLIQUE_CONTROL)) {
			const char *options;
			options = SkillSupportedOptions(t);
			if (options == NULL) {
				/* I guess we don't have the target */
				continue;
			}
			/* let's count how many options we have (the are
			 * comma separated so there are 1 + # of commas) */
			for (done = 1; *options != '\0'; options++) {
				if (*options == ',') {
					done++;
				}
			}

			/* now let's get the target: it is done commas
			 * away from the resource name */
			tmp = strstr(where, ResourceName(m));
			/* we have an extra '.' (the one after
			 * the resource name */
			for (done++; *tmp != '\0'; tmp++) {
				if (*tmp == '.') {
					done--;
				}
				if (done == 0) {
					/* we got it: let's pass the dot */
					tmp++;
					AddNwsAttribute(&obj, "target", tmp);
					break;
				}
			}
		}
		
		/* now let's add the resource and the host */
		AddNwsAttribute(&obj, "resource", ResourceName(m));

		/* if we have the resource we can take an educate
		 * guess on what the host is */
		tmp = strstr(where, ResourceName(m));
		if (tmp != NULL) {
			tmp--;
			if (*tmp == '.') {
				*tmp = '\0';
				AddNwsAttribute(&obj, "host", where);
			}
		}

		InsertRegistration(orphan, obj, 10, i);
		FreeObject(&obj);

		/* done with this name */
		*where = '\0';

		if (--howMany <= 0) {
			/* done for this round */
			break;
		}
	}

	return (howMany <= 0);
}


/* 
 * this function looks for series that needs to be registered (expiration
 * will tell) with the nameserver. We register only #hoeMany# of them at a
 * time. Returns 1 if more registration work needs to be done.
 */
static int
RegisterSeries(	registrations *r, 
		int howMany) {
	int i, j;
	unsigned long now;
	
	/* sanity check */
	if (r->howMany <= 0) {
		return 0;
	}

	now = (unsigned long)CurrentTime();

	for (i = 0, j = 0; j < r->howMany; j++) {
		if (r->expirations[j] < now) {
			/* need to be registered */
			if (RegisterWithNameServer(r->vals[j], DEFAULT_HOST_BEAT * 10)) {
				r->expirations[j] = now + DEFAULT_HOST_BEAT * 5;
				/* we register only howMany series at a time */
				if (i++ >= howMany) 
					break;
			}
		}
	}

	return  (j < r->howMany);
}

/* 
 * This is somewhat hopeless, but we tried to unregister all the series!!
 */
static void
UnregisterSeries(	registrations *r) {
	int j;
	char *name, filter[255];
	const char *myName;
	
	myName = EstablishedRegistration();
	for (j = 0; j < r->howMany; j++) {
		/* let's get the name and unregister the beast */
		name = NwsAttributeValue_r(FindNwsAttribute(r->vals[j], "name"));
		if (name == NULL) {
			WARN("UnregisterSeries: object with no name??\n");
			continue;
		}
		snprintf(filter, 255, "%s)(memory=%s", name, myName);
		FREE(name);

		UnregisterObject(filter);
	}

	return;
}
/* todo list when we exit */
static int
MyExit(void) {
	LOG("MyExit: unregistering series, it may take sometime!\n");
	UnregisterSeries(mySeries);

	return 1;
}


/*
 * this functions gets a #registration# of a Series in input and looks for
 * it in the lists of Series names. If not found it adds it. 
 */
static int
StoreSeriesName(char *registration) {
	int ind;
	Object obj;
	char *name;

	/* sanity check */
	if (registration == NULL) {
		ERROR("StoreSeriesName: NULL registration\n");
		return 0;
	}

	/* we'll need the name later */
	name = NwsAttributeValue_r(FindNwsAttribute(registration, "name"));
	if (name == NULL) {
		ERROR1("StoreSeriesName: object without a name (%s)!\n", registration);
		return 0;
	}

	/* before doing anything else, let's set straight who is the
	 * memory here */
	obj = strdup(registration);
	DeleteNwsAttribute(&obj, "memory");
	AddNwsAttribute(&obj, "memory", EstablishedRegistration());

	/* we need to see if there is similar registration in the
	 * orphaned list: if so remove it and add it to the good list */
	if (SearchForName(orphanedSeries, name, 1, &ind)) {
		/* we found it: remove it from orphaned ... */
		DeleteRegistration(orphanedSeries, ind);
		/* .. and from the nameserver */
		UnregisterObject(name);
	}
	FREE(name);

	/* let's look for the registration in the good list */
	if (!SearchForObject(mySeries, obj, &ind)) {
		/* expiration is bogus so that we'll register the series
		 * right away */
		InsertRegistration(mySeries, obj, 10, ind);
	}
	FREE(obj);

	return 1;
}

/*
 * A "local" function of ProcessRequest().  Implements the MEMORY_CLEAN service
 * by deleting all files in the memory directory that have not been accessed
 * within the past #idle# seconds.  Returns 1 if successful, else 0.
 */
static int
DoClean(unsigned long idle) {
	int ret;

	switch (backType) {
	case LOCALDIR:
		ret = CleanLocalStates(idle);
		break;

	case POSTGRES:
		INFO("DoClean: no cleaning implemented when using database\n");
		ret = 0;
		break;
	
	case NETLOGGER:
		INFO("DoClean: no cleaning implemented when using netlooger\n");
		ret = 0;
		break;
	}

	return ret;
}


/*
 * Removes from the #auotFetchInfo# module variable all information for the
 * client connected to #sock#.
 */
static void
EndAutoFetch(Socket sock) {
	int i;

	/* sanity check */
	if (sock == NO_SOCKET) {
		return;
	}

	for(i = 0; i < autoFetchCount; i++) {
		if(autoFetches[i].clientSock == sock) {
			/* feedback */
			INFO1("EndAutoFetch: cleaning after socket %d\n", sock);

			/* remove all the registrations */
			while(autoFetches[i].reg->howMany > 0) {
				DeleteRegistration(autoFetches[i].reg, 0);
			}
			autoFetches[i].clientSock = NO_SOCKET;
		}
	}
}

/* Used in ProcessRequest to store the data.
 * Stores #data# in #directory# with the attributes indicated by #s#.
 * Fails if the record size and count in #s# yield more than #len#
 * total bytes.  Returns 1 if successful, else 0.
 */
static int
KeepState(	const struct nws_memory_state *s,
		const char *data,
		size_t len) {
	const char *curr;
	int i, ret;
	size_t recordSize;

	/* sanity check */
	if (s == NULL || data == NULL) {
		ERROR("KeepState: NULL parameter\n");
		return 0;
	}
	if(s->rec_count > fileSize) {
		FAIL("KeepState: rec count too big\n");
	}
	if(s->rec_size > MAX_RECORD_SIZE) {
		WARN("KeepState: state record too big.\n");
		recordSize = MAX_RECORD_SIZE;
	} else {
		recordSize = (size_t)s->rec_size;
	}
	if(s->rec_count * recordSize > len) {
		FAIL1("KeepState: too much data %d\n", s->rec_count * recordSize);
	}

	/* all right, we are clear to store the data */
	ret = 1;
	for(curr = data, i = 0; i < s->rec_count; curr += recordSize, i++) {
		switch (backType) {
		case LOCALDIR:
			ret = WriteState(s->id,
					fileSize,
					s->time_out,
					s->seq_no,
					curr,
					recordSize);
			if (!ret) {
				/* as of 2.8.2 we disabled the journal */
				/*|| !EnterInJournal(s->id, s->seq_no)) */
				if(errno == EMFILE) {
					CheckConnections();
				}
			}
			break;

		case POSTGRES:
			/* let's go to the database */
			ret = WriteNwsDB(s->id, 
					s->time_out, 
					s->seq_no, 
					curr, 
					recordSize);
			break;

		case NETLOGGER:
#ifdef WITH_NETLOGGER
			ret = WriteStateNL(logLoc->path,
					s->id,
					fileSize,
					s->time_out,
					s->seq_no,
					curr,
					recordSize);
#endif
			break;
		}
		/* let's see how did it go */
		if (ret == 0) {
			ERROR("KeepState: write failed\n");
			break;
		}
	}

	return ret;
}


static void
NotifyFetchers(	const struct nws_memory_state *s,
		const char *data,
		size_t len) {
	DataDescriptor contentsDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
	int i, j;
	Socket sock;

	/* set the size of the experiments string to be sent */
	contentsDescriptor.repetitions = len;

	/* forward to the autofetch clients */
	for (i = 0; i < autoFetchCount; i++) {
		if (autoFetches[i].clientSock == NO_SOCKET) {
			/* empty slot */
			continue;
		}

		if (SearchForName(autoFetches[i].reg, s->id, 1, &j)) {
			if (!SendMessageAndDatas(autoFetches[i].clientSock, STATE_FETCHED, s, stateDescriptor, stateDescriptorLength, data, &contentsDescriptor, 1, -1)) {
				/* some feedback */
				LOG1("NotifyFetchers: failed for socket %d\n", autoFetches[i].clientSock);
	
				/* now let's remove traces for this guy */
				sock = autoFetches[i].clientSock;
				EndAutoFetch(autoFetches[i].clientSock);
				DROP_SOCKET(&sock);
			}
		}
	}
}

static int
AddAutoFetcher(	Socket *sd,
		char *stateNames) {
	int i, ret, j;
	const char *word;
	char name[255 + 1];
	AutoFetchInfo *expandedAutoFetches;
	Object obj;

	/* sanity check */
	if (*sd == NO_SOCKET || stateNames == NULL) {
		WARN("AddAutoFetcher: NULL parameter(s)\n");
		return 0;
	}

	/* we have a new list of series to autoFetch: is
	 * this an old client? */
	for(j = -1, i = 0; i < autoFetchCount; i++) {
		if (autoFetches[i].clientSock == NO_SOCKET && j == -1) {
			/* remember empty slot */
			j = i;
		}
		if (autoFetches[i].clientSock == *sd) {
			/* old client: remove the old list */
			EndAutoFetch(*sd);
		}
	}

	/* let's make room for the new autofetcher */
	if (j == -1) {
		expandedAutoFetches = REALLOC(autoFetches, (i+1)*sizeof(AutoFetchInfo));
		if (expandedAutoFetches == NULL) {
			ERROR("AddAutoFetcher: out of memory\n");
			return 0;
		}
		autoFetchCount++;
		autoFetches = expandedAutoFetches;
		j = i;

		/* let's set the new registrations */
		if (!InitRegistrations(&autoFetches[j].reg)) {
			ERROR("AddAutoFetcher: failed to init structure\n");
			EndAutoFetch(*sd);
			return 0;
		}
	}
	autoFetches[j].clientSock = *sd;

	/* let's get the registrations one by one */
	for (word = stateNames; GETWORD(name, word, &word); ) {
		/* let's get the right spot top add it */
		if (SearchForName(autoFetches[j].reg, name, 1, &ret)) {
			/* we already have it */
			LOG1("AddAutoFetcher: duplicate series (%s)\n", name);
			continue;
		}
					
		/* set the object */
		obj = NewObject();
		AddNwsAttribute(&obj, "name", name);

		if (!InsertRegistration(autoFetches[j].reg,
				obj,
				0,
				ret)) {
			ABORT("AddAutoFetcher: failed to insert series!\n");
		}
		FreeObject(&obj);
	}

	INFO1("AddAutoFetcher: we have %d autofetchers\n", autoFetchCount);

	return 1;
}


/* wrap around the reading functions */
static int
ReadRecord(	char *where,
		int maxSize,
		struct nws_memory_state *stateDesc) {
	int ret = 0;

	/* let's see which backend are we using */
	switch (backType) {
	case LOCALDIR:
		ret = ReadState(	stateDesc->id,
					where,
					stateDesc->rec_count,
					stateDesc->rec_count * maxSize,
					stateDesc->seq_no,
					&stateDesc->time_out,
					&stateDesc->seq_no,
					&stateDesc->rec_count,
					&stateDesc->rec_size);
		break;

	case POSTGRES:
		ret = ReadNwsDB(	stateDesc->id,
					where,
					stateDesc->rec_count,
					stateDesc->rec_count * maxSize,
					stateDesc->seq_no,
					&stateDesc->time_out,
					&stateDesc->seq_no,
					&stateDesc->rec_count,
					&stateDesc->rec_size);
		break;

	case NETLOGGER:
		ERROR("HELP!\n");
		break;
	}

	return ret;
}


/*
 * A "local" function of main().  Handles a #header#.message message arrived on
 * #sd# accompanied by #header#.dataSize bytes of data.
 */
static void
ProcessRequest(	Socket *sd,
		MessageHeader header) {
	char *contents;
	unsigned long expiration;
	DataDescriptor contentsDes = SIMPLE_DATA(CHAR_TYPE, 0);
	DataDescriptor expDescriptor = SIMPLE_DATA(UNSIGNED_LONG_TYPE, 1);
	DataDescriptor stateNamesDescriptor = SIMPLE_DATA(CHAR_TYPE, 0);
	int i, ret;
	struct nws_memory_state stateDesc;
	struct nws_memory_new_state newStateDesc;
	char *stateNames, *tmp;

	/* makes the compiler happy */
	contents = NULL;

	switch(header.message) {
	case FETCH_STATE:
		/* got an extra query */
		fetchQuery++;
		fetchTime -= MicroTime();

		if(!RecvData(*sd, &stateDesc, stateDescriptor, stateDescriptorLength, -1)) {
			DROP_SOCKET(sd);
			ERROR("ProcessRequest: state receive failed\n");
		} else {
			/* we are cool */
			contents = (char *)MALLOC(stateDesc.rec_count * MAX_RECORD_SIZE);
			if(contents == NULL) {
				(void)SendMessage(*sd, MEMORY_FAILED, -1);
				ERROR("ProcessRequest: out of memory\n");
			} else {
				if(ReadRecord( contents,
						MAX_RECORD_SIZE,
						&stateDesc)) {
					if(stateDesc.rec_count > 0) {
						contentsDes.repetitions = stateDesc.rec_size * stateDesc.rec_count;
						(void)SendMessageAndDatas(*sd,
							STATE_FETCHED,
							&stateDesc,
							stateDescriptor,
							stateDescriptorLength,
							contents,
							&contentsDes,
							1,
							-1);
					} else {
						(void)SendMessageAndData(*sd,
							STATE_FETCHED,
							&stateDesc,
							stateDescriptor,
							stateDescriptorLength,
							-1);
					}
				} else {
					INFO1("ProcessRequest: couldn't read state %s\n", stateDesc.id);
					(void)SendMessage(*sd, MEMORY_FAILED, -1);
					if(errno == EMFILE) {
						CheckConnections();
					}
				}
				free(contents);
			}
		}

		fetchTime += MicroTime();	/* stop the timer */
		break;

	case STORE_STATE:
		/* we got an old store request */
		oldStoreQuery++;
		oldStoreTime -= MicroTime();

		ret = 0;

		if(!RecvData(*sd,
				&stateDesc,
				stateDescriptor,
				stateDescriptorLength,
				-1)) {
			DROP_SOCKET(sd);
			ERROR("ProcessRequest: state receive failed\n");
		} else {
			/* we are cool */
			contentsDes.repetitions = stateDesc.rec_size * stateDesc.rec_count;
			contents = (char *)MALLOC(contentsDes.repetitions + 1);
			if(contents == NULL) {
				(void)SendMessage(*sd, MEMORY_FAILED, -1);
				ERROR("ProcessRequest: out of memory\n");
				break;
			}
			if(!RecvData(*sd, contents, &contentsDes, 1, -1)) {
				DROP_SOCKET(sd);
				ERROR("ProcessRequest: data receive failed\n");
				break;
			}
			contents[contentsDes.repetitions] = '\0';
	
			/* let's try to save the received experiment */
			ret = KeepState(&stateDesc, contents, contentsDes.repetitions);
			if (ret) {
				(void)SendMessage(*sd, STATE_STORED, -1);
			} else {
				(void)SendMessage(*sd, MEMORY_FAILED, -1);
			}
		}
		oldStoreTime += MicroTime();	/* stop the timer */

		/* notify the auto fetchters */
		autoFetchTime -= MicroTime();
		if (ret) {
			NotifyFetchers(	&stateDesc, 
					contents, 
					contentsDes.repetitions);
		}
		autoFetchTime += MicroTime();

		FREE(contents);
		break;

	/* new message since 2.9: we receive the full registration piggy
	 * backed into the packed experiment */
	case STORE_AND_REGISTER:
		/* we got a new query */
		storeQuery++;
		storeTime -= MicroTime();

		ret = 0;

		if(!RecvData(		*sd, 
					&newStateDesc,
					newStateDescriptor,
					newStateDescriptorLength,
					-1)) {
			DROP_SOCKET(sd);
			ERROR("ProcessRequest: new state receive failed\n");
			return;
		} else {
			/* we are cool */
			contentsDes.repetitions = newStateDesc.rec_size * newStateDesc.rec_count + newStateDesc.id_len;
			contents = (char *)MALLOC(contentsDes.repetitions + 1);
			tmp = (char *)MALLOC(newStateDesc.id_len + 1);
			if(contents == NULL || tmp == NULL) {
				(void)SendMessage(*sd, MEMORY_FAILED, -1);
				ERROR("ProcessRequest: out of memory\n");
				break;
			}
			if(!RecvData(*sd, contents, &contentsDes, 1, -1)) {
				FREE(contents);
				FREE(tmp);
				DROP_SOCKET(sd);
				ERROR("ProcessRequest: data receive failed\n");
				break;
			}
			contents[contentsDes.repetitions] = '\0';

			/* let's try to save the received experiment */
			/* now is a trick: KeepState expects a stateDesc not a
			 * newStateDesc, so we just do it */
			stateDesc.rec_size = newStateDesc.rec_size;
			stateDesc.rec_count = newStateDesc.rec_count;
			stateDesc.seq_no = newStateDesc.seq_no;
			stateDesc.time_out = newStateDesc.time_out;

			/* let's extract the registration now: it's at the
			 * beginning of the content */
			memcpy(tmp, contents, newStateDesc.id_len);
			tmp[newStateDesc.id_len] = '\0';
	
			/* here only the name is needed */
			stateNames = NwsAttributeValue_r(FindNwsAttribute(tmp, "name"));
			if (stateNames == NULL) {
				ERROR("ProcessRequest: series without a name?!\n");
				DROP_SOCKET(sd);
				FREE(tmp);
				FREE(contents);
				break;
			}
			SAFESTRCPY(stateDesc.id, stateNames);
			FREE(stateNames);

			/* let's see how big is the record to be registered */
			i = strlen(contents + newStateDesc.id_len);
			ret = KeepState(&stateDesc, contents + newStateDesc.id_len, i);
			if (ret) {
				(void)SendMessage(*sd, STATE_STORED, -1);
			} else {
				(void)SendMessage(*sd, MEMORY_FAILED, -1);
			}

			/* last to be done for this is the REGISTER part: let's
			 * keep track of this registration */
			StoreSeriesName(tmp);
		}
		storeTime += MicroTime();	/* stop the timer */

		/* notify the auto fetchters */
		autoFetchTime -= MicroTime();
		if (ret) {
			NotifyFetchers(	&stateDesc, 
					contents + newStateDesc.id_len, 
					i);
		}
		autoFetchTime += MicroTime();

		FREE(contents);
		FREE(tmp);
		break;

	case AUTOFETCH_BEGIN:
		autoFetchTime -= MicroTime();

		stateNamesDescriptor.repetitions = header.dataSize;
		stateNames = (char *)MALLOC(header.dataSize);
		if(stateNames == NULL) {
			(void)SendMessage(*sd, MEMORY_FAILED, -1);
			DROP_SOCKET(sd);
			ERROR("ProcessRequest: out of memory\n");
		} else if(!RecvData(*sd,
					stateNames,
					&stateNamesDescriptor,
					1,
					-1)) {
			(void)SendMessage(*sd, MEMORY_FAILED, -1);
			DROP_SOCKET(sd);
			ERROR("ProcessRequest: data receive failed\n");
		} else if(*stateNames == '\0') {
			/* empty list: remove the client from the list of
			 * our autofetchers */
			EndAutoFetch(*sd);

			(void)SendMessage(*sd, AUTOFETCH_ACK, -1);
		} else {
			/* let's add the new autofetcher */
			if (!AddAutoFetcher(sd, stateNames)) {
				SendMessage(*sd, MEMORY_FAILED, -1);
				DROP_SOCKET(sd);
				ERROR("ProcessRequest: failed to add autoFetcher\n");
			} else {
				(void)SendMessage(*sd, AUTOFETCH_ACK, -1);
			}
		}
		FREE(stateNames);
		autoFetchTime += MicroTime();
		break;

	case MEMORY_CLEAN:
		if (!RecvData(*sd, &expiration, &expDescriptor, 1, -1)) {
			DROP_SOCKET(sd);
			ERROR("ProcessRequest: data receive failed\n");
		} else {
			(void)SendMessage(*sd, MEMORY_CLEANED, -1);
			(void)DoClean(expiration);
		}
		break;

#ifdef WITH_NETLOGGER	  
static struct loglocation memLogLocation;
	case MEMORY_LOGDEST: /* config message contains log location */
		if (!RecvData(*sd,
				&memLogLocation,
				loglocationDescriptor,
				loglocationDescriptorLength,
				-1)) {
			DROP_SOCKET(sd);
			ERROR("ProcessRequest: loglocation receive failed\n");
			return;
		}else {
			(void)SendMessage(*sd, MEMORY_LOGDEST_ACK, -1);
		}
		LOG2("ProcessRequest: loglocation %d .%s.\n", memLogLocation.loc_type, memLogLocation.path);
		break;
#endif /* WITH_NETLOGGER */	  	

	default:
		DROP_SOCKET(sd);
		ERROR1("ProcessRequest: unknown message %d\n", header.message);
	}

	/* socket is now available */
	SocketIsAvailable(*sd);
}

#define DEFAULT_MEMORY_DIR "."
#define DEFAULT_MEMORY_SIZE "2000"
#define DEFAULT_JOURNAL_SIZE "2000"
#define SWITCHES "C:a:d:n:e:l:N:Pp:s:v:Vi:B:"

static void usage() {
	printf("\nUsage: nws_memory [OPTIONS]\n");
	printf("Memory for the Network Weather Service\n");
	printf("\nOPTIONS can be:\n");
	printf("\t-e filename         write error messages to filename\n");
	printf("\t-l filename         write info/debug messages to filename\n");
	printf("\t-i filename         write pid to filename\n");
	printf("\t-a address          use this address as mine (ie multi-homed hosts)\n");
	printf("\t-n name             use name as my hostname\n");
	printf("\t-N nameserver       register with this nameserver\n");
	printf("\t-p port             bind to port instead of the default\n");
	printf("\t-s num              keep #num# measurement per experiment\n");
	printf("\t-d dir              save series files into directory dir\n");
	printf("\t-B db               use database #db# to store data\n");
	printf("\t-C #                # of caches to keep (0 to disable cache)\n");
	printf("\t-v level            verbose level (up to 5)\n");
	printf("\t-V                  print version\n");
	printf("Report bugs to <nws@nws.cs.ucsb.edu>.\n\n");
}

int
main(		int argc,
		char *argv[]) {
	IPAddress addresses[MAX_ADDRESSES], tmpAddress;
	unsigned int addressesCount;
	struct host_cookie memCookie,
		nsCookie;
	double nextBeatTime, wakeup;
	double now;
	int opt, 
		tmp,
		cacheEntries = 256,
		verbose;
	extern char *optarg;
	char tmpIP[127 + 1],
		password[127 + 1],
		memoryDir[255 + 1];
	FILE *logFD, *errFD;
	const char *c;
	char *toProcess, *dbname, *pidFile;

	/* Set up default values */
	verbose = 2;
	logFD = stdout;
	errFD = stderr;
	addressesCount = 0;
	toProcess = pidFile = NULL;

	dbname = GetEnvironmentValue("MEMORY_SIZE", "~", ".nwsrc", DEFAULT_MEMORY_SIZE);
	if (dbname == NULL) {
		fileSize = strtol(DEFAULT_MEMORY_SIZE, NULL, 10);
	} else {
		fileSize = strtol(dbname, NULL, 10);
		FREE(dbname);
	}
	dbname = GetEnvironmentValue("MEMORY_DIR", "~", ".nwsrc", DEFAULT_MEMORY_DIR);
	if (dbname == NULL) {
		SAFESTRCPY(memoryDir, DEFAULT_MEMORY_DIR);
	} else {
		SAFESTRCPY(memoryDir, dbname);
		FREE(dbname);
	}
	dbname = GetEnvironmentValue("NAME_SERVER", "~", ".nwsrc", "localhost");
	if (dbname == NULL) {
		SAFESTRCPY(nsCookie.name, "localhost");
	} else {
		SAFESTRCPY(nsCookie.name, dbname);
		FREE(dbname);
	}
	Host2Cookie(nsCookie.name, DefaultHostPort(NAME_SERVER_HOST), &nsCookie);
	password[0] = '\0';
	dbname = NULL;

	/* get my deafult name */
	Host2Cookie(MyMachineName(), DefaultHostPort(MEMORY_HOST), &memCookie);
	addressesCount = IPAddressValues(MyMachineName(),
			&addresses[0],
			MAX_ADDRESSES);
	if (addressesCount == 0) {
		ERROR1("Couldn't resolve my name (%s)\n", MyMachineName());
	}

	while((int)(opt = getopt(argc, argv, SWITCHES)) != EOF) {
		switch(opt) {
		case 'n':
			/* let's check we have a good name */
			if (!IPAddressValue(optarg, &tmpAddress)) {
				/* save the inet addresses */
				addressesCount += IPAddressValues(optarg, &addresses[addressesCount], MAX_ADDRESSES - addressesCount);
			} else {
				ERROR1("Unable to convert '%s': I'll do what you said but expect problems!\n", optarg);
			}

			/* overrride the name of the machine: we hope the
			 * user knows what is doing! */
			SAFESTRCPY(memCookie.name, optarg);

			break;

		case 'a':
			/* let's add this IPs to the list of my addresses */
			for (c = optarg; GETTOK(tmpIP, c, ",", &c); ) {
				tmp = IPAddressValues(tmpIP,
						&addresses[addressesCount],
						MAX_ADDRESSES - addressesCount);
				if (tmp == 0) {
					ERROR1("Unable to convert '%s' into an IP address\n", tmpIP);
				} else {
					addressesCount += tmp;
				}
			}
			break;

		case 'd':
			SAFESTRCPY(memoryDir, optarg);
			break;

		case 'e':
			/* open the error file */
			errFD = fopen(optarg, "w");
			if (errFD == NULL) {
				printf("Couldn't open %s!\n", optarg);
				exit(1);
			}
			break;

		case 'l':
			/* open the error file */
			logFD = fopen(optarg, "w");
			if (logFD == NULL) {
				printf("Couldn't open %s!\n", optarg);
				exit(1);
			}
			break;

		case 'i':
			/* write pid to file */
			pidFile = strdup(optarg);
			if (pidFile == NULL) {
				ABORT("out of memory\n");
			}
			break;

		case 'N':
			Host2Cookie(optarg, DefaultHostPort(NAME_SERVER_HOST), &nsCookie);
			break;

		case 'p':
			memCookie.port = strtol(optarg, NULL, 10);
			break;

		case 'P':
			fprintf(stdout, "Password? ");
			fscanf(stdin, "%s", password);
			break;

		case 's':
			fileSize = strtol(optarg, NULL, 10);
			break;

		case 'B':
			dbname = strdup(optarg);
			if (dbname == NULL) {
				fprintf(stderr, "out of memory\n");
			}
#ifdef NWS_WITH_DB
			backType = POSTGRES;
			cacheEntries = 0;
#else
			fprintf(stderr, "database is not enabled: ignoring -B\n");
#endif

		case 'C':
			cacheEntries = strtol(optarg, NULL, 10);
			break;

		case 'V':
			printf("nws_memory for NWS version %s", VERSION);
#ifdef HAVE_PTHREAD_H
			printf(", with thread support");
#endif
#ifdef WITH_DEBUG
			printf(", with debug support");
#endif
			printf("\n\n");
			exit(0);
			break;

		case 'v':
			verbose = (unsigned short)atol(optarg);
			break;

		case '?':
			if (optopt == 'v') {
				/* using the first level */
				verbose = 1;
				break;
			}

		default:
			usage();
			exit(1);
			break;

		}
	}

	/* initialize the performance counters */
	fetchTime = storeTime = oldStoreTime = autoFetchTime = 0;
	fetchQuery = storeQuery = oldStoreQuery = 0;

	/* let's set the verbose evel */
	SetDiagnosticLevel(verbose, errFD, logFD);

	/* now initializing the backend: if we use the directory, we need
	 * to initialize the caching schema */
	/* let's see if we are trying to use a database */
	switch (backType) {
	case LOCALDIR:
		/* WARNING: filesize s very important to have it right or
		 * cache and backing store could be inconsistent */
		InitStateModule(cacheEntries, fileSize, memoryDir);

		/* let's get the list of filename of possibly old states */
		toProcess = ReadOldStates();
		break;

	case POSTGRES:
		if (dbname == NULL || strlen(dbname) == 0) {
			ABORT("You need to specify a database name (-B)\n");
		}
		if (!ConnectToNwsDB(dbname)) {
			ABORT("Fail to use database try to remove -B\n");
		}

		/* let's get the list of tables of possibly old states */
		toProcess = GetTables();
		break;
	
	case NETLOGGER:
		WARN("we should initialize to use netlooger\n");
		break;
	}

	/* initialize the mySeries/orphanedSeries structures */
	if (!InitRegistrations(&orphanedSeries)) {
		ABORT("main: out of memory\n");
	}
	if (!InitRegistrations(&mySeries)) {
		ABORT("main: out of memory\n");
	}

	/* let's get the port and start serving */
	if(!EstablishHost(HostCImage(&memCookie),
                    MEMORY_HOST,
                    addresses,
                    addressesCount,
                    memCookie.port,
                    password,
                    &nsCookie,
		    NULL,		/* we are the memory ... */
                    &MyExit)) {
		ABORT("Unable to establish host: port already in use?\n");
	}

	/* now that we've got the port, we can print the pid into the
	 * pid file. We thus avoid to override pid files of running
	 * nameservers */
	if (pidFile != NULL) {
		FILE *pidfile = fopen(pidFile, "w");
		if (!pidfile) {
			ABORT1("Can't write pidfile %s\n", pidFile);
		}
		fprintf(pidfile, "%d", (int)getpid());
		fclose(pidfile);
		free(pidFile);
	}

	fclose(stdin);

	RegisterListener(STORE_STATE, "STORE_STATE", &ProcessRequest);
	RegisterListener(STORE_AND_REGISTER, "STORE_AND_REGISTER", &ProcessRequest);
	RegisterListener(FETCH_STATE, "FETCH_STATE", &ProcessRequest);
	RegisterListener(AUTOFETCH_BEGIN, "AUTOFETCH_BEGIN", &ProcessRequest);
	RegisterListener(MEMORY_CLEAN, "MEMORY_CLEAN", &ProcessRequest);
#ifdef WITH_NETLOGGER
	RegisterListener(MEMORY_LOGDEST, "MEMORY_LOGDEST", &ProcessRequest);
#endif
	if (!NotifyOnDisconnection(&EndAutoFetch)) {
		WARN("main: failed to register for disconnections\n");
	}

	nextBeatTime = 0;

	/* main service loop */
	while(1) {
		now = CurrentTime();
		if(now >= nextBeatTime) {
			RegisterHost(DEFAULT_HOST_BEAT * 2);
			nextBeatTime = now + (HostHealthy() ? DEFAULT_HOST_BEAT : SHORT_HOST_BEAT);

			/* print performance timing */
			LOG1("main: spent %.0fms in fetch\n", fetchTime/1000);
			LOG1("main: spent %.0fms in store\n", storeTime/1000);
			LOG1("main: spent %.0fms in old store\n", oldStoreTime/1000);
			LOG1("main: spent %.0fms for autofetching\n", autoFetchTime/1000);
			LOG3("main: got %d fetch, %d store and %d old store requests\n", fetchQuery, storeQuery, oldStoreQuery);
			/* resetting */
			fetchTime = storeTime = oldStoreTime = autoFetchTime = 0;
			fetchQuery = storeQuery = oldStoreQuery = 0;


			LOG2("main: we have %d series and %d orphaned series\n", mySeries->howMany, orphanedSeries->howMany);
		}

		/* we want to wake up at least once a minute */
		if ((now + 60) < nextBeatTime) {
			wakeup = 60;
		} else {
			wakeup = nextBeatTime - now;
		}

		/* let's convert filenames to orphaned series: if the
		 * directory is big it may take time to read it. */
		if (toProcess != NULL) {
			if (CheckOldNames(	toProcess,
						mySeries,
						orphanedSeries,
						1)) {
				wakeup = -1;
			} else {
				FREE(toProcess);
			}
		}

		/* let's register the series we are in charge of */
		if (RegisterSeries(orphanedSeries, 10)) {
			wakeup = -1;
		}
		if (RegisterSeries(mySeries, 10)) {
			wakeup = -1;
		}

		/* we want the memory to be repsonsive, so we flush all
		 * the waiting messages */
		while(ListenForMessages(-1)) {
			;
		}
		ListenForMessages((wakeup > 0) ? wakeup : -1);
	}

	/* return(0); Never reached */
}