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

Revision 435, 24.6 KB (checked in by bhilburn, 15 years ago)

Now outputting socketFD in of registered components in logs, returning
proper data type to support different platforms.

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