root/vtcross/trunk/src/shell/CognitiveRadioShell.cpp @ 432

Revision 432, 24.5 KB (checked in by bhilburn, 15 years ago)

Fixed a memery allocation issue that might have segfaulted, and a memory
leak.

Line 
1/*
2 Copyright 2009 Virginia Polytechnic Institute and State University 
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7 
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15*/
16
17/* DESCRIPTION OF FILE.
18 */
19
20
21#include <cstdlib>
22#include <cstring>
23#include <stdint.h>
24#include <string>
25
26#include <arpa/inet.h>
27#include <iostream>
28#include <netinet/in.h>
29#include <netdb.h>
30#include <fcntl.h>
31#include <sys/ioctl.h>
32#include <sys/mman.h>
33#include <sys/socket.h>
34#include <sys/types.h>
35#include <sys/wait.h>
36
37#include "tinyxml/tinyxml.h"
38#include "tinyxml/tinystr.h"
39
40#include "vtcross/common.h"
41#include "vtcross/components.h"
42#include "vtcross/containers.h"
43#include "vtcross/debug.h"
44#include "vtcross/error.h"
45#include "vtcross/socketcomm.h"
46
47
48CognitiveRadioShell::CognitiveRadioShell()
49{
50    LOG("Creating Cognitive Radio Shell.\n");
51    SML_present = false;
52    PE_present = false;
53    CE_present = false;
54
55    /* These allocations must be done here to prevent a segfault should the
56     * shell be constructed then immediately destructed. */
57    params = new Parameter[10];
58    observables = new Observable[10];
59    utils = new Utility[10];
60    radio_info = new Radio_Info;
61}
62
63
64CognitiveRadioShell::~CognitiveRadioShell()
65{
66    delete [] params;
67    delete [] observables;
68    delete [] utils;
69    delete Radio_Info;
70}
71
72
73CognitiveRadioShell::CognitiveRadioShell(const char* radioConfig, int16_t p1, \
74        int16_t p2, int16_t p3)
75{
76    LOG("Creating Cognitive Radio Shell.\n");
77    LoadRadioConfiguration(radioConfig, params, utils, observables, radio_info);
78
79    primaryPort = p1;
80    policyPort = p2;
81    commandPort = p3;
82}
83
84
85void
86CognitiveRadioShell::SendComponentType(int32_t socketFD)
87{
88    SendMessage(socketFD, "response_shell");
89    LOG("Cognitive Radio Shell responded to GetRemoteComponentType query.\n");
90}
91
92
93std::string
94CognitiveRadioShell::GetRemoteComponentType(int32_t socketFD)
95{
96    SendMessage(socketFD, "request_component_type");
97
98    char buffer[256];
99    memset(buffer, 0, 256);
100    ReadMessage(socketFD, buffer);
101
102    return std::string(buffer);
103}
104
105
106void
107CognitiveRadioShell::Shutdown()
108{
109    // TODO should something else be happening here?
110}
111
112
113void
114CognitiveRadioShell::Reset()
115{
116    LOG("Resetting Cognitive Radio Shell.\n");
117}
118
119
120// TODO what is the point of always returning a 1?
121bool
122CognitiveRadioShell::SendRadioConfiguration(int32_t socketFD)
123{
124    LOG("Cognitive Radio Shell:: Sending radio configuration to Cognitive Engine.\n");
125
126    char counter[55];
127    char var[50];
128
129    /* Send utilities */
130    sprintf(counter, "%d", radio_info->numUtilities);
131    SendMessage(socketFD, counter);
132    for(size_t i = 0; i < radio_info->numUtilities; i++) {
133        SendMessage(socketFD, utils[i].name.c_str());
134        SendMessage(socketFD, utils[i].units.c_str());
135        SendMessage(socketFD, utils[i].goal.c_str());
136        sprintf(var,"%f", utils[i].target);
137        SendMessage(socketFD, var);
138    }
139
140    /* Send parameters */
141    sprintf(counter,"%i",radio_info->numParameters);
142    SendMessage(socketFD,counter);
143    for(size_t i = 0; i < radio_info->numParameters; i++) {
144        SendMessage(socketFD, params[i].name.c_str());
145        SendMessage(socketFD, params[i].units.c_str());
146        sprintf(var, "%f", params[i].min);
147        SendMessage(socketFD,var);
148        sprintf(var, "%f", params[i].max);
149        SendMessage(socketFD, var);
150        sprintf(var, "%f", params[i].step);
151        SendMessage(socketFD, var);
152
153        sprintf(counter, "%i", params[i].numAffects);
154        SendMessage(socketFD, counter);
155        for(size_t j = 0; j < params[i].numAffects; j++) {
156            SendMessage(socketFD, params[i].affection_list[j].u->name.c_str());
157            SendMessage(socketFD, params[i].affection_list[j].relation.c_str());
158        }
159    }
160
161    /* Send observables */
162    sprintf(counter,"%i",radio_info->numObservables);
163    SendMessage(socketFD, counter);
164    for(size_t i = 0; i < radio_info->numObservables; i++) {
165        SendMessage(socketFD, observables[i].name.c_str());
166       
167        sprintf(counter, "%i", observables[i].numAffects);
168        SendMessage(socketFD, counter);
169        for(size_t j = 0; j < observables[i].numAffects; j++) {
170            SendMessage(socketFD, observables[i].affection_list[j].u->name.c_str());
171            SendMessage(socketFD, observables[i].affection_list[j].relation.c_str());
172        }
173    }
174   
175    /* Receive ACK for radio configuration */
176    char buffer[256];
177    memset(buffer, 0, 256);
178    ReadMessage(socketFD, buffer);
179
180    if(strcmp(buffer, "receive_config_ack") != 0) {
181        LOG("Cognitive Radio Shell:: Unexpected response: %s\n", buffer);
182        return 0;
183    }
184
185    return 1;
186}
187
188bool
189CognitiveRadioShell::SendRadioExperience(int32_t socketFD)
190{
191
192    LOG("Cognitive Radio Shell:: Sending radio experience to Cognitive Engine.\n");
193    int32_t numberExp = 4;
194    char numberExpString[50];
195
196    sprintf(numberExpString, "%d", numberExp);
197    SendMessage(socketFD, "test");  //TODO modified
198
199    char buffer[256];
200    memset(buffer, 0, 256);
201    ReadMessage(socketFD, buffer);
202    if(strcmp(buffer, "receive_exp_ack") != 0) {
203        // TODO perhaps this should be a WARNING instead of a LOG?
204        LOG("Cognitive Radio Shell:: Unexpected response: %s\n", buffer);
205        return 0;
206    }
207    //printf("done sending exp \n");
208    return 1;
209}
210
211
212void
213CognitiveRadioShell::RegisterCognitiveEngine(int32_t socketFD)
214{
215    LOG("Cognitive Radio Shell:: Received registration message from Cognitive Engine.\n");
216   
217    SendMessage(socketFD, "register_ack");
218    SendRadioConfiguration(socketFD);
219    SendRadioExperience(socketFD);
220
221    numberOfCognitiveEngines++;
222    CE_present = true;
223}
224
225
226void
227CognitiveRadioShell::DeregisterCognitiveEngine(int32_t socketFD)
228{
229    LOG("Cognitive Radio Shell:: Received deregistration message from Cognitive Engine.\n");
230
231    numberOfCognitiveEngines--;
232    if(numberOfCognitiveEngines == 0)
233        CE_present = false;
234
235    SendMessage(socketFD, "deregister_ack");
236    shutdown(socketFD, 2);
237    close(socketFD);
238    LOG("Cognitive Radio Shell:: Socket closed.\n");
239}
240
241
242void
243CognitiveRadioShell::RegisterPolicyEngine(int32_t socketFD)
244{
245    LOG("Cognitive Radio Shell:: Received registration message from Policy Engine.\n");
246    PE_present = true;
247}
248
249
250void
251CognitiveRadioShell::DeregisterPolicyEngine(int32_t socketFD)
252{
253    LOG("Cognitive Radio Shell:: Received deregistration message from Policy Engine.\n");
254
255    PE_present = false;
256   
257    SendMessage(socketFD, "deregister_ack");
258    shutdown(socketFD, 2);
259    close(socketFD);
260    LOG("Cognitive Radio Shell:: Socket closed.\n");
261}
262
263
264void
265CognitiveRadioShell::RegisterSML(int32_t socketFD)
266{
267    LOG("Cognitive Radio Shell:: Received registration message from SML.\n");
268
269    SML_present = true;
270}
271
272
273void
274CognitiveRadioShell::DeregisterSML(int32_t socketFD)
275{
276    LOG("Cognitive Radio Shell:: Received deregistration message from SML.\n");
277
278    SML_present = false;
279
280    SendMessage(socketFD, "deregister_ack");
281    shutdown(socketFD, 2);
282    close(socketFD);
283    LOG("Cognitive Radio Shell:: Socket closed.\n");
284}
285
286void
287CognitiveRadioShell::SetActiveMission(int32_t socketFD)
288{
289    char buffer[256];
290
291    LOG("Cognitive Radio Shell:: Received Set Active Mission command from host.\n");
292   
293    // Read the name of the active mission to be set from the host.
294    memset(buffer, 0, 256);
295    ReadMessage(commandSocketFD, buffer);
296
297    // Send command to SML
298    SendMessage(ceSocketFD, "set_active_mission");
299    SendMessage(ceSocketFD, buffer);
300
301    // Get ack from SML saying the mission was set properly
302    memset(buffer, 0, 256);
303    ReadMessage(ceSocketFD, buffer);
304
305    // Forward ack to host
306    SendMessage(commandSocketFD, buffer);
307}
308
309int32_t
310CognitiveRadioShell::LoadRadioConfiguration(const char* radioConfig, \
311        Parameter* &pList, Utility* &uList, Observable* &oList, \
312        Radio_Info* radioInfo)
313{
314    TiXmlElement *pElem;
315    TiXmlElement *pChild;
316    TiXmlElement *pChild1;
317    TiXmlElement *pSecondChild;
318    TiXmlHandle hRoot(0);
319
320    int32_t count = 0;
321    size_t item_count = 0;
322    size_t affect_count = 0;
323    uint32_t attribute_count = 0;
324    bool match_found = false;
325
326    LOG("Cognitive Radio Shell:: Loading radio configuration.\n");
327
328    TiXmlDocument doc( radioConfig );
329    bool loadOkay = doc.LoadFile();
330    if(!loadOkay)
331        ERROR(1,"Loading radio configuration failed: %s\n", radioConfig);
332
333    TiXmlHandle hDoc(&doc);
334   
335    pElem = hDoc.FirstChildElement().Element();
336
337    if(!pElem)
338        ERROR(1, "No valid root!");
339
340    hRoot = TiXmlHandle(pElem);
341
342    pElem = hRoot.FirstChild("utilities").Element();
343    pChild1 = hRoot.Child("utilities", count).Element();
344
345    for(pChild = pChild1->FirstChildElement("utility"); pChild; \
346        pChild = pChild->NextSiblingElement()) {
347
348        const char *uName = pChild->Attribute("name");
349        if(uName)
350            uList[item_count].name = uName;   
351
352        const char *uUnits = pChild->Attribute("units");
353        if(uUnits)
354            uList[item_count].units = uUnits;
355
356        const char *uGoal = pChild->Attribute("goal");
357        if(uGoal)
358            uList[item_count].goal = uGoal;
359
360        if(pChild->QueryFloatAttribute("target", &uList[item_count].target) != TIXML_SUCCESS)
361            uList[item_count].target = -1;
362
363        item_count++;
364    }
365
366    radio_info->numUtilities = item_count;   
367    LOG("Cognitive Radio Shell:: Parsed %d utilities.\n", radioInfo->numUtilities);
368
369    item_count = 0;
370    pElem = hRoot.FirstChild("observables").Element();
371    pChild1 = hRoot.Child("observables", count).Element();
372
373    for(pChild = pChild1->FirstChildElement("observable"); pChild; \
374        pChild = pChild->NextSiblingElement()) {
375
376        const char *oName = pChild->Attribute("name");
377        if(oName)
378            oList[item_count].name = oName;
379       
380        affect_count = 0;
381        for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; \
382            pSecondChild = pSecondChild->NextSiblingElement()) {
383
384            const char *oUtilName = pSecondChild->Attribute("utility");
385            if(oUtilName) {
386                for(attribute_count = 0; attribute_count < radio_info->numUtilities; attribute_count++ ) {
387                    if(uList[attribute_count].name == oUtilName) {
388
389                        oList[item_count].affection_list[affect_count].u = &uList[attribute_count];
390                        const char *oRelate = pSecondChild->Attribute("relationship");
391                        if(oRelate)
392                            oList[item_count].affection_list[affect_count].relation = oRelate;
393
394                        affect_count++;
395                        match_found = true;
396                        break;
397                    }
398                }
399            }
400
401            if(!match_found) {
402                ERROR(1, "Error: %s: %s is not a valid utility.\n", \
403                    oList[item_count].name.c_str(), oUtilName);
404            }
405            else
406                match_found = false;   
407        }
408        oList[item_count].numAffects = affect_count;
409        item_count++;
410    }
411
412    radioInfo->numObservables = item_count;   
413    LOG("Cognitive Radio Shell:: Parsed %d observables.\n", radioInfo->numObservables);
414
415    pElem = hRoot.FirstChild("parameters").Element();
416    pChild1 = hRoot.Child("parameters", count).Element();
417   
418    item_count = 0;
419    for(pChild = pChild1->FirstChildElement("parameter"); pChild; \
420        pChild = pChild->NextSiblingElement()) {
421
422        const char *pName = pChild->Attribute("name");
423        if(pName)
424            pList[item_count].name = pName;   
425
426        const char *pUnits = pChild->Attribute("units");
427        if(pUnits)
428            pList[item_count].units = pUnits;
429
430        if(pChild->QueryFloatAttribute("min", &pList[item_count].min) != TIXML_SUCCESS)
431            pList[item_count].min = -1;
432
433        if(pChild->QueryFloatAttribute("max", &pList[item_count].max) != TIXML_SUCCESS)
434            pList[item_count].max = -1;
435
436        if(pChild->QueryFloatAttribute("step", &pList[item_count].step) != TIXML_SUCCESS)
437            pList[item_count].step = -1;
438       
439        affect_count = 0;
440        for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; \
441
442            pSecondChild = pSecondChild->NextSiblingElement()) {
443            const char *pUtilName = pSecondChild->Attribute("utility");
444            if(pUtilName) {
445                for(attribute_count = 0; attribute_count < radio_info->numUtilities; attribute_count++) {
446                    if(uList[attribute_count].name == pUtilName) {
447                        pList[item_count].affection_list[affect_count].u = &uList[attribute_count];   
448
449                        const char *pRelate = pSecondChild->Attribute("relationship");
450                        if(pRelate)
451                            pList[item_count].affection_list[affect_count].relation = pRelate;
452                        else
453                            LOG("Error: No relation found.\n");
454
455                        match_found = true;
456                        affect_count++;
457                        break;
458                    }
459                }
460            }
461
462            if(!match_found) {
463                ERROR(1, "Error: %s: %s is not a valid utility.\n", \
464                    pList[item_count].name.c_str(), pUtilName);
465            }
466
467            match_found = false;   
468        }
469
470        pList[item_count].numAffects = affect_count;
471        item_count++;
472    }
473
474    radioInfo->numParameters = item_count;
475    LOG("Cognitive Radio Shell:: Parsed %d parameters.\n", radioInfo->numParameters);
476
477    return 1;
478}
479
480
481void
482CognitiveRadioShell::GetOptimalParameters(int32_t socketFD)
483{
484    char buffer[256];
485    char counter[55];
486    char var[50];
487
488    /* Receive Set of Observables */
489    LOG("Cognitive Radio Shell:: Got request for optimization.\n");
490    memset(buffer, 0, 256);
491    ReadMessage(commandSocketFD, buffer);
492    uint32_t numObservables = atoi(buffer);
493 
494    LOG("Cognitive Radio Shell:: Attempting to get %i observables.\n", numObservables);
495    Observable *o = new Observable[numObservables];
496 
497    for(size_t i = 0; i < numObservables; i++) {
498        memset(buffer, 0, 256);
499        ReadMessage(commandSocketFD, buffer);
500        o[i].name = std::string(buffer);
501   
502        memset(buffer, 0, 256);
503        ReadMessage(commandSocketFD, buffer);
504        o[i].value = atof(buffer);
505    }
506
507    /* Receive Set of Current Parameters */
508    memset(buffer, 0, 256);
509    ReadMessage(commandSocketFD,buffer);
510    uint32_t numCurrentParameters = atoi(buffer);
511 
512    LOG("Cognitive Radio Shell:: Attempting to get %i parameters.\n",numCurrentParameters);
513    Parameter * cp = new Parameter[numCurrentParameters];
514
515    for (size_t i = 0; i < numCurrentParameters; i++){
516        memset(buffer, 0, 256);
517        ReadMessage(commandSocketFD,buffer);
518        cp[i].name = std::string(buffer);
519        memset(buffer, 0, 256);
520        ReadMessage(commandSocketFD,buffer);
521        cp[i].value = atof(buffer);
522    }
523
524    /* Send to Cognitive Engine
525     * TODO: With multiple CEs we need to make a decision about where
526     * to send this information
527     */
528    LOG("Cognitive Radio Shell:: Passing on observables.\n");
529    SendMessage(ceSocketFD,"request_optimization");
530    sprintf(counter,"%i",numObservables);
531    SendMessage(ceSocketFD,counter);
532    for(size_t i = 0; i < numObservables; i++) {
533        SendMessage(ceSocketFD,o[i].name.c_str());
534        sprintf(var,"%f",o[i].value);
535        SendMessage(ceSocketFD,var);
536    }
537       
538    LOG("Cognitive Radio Shell:: Passing on current parameters.\n");
539    sprintf(counter,"%i",numCurrentParameters);
540    SendMessage(ceSocketFD,counter);
541    for(size_t i = 0; i < numCurrentParameters; i++) {
542        SendMessage(ceSocketFD,cp[i].name.c_str());
543        sprintf(var,"%f",cp[i].value);
544        SendMessage(ceSocketFD,var);
545    }
546
547    LOG("Cognitive Radio Shell:: Receiving optimized parameters.\n");
548    /* Receive Set of Parameters */
549    memset(buffer, 0, 256);
550    ReadMessage(ceSocketFD, buffer);
551    uint32_t numParameters = atoi(buffer);
552   
553    Parameter *p = new Parameter[numParameters];
554 
555    for(size_t i = 0; i < numParameters; i++) {
556        memset(buffer, 0, 256);
557        ReadMessage(ceSocketFD, buffer);
558        p[i].name = std::string(buffer);
559   
560        memset(buffer, 0, 256);
561        ReadMessage(ceSocketFD, buffer);
562        p[i].value = atof(buffer);
563    }
564
565    /* Send to Application
566     */
567    LOG("Cognitive Radio Shell:: Sending optimized parameters to Application.\n");
568    memset(counter, 0, 55);
569    sprintf(counter, "%i", numParameters);
570    SendMessage(commandSocketFD, counter);
571    for(size_t i = 0; i < numParameters; i++) {
572        SendMessage(commandSocketFD, p[i].name.c_str());
573        sprintf(var, "%f", p[i].value);
574        SendMessage(commandSocketFD, var);
575    }
576
577    delete [] o;
578    delete [] p;
579}
580
581// TODO point of always returning 1?
582bool
583CognitiveRadioShell::UpdateParameterPerformance(int32_t socketFD)
584{
585    char counter[55];
586    char var[50];
587    char buffer[256];
588
589    /* Receive Set of Parameters */
590    memset(buffer, 0, 256);
591    ReadMessage(commandSocketFD,buffer);
592    uint32_t numParameters = atoi(buffer);
593 
594    Parameter *p = new Parameter[numParameters];
595
596    for (size_t i = 0; i < numParameters; i++){
597        memset(buffer, 0, 256);
598        ReadMessage(commandSocketFD,buffer);
599        p[i].name = std::string(buffer);
600        memset(buffer, 0, 256);
601        ReadMessage(commandSocketFD,buffer);
602        p[i].value = atof(buffer);
603    }
604
605    /* Receive Set of Observables */
606    memset(buffer, 0, 256);
607    ReadMessage(commandSocketFD, buffer);
608    uint32_t numObservables = atoi(buffer);
609 
610    Observable *o = new Observable[numObservables];
611 
612    for(size_t i = 0; i < numObservables; i++) {
613        memset(buffer, 0, 256);
614        ReadMessage(commandSocketFD, buffer);
615        o[i].name = std::string(buffer);
616   
617        memset(buffer, 0, 256);
618        ReadMessage(commandSocketFD, buffer);
619        o[i].value = atof(buffer);
620    }
621
622    SendMessage(ceSocketFD, "update_performance");
623   
624    /* Send Parameters */
625    memset(counter, 0, 55);
626    sprintf(counter, "%i", numParameters);
627    SendMessage(ceSocketFD, counter);
628   
629    for(size_t i = 0; i < numParameters; i++) {
630        SendMessage(ceSocketFD,p[i].name.c_str());
631        sprintf(var,"%f",p[i].value);
632        SendMessage(ceSocketFD,var); 
633    }   
634   
635    /* Send Observables */
636    sprintf(counter, "%i", numObservables);
637    SendMessage(ceSocketFD, counter);
638    for(size_t i = 0; i < numObservables; i++) {
639        SendMessage(ceSocketFD, o[i].name.c_str());
640        sprintf(var, "%f", o[i].value);
641        SendMessage(ceSocketFD, var);
642    }   
643
644    delete [] p;
645    delete [] o;
646   
647    return 1;
648}
649
650
651int32_t
652CognitiveRadioShell::HandleMessage(int32_t socketFD)
653{
654    char buffer[256];
655    int ret = 0;
656   
657    ret = ReadMessage(socketFD, buffer);
658    if(ret == -1) {
659        return ret;
660    }
661
662    // TODO trying to read this code lock makes my eyes bleed
663    if(strcmp(buffer, "register_engine_cognitive") == 0) {
664        RegisterCognitiveEngine(socketFD);
665    } else if(strcmp(buffer, "deregister_engine_cognitive") == 0) {
666        DeregisterCognitiveEngine(socketFD);
667    } else if(strcmp(buffer, "register_engine_policy") == 0) {
668        RegisterPolicyEngine(socketFD);
669    } else if(strcmp(buffer, "deregister_engine_policy") == 0) {
670        DeregisterPolicyEngine(socketFD);
671    } else if(strcmp(buffer, "register_sml") == 0) {
672        RegisterSML(socketFD);
673    } else if(strcmp(buffer, "deregister_sml") == 0) {
674        DeregisterSML(socketFD);
675    } else if(strcmp(buffer, "update_performance") == 0) {
676        UpdateParameterPerformance(socketFD);
677    } else if(strcmp(buffer, "get_number_utilities") == 0) {
678        char numUtilities[20];
679        sprintf(numUtilities, "%i", radio_info->numUtilities);
680        SendMessage(commandSocketFD, numUtilities);
681    } else if(strcmp(buffer, "get_number_observables") == 0) {
682        char numObservables[20];
683        sprintf(numObservables, "%i", radio_info->numObservables);
684        SendMessage(commandSocketFD, numObservables);
685    } else if(strcmp(buffer, "get_number_parameters") == 0) {
686        char numParameters[20];
687        sprintf(numParameters, "%i", radio_info->numParameters);
688        SendMessage(commandSocketFD, numParameters);
689    } else if(strcmp(buffer, "request_optimization") == 0) {
690        /* Receive optimization request and current environment */
691        GetOptimalParameters(socketFD); 
692    } else if(strcmp(buffer, "set_active_mission") == 0) {
693        SetActiveMission(socketFD); 
694    } else if(strcmp(buffer, "request_optimization_service") == 0) {
695        /* Receive optimization request and current environment */
696        //GetOptimalParametersService(socketFD); 
697    }
698
699    return ret;
700}
701
702
703void
704CognitiveRadioShell::StartShellServer()
705{
706    struct timeval selTimeout;
707    int32_t primary = 0;
708    int32_t policy = 1;
709    int32_t command = 2;
710    int32_t running = 1;
711    int32_t port, rc, new_sd = 1;
712    int32_t desc_ready = 1;
713    int32_t timeout = 50;
714    int32_t ret = 0;;
715    fd_set sockSet;
716   
717
718
719    int32_t *servSock = new int32_t[3];
720
721    servSock[primary] = CreateTCPServerSocket(primaryPort);
722    servSock[policy] = CreateTCPServerSocket(policyPort);
723    servSock[command] = CreateTCPServerSocket(commandPort);
724
725    int32_t maxDescriptor;
726
727    if(servSock[primary] > servSock[policy])
728        maxDescriptor = servSock[primary];
729    else
730        maxDescriptor = servSock[policy];
731
732    if(servSock[command] > maxDescriptor)
733        maxDescriptor = servSock[command];
734
735    if(InitializeTCPServerPort(servSock[primary]) == -1)
736        ERROR(1,"Error initializing primary port\n");
737 
738    if(InitializeTCPServerPort(servSock[policy]) == -1)
739        ERROR(1,"Error initializing policy port\n");
740
741    if(InitializeTCPServerPort(servSock[command]) == -1)
742        ERROR(1,"Error initializing command port\n");
743
744    FD_ZERO(&sockSet);
745   
746    while (running) {
747        /* Zero socket descriptor vector and set for server sockets */
748        /* This must be reset every time select() is called */
749        FD_SET(servSock[primary], &sockSet);
750        FD_SET(servSock[policy], &sockSet);
751        FD_SET(servSock[command], &sockSet);
752
753        /* Timeout specification */
754        /* This must be reset every time select() is called */
755        selTimeout.tv_sec = timeout;       /* timeout (secs.) */
756        selTimeout.tv_usec = 0;            /* 0 microseconds */
757
758        /* Suspend program until descriptor is ready or timeout */
759        rc = select(maxDescriptor + 1, &sockSet, NULL, NULL, &selTimeout);
760        if(rc == 0)
761            LOG("No echo requests for %i secs...Server still alive\n", timeout);
762        else {
763            desc_ready = rc;
764
765            for(port = 0; port <= maxDescriptor && desc_ready > 0; port++) {
766                if(FD_ISSET(port, &sockSet)) {
767                    desc_ready -= 1;
768                    /* Check if request is new or on an existing open descriptor */
769                    if((port == servSock[primary]) || (port == servSock[policy]) || (port == servSock[command])) {
770                        do {
771                            new_sd = AcceptTCPConnection(port);
772                            if(new_sd < 0) {
773                                break;
774                            }
775                           
776                            if(port == servSock[primary])
777                                ceSocketFD = new_sd;
778                            if(port == servSock[command])
779                                commandSocketFD = new_sd;
780                            if(port == servSock[policy])
781                                policySocketFD = new_sd;
782
783                            ret = HandleMessage(new_sd);
784
785                            if(ret == -1) {
786                                FD_CLR(new_sd,&sockSet);
787                                close(new_sd);
788                                break;
789                            }
790
791                            FD_SET(new_sd,&sockSet);
792                            if(new_sd > maxDescriptor)
793                                maxDescriptor = new_sd;
794                        } while(new_sd != -1);
795                    }
796                    else {
797                        ret = HandleMessage(port);
798                        if(ret == -1) {
799                            FD_CLR(port,&sockSet);
800                            close(port);
801                        }
802                    }
803                }
804            }
805        }
806    }
807
808    LOG("Closing it all.\n\n");
809    /* Close sockets */
810    close(servSock[primary]);
811    close(servSock[policy]);
812    close(servSock[command]);
813
814    /* Free list of sockets */
815    delete servSock;
816
817    return;
818}
Note: See TracBrowser for help on using the browser.