Tải bản đầy đủ - 0 (trang)
Chapter 7. The ACE Acceptor-Connector Framework

Chapter 7. The ACE Acceptor-Connector Framework

Tải bản đầy đủ - 0trang

7.1Overview

Manynetworkedapplications,suchase-mail,remotefile

backups,andWebservices,useconnection-orientedservices

containingclassesthatplaythefollowingroles:

Theconnectionroledetermineshowanapplication

establishesconnections.

Thecommunicationroledetermineswhetheran

applicationplaystheroleofaclient,aserver,orbothclient

andserverinapeer-to-peerconfiguration.

Networkedapplicationsthatcommunicateviaconnectionorientedprotocols(e.g.,TCP/IP)aretypifiedbythefollowing

asymmetricconnectionrolesbetweenclientsandservers:

Serversoftenwaitpassivelytoacceptconnectionsby

listeningonadesignatedTCPport.

Clientsofteninitiateconnectionsactivelybyconnectingtoa

server'slisteningport.

Eveninpeer-to-peerapplications,whereapplicationsplayboth

clientandserverroles,connectionsmustbeinitiatedactivelyby

onepeerandacceptedpassivelybytheother.Toenhancereuse

andextensibility,networkedapplicationsshouldbedesignedto

easilychangeconnectionandcommunicationrolestosupport

differentrequirementsandenvironments.

TheACEAcceptor-Connectorframeworkimplementsthe

Acceptor-Connectordesignpattern[POSA2],whichenhances

softwarereuseandextensibilitybydecouplingtheactivities

requiredtoconnectandinitializecooperatingpeerservicesina



networkedapplicationfromtheprocessingtheyperformonce

they'reconnectedandinitialized.Thischapterdescribesthe

followingACEAcceptor-Connectorframeworkclassesthat

networkedapplicationscanusetoestablishconnectionsand

initializepeerservices:

ACEClass



Description



ACE_Svc_Handler RepresentsthelocalendofaconnectedserviceandcontainsanIPC

endpointusedtocommunicatewithaconnectedpeer.



ACE_Acceptor



Thisfactorywaitspassivelytoacceptaconnectionandthen

initializesanACE_Svc_Handlerinresponsetoanactiveconnection

requestfromapeer.



ACE_Connector



Thisfactoryactivelyconnectstoapeeracceptorandtheninitializes

anACE_Svc_Handlertocommunicatewithitsconnectedpeer.



ThemostimportantrelationshipsbetweentheACEAcceptorConnectorframework'sclassesareshowninFigure7.1.These

classesplaythefollowingrolesinaccordancewiththeAcceptorConnectorpattern[POSA2]:

Figure7.1.TheACEAcceptor-ConnectorFramework

Classes



Eventinfrastructurelayerclassesperformgeneric,

application-independentstrategiesfordispatchingevents.

TheACEReactorframeworkdescribedinChapter3is

commonlyusedastheeventinfrastructurelayer.

Connectionmanagementlayerclassesperform

application-independentconnectionandinitialization

services.TheseclassesincludetheACE_Svc_Handler,

ACE_Acceptor,andACE_Connector.

Applicationlayerclassescustomizethegeneric

strategiesperformedbytheothertwolayersviasubclassing

and/ortemplateinstantiationtocreateobjectsthat

establishconnections,exchangedata,andperformservicespecificprocessing.IntheACEAcceptor-Connector

framework,applicationlayerclassesaredescendantsand

templateinstantiationsoftheconnectionmanagementlayer

classesoutlinedabove.

BybeingdescendantsofACE_Event_Handler,theseclasses

allofferintegrationwiththeACEReactorframeworkfrom

Chapter3.Chapter8describesavariantoftheAcceptorConnectorframeworkbasedontheACEProactorframeworkfor

applicationsinwhichasynchronousI/Oismoreappropriateor

beneficial.

TheACEAcceptor-Connectorframeworkprovidesthefollowing

benefits:

Reusabilityandextensibility.Connection-oriented

networkedapplicationsoftencontainasignificantamountof

low-levelcodethatestablishesconnectionsandinitializes

services.Thiscodeislargelyindependentoftheprocessing

thatconnectedservicehandlersperformonthedatathey

exchange.TheACEAcceptor-Connectorframeworkrefactors



thislow-levelcodeintoreusable,application-independent

acceptorandconnectorclassesthatknowhowtoestablish

aconnectionandinitializeitsassociatedservicehandler

aftertheconnectionisestablished.Asaresult,service

handlerscanfocussolelyontheirapplication-defined

processing.Thisseparationofconcernsmakesiteasierto

addnewtypesofapplicationservices,service

implementations,authenticationprotocols,and

communicationprotocolswithoutaffectingexisting

connectionestablishmentandserviceinitialization

configurationcode.

Portability.Theclasstemplatesintheframeworkareall

parameterizedbythetypeofIPCmechanismneededto

establishconnectionsandtotransferdata.Theflexibility

offeredbythistemplate-basedextensibilityisusefulwhen

developingapplicationsthatmustrunportablyand

efficientlyacrossmultipleOSplatforms.TheIPCclass

parametersfortheAcceptor-Connectortemplatescanbe

anynetworkprogrammingclassesthatconformtothe

interfaceexpectedbythetemplates.Forexample,

dependingoncertainpropertiesoftheunderlyingOS

platform,suchaswhetherit'saBSDorSystemVvariantof

UNIX,aservercaninstantiatetheframeworkclassestouse

theACESocketwrapperfacadesortheACETLIwrapper

facades.Fornon-TCP/IPapplications,thetemplatescanbe

instantiatedwithmanyofACE'sIPCwrapperfacades,or

anyprivatelydevelopedclassesthatexportthenecessary

interface.

Robustness.Bystronglydecouplingaservicehandlerfrom

itsacceptor,theframeworkcanensurethatpassive-mode

transportendpointsaren'taccidentallyusedtoreadorwrite

data.Thisaddedtypesafetyeliminatesasubtleand

perniciousclassoferrorsthatcanarisewhenprogramming

withweaklytypednetworkprogramminginterfaces,suchas

theSocketorTLIAPIsdefinedinC.



Efficiency.TheAcceptor-Connectorpatterncanactively

establishconnectionswithalargenumberofpeers

asynchronouslyandefficientlyoverlong-latencywidearea

networks.Asynchronyisimportantinthesesituations

becauselarge-scalenetworkedapplicationsmayhave

hundredsorthousandsofpeerstoconnect.

Theremainderofthischaptermotivatesanddescribesthe

capabilitiesoftheACEAcceptor-Connectorframeworkclasses.

Itshowshowservicehandlersareinitializedanddestroyed,and

motivateskeyframeworkdesignchoices.Italsoshowshowthis

frameworkcanbelayeredontopoftheACEReactorandACE

Taskframeworkstohandleconnectionrequestsanddata

exchangedbetweenclientandserverloggingdaemons.If

you'renotfamiliarwiththeAcceptor-Connectorpatternfrom

POSA2werecommendyoureadaboutitfirstbeforedelving

intothedetailedexamplesinthischapter.Wealsorecommend

youreadabouttheACEReactorandTaskframeworksin

Chapters3and6,respectively.



7.2TheACE_Svc_HandlerClass

Motivation

Chapter2definedaserviceasasetoffunctionalityofferedtoa

clientbyaserver.Aservicehandleristheportionofa

networkedapplicationthateitherimplementsoraccesses(or

both,inthecaseofapeer-to-peerarrangement)aservice.

Connection-orientednetworkedapplicationsrequireatleasttwo

communicatingservicehandlers—oneforeachendofevery

connection.Incidentally,applicationsusingmulticastor

broadcastcommunicationmayhavemultipleservicehandlers.

Althoughtheseconnectionlesscommunicationprotocolsdon't

cleanlyfittheAcceptor-Connectormodel,the

ACE_Svc_Handlerclassisoftenagoodchoicefor

implementingaservicehandlerandshouldbeconsidered.

Whendesigningtheservicehandlersinvolvedinaservice,

developersshouldalsotakeintoaccountthecommunication

designdimensionsdiscussedinChapter1ofC++NPv1.In

general,theapplicationfunctionalitydefinedbyaservice

handlercanbedecoupledfromthefollowingdesignaspects:

Howtheservicehandlerwasconnected(activelyor

passively)andinitialized

Theprotocolsusedtoconnect,authenticate,andexchange

messagesbetweentwoservicehandlers

ThenetworkprogrammingAPIusedtoaccesstheOSIPC

mechanisms

Ingeneral,connection/authenticationprotocolsandservice

initializationstrategieschangelessfrequentlythantheservice



handlerfunctionalityimplementedbyanapplication.To

separatetheseconcernsandallowdeveloperstofocusonthe

functionalityoftheirservicehandlers,theACEAcceptorConnectorframeworkdefinestheACE_Svc_Handlerclass.



ClassCapabilities

ACE_Svc_HandleristhebasisofACE'ssynchronousand

reactivedatatransferandserviceprocessingmechanisms.This

classprovidesthefollowingcapabilities:

Itprovidesthebasisforinitializingandimplementinga

serviceinasynchronousand/orreactivenetworked

application,actingasthetargetoftheACE_Connectorand

ACE_Acceptorconnectionfactories.

ItprovidesanIPCendpointusedbyaservicehandlerto

communicatewithitspeerservicehandler(s).Thetypeof

thisIPCendpointcanbeparameterizedwithmanyofACE's

IPCwrapperfacadeclasses,therebyseparatinglower-level

communicationmechanismsfromapplication-levelservice

processingpolicies.

SinceACE_Svc_HandlerderivesfromACE_Task(and

ACE_TaskfromACE_Event_Handler),itinheritsthe

concurrency,synchronization,dynamicconfiguration,and

eventhandlingcapabilitiesdescribedinChapters3through

6.

Itcodifiesthemostcommonpracticesofreactivenetwork

services,suchasregisteringwithareactorwhenaservice

isopenedandclosingtheIPCendpointwhenunregistering

aservicefromareactor.

TheinterfaceforACE_Svc_HandlerisshowninFigure7.2



(page208).Asshowninthefigure,thisclasstemplateis

parameterizedby:

Figure7.2.TheACE_Svc_HandlerClass



APEER_STREAMtraitsclass,whichisabletotransferdata

betweenconnectedpeerservicehandlers.Italsodefinesan

associatedPEER_STREAM::PEER_ADDRtraitthat

representstheaddressclassforidentifyingthepeerstothe

service.ThePEER_STREAMparameterisofteninstantiated

byoneoftheACEIPCwrapperfacades,suchasthe

ACE_SOCK_StreamdescribedinChapter3ofC++NPv1.

ASYNCH_STRATEGYtraitsclass,whichappliesthe

StrategizedLockingpattern[POSA2]toparameterizethe

synchronizationtraitsofanACE_Message_Queueinthe

parentACE_Taskclass.Thisparameterisofteninstantiated

byeithertheACE_NULL_SYNCHorACE_MT_SYNCHtraits

classes(page163).

Sidebar40(page165)describestheC++traitsandtraitsclass

idioms.

SinceACE_Svc_Handlerisadescendantof



ACE_Event_Handler,aninstanceofitcanberegisteredwith

theACEReactorframeworkforvarioustypesofevents.For

example,itcanberegisteredtohandleREADandWRITEevents.

Itshandle_input()andhandle_output()hookmethods

willthenbedispatchedautomaticallybyareactorwhenits

data-modesockethandleisreadytoreceiveorsenddata,

respectively.

TheACE_Svc_Handlerclasshasarichinterfacethatexports

bothitscapabilitiesandthecapabilitiesofitsparentclasses.We

thereforegroupthedescriptionofitsmethodsintothethree

categoriesdescribedbelow.

1.Servicecreationandactivationmethods.TheACE

Acceptor-Connectorframeworkcanmodifyvariousservice

handlercreationandinitializationaspectsatcompiletimeand

atruntime.Bydefault,anACE_Svc_Handlersubclassis

allocateddynamicallybyanacceptororconnectorfactory,

whichusethefollowingmethodstocreateandactivateit:

Method



Description



ACE_Svc_Handler() Constructorcalledbyanacceptororconnectorwhenitcreatesa

servicehandler



open()



Hookmethodcalledautomaticallybyanacceptororconnectorto

initializeaservicehandler



Sidebar47explainswhytheACEAcceptor-Connector

frameworkdecouplesservicehandlercreationfromactivation.

PointerstoACE_Thread_Manager,ACE_Message_Queue,

andACE_Reactorobjectscanbepassedtothe

ACE_Svc_Handlerconstructortooverrideitsdefaults.The

open()hookmethodcanperformactivitiesthatinitializea

servicehandler,suchas:



Spawningathread(orpoolofthreads)thatwillperform

serviceprocessingviathesvc()hookmethod

Registeringoneormoreeventsources,suchasinput

eventsortimeouts,withareactor



Sidebar47:DecouplingServiceHandlerCreationfromActivation

Themotivationsfordecouplingserviceactivationfromservicecreationin

theACEAcceptor-Connectorframeworkinclude:

Tomakeservicehandlercreationflexible.ACEallowsforwide

flexibilityinthewayanapplicationcreates(orreuses)service

handlers.Manyapplicationscreatenewhandlersdynamicallyas

needed,butsomemayrecyclehandlersoruseasinglehandlerforall

connections,asdiscussedinSidebar53(page240).

Tosimplifyerrorhandling.ACEdoesn'trelyonnativeC++

exceptionsforthereasonsdescribedinAppendixA.6ofC++NPv1.

Theconstructorusedtocreateaservicehandlerthereforeshouldn't

performanyoperationsthatcanfail.Instead,anysuchoperations

shouldbeplacedintheopen()hookmethod,whichmustreturn-1if

activationfails.

Toensurethreadsafety.Ifathreadisspawnedinaconstructorit's

notpossibletoensurethattheobjecthasbeeninitializedcompletely

beforethethreadbeginstorun.Toavoidthispotentialracecondition,

theACEAcceptor-Connectorframeworkdecouplesservicehandler

creationfromactivation.



Openinglogfilesandinitializingusagestatistics

Initializinglocksorotherresources

Iftheseinitializationactivitiescompletesuccessfully,open()

returns0.Ifafailureoccursandtheservicecannotorshould

notcontinue,however,open()mustreportthiseventtoits

callerbyreturning-1.Sincetheservicehandlerdoesn'tcontrol

howitwasinstantiated,afailureinopen()mustbereported

backtothecallersothatcleanupactivitiescanbeperformed.

Bydefault,theservicehandlerisdeletedautomaticallyif

open()returns-1,asshowninthevarious

activate_svc_handler()methodsoftheacceptorand



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 7. The ACE Acceptor-Connector Framework

Tải bản đầy đủ ngay(0 tr)

×