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

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

Reworked memory allocation in the constructors a bit more. Looking at,
I'm not 100% certain how it wasn't segfaulting previously during normal
operation since 'LoadConfiguration?' was being called before the memory
was allocated.

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