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

Revision 411, 24.6 KB (checked in by trnewman, 15 years ago)

Adding Apache license information.

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