Tải bản đầy đủ - 0 (trang)
Chapter 5. Embedding Perl into Apache with mod_perl

Chapter 5. Embedding Perl into Apache with mod_perl

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

ThemodulethatprovidestheinterfacebetweenApacheandPerl.

Apache::Registry

AnApachemodulethatisprovidedasastandardpartofthe

mod_perldownload.ItgreatlyimprovestheperformanceofyourCGI

Perlscriptsbyevaluatingyourscriptsintoserversubroutinesthat

remainresidentintheApacheserver'smemory.

Apache::DBI

ThisApachemodulepoolsallofyourdatabaseconnectionsinto

memory.Byprovidingpersistentconnectionsinthisway,

Apache::DBIgreatlyimprovestheperformanceofyourPerlCGI

scripts.ThisisasupplementaryApachemodulethatyoumustobtain

fromCPAN.

Apache::OWA

Toillustratetheeffectivenessofmod_perl,we'llalsoshowhowit's

usedwiththeApache::OWAPerlApachemodule,whichconnects

mod_perltothePL/SQLWebToolkit.



5.1mod_perl

FirstcreatedbyDougMacEachernin1996,mod_perlisthemainflower

oftheApachePerlintegrationproject.ItbringsthefullpowerofthePerl

languageintotheheartoftheApacheHTTPserverbylinkingthePerl

runtimelibraryintoApache'smodularClanguageAPI.Thisislikebeing

abletoturnyourJeepintoajet-poweredhelicopterfortheweekend,and

thenbackagainonMonday,attheflickofaswitch.[1]

[1]Thesametrickisrepeated,laterinthisbook,inChapter8,whenweembedPerlintoa

PL/SQLClibrary.



OnceApacheisupandrunningwithmod_perl,thePerlinterpreter

engineisupandrunningtoo,convenientlypreloadedintoconstant

memory.Thismeansthere'snorestartoverheadeachtimeyouruna

PerlCGIscript.ThespeedimprovementbroughttoanyPerl-basedweb

sitebytheadditionofmod_perl,andthescalabilityimplications,are

enormous.ImportantApachemod_perllinksinclude:

http://perl.apache.org:

ApachePerlintegrationprojecthomepage.

http://www.modperl.com:

HomepageofLincolnSteinandDougMacEachern'shelpfulbook,

WritingApacheModuleswithPerlandC(O'Reilly&Associates,

1999).[2]

[2]TheofficialO'Reillypageishttp://www.oreilly.com/catalog/wrapmod.



http://www.refcards.com/about/mod_perl.html:

AndrewFord'sonlinereferencecardsformod_perl,alsosupported

byhisbook,themod_perlPocketReference(O'Reilly&Associates,

2000).[3]



[3]http://www.oreilly.com/catalog/modperlpr



http://theoryx5.uwinnipeg.ca/guide

AgoodentrypointtotheUniversityofWinnipeg'sexcellentpageson

mod_perlandCGIscripting.Thisguideisparticularlyhelpfulin

explainingthecomplexissueofportingCGIscriptsto

Apache::Registryandmod_perl.

http://mathforum.org/epigone/modperl

KenWilliam'ssuperbmod_perltopicsarchive.



5.1.1Installingmod_perlonUnix

Beforeyoucantestyourmod_perlinstallation,youmustmakesurethat

thePerlLWP.pmmoduleisavailable.DevelopedbyGisleAas,this

moduleprovidesa"LibraryforWWWaccessinPerl";itconsistsofawide

rangeofrelatedPerlmodulesdesignedtohelpsimplifyPerlInternet

clientconnections.Notonlyisthismoduleusefulforourlatermod_perl

test,it'sinvaluableformanyPerlInternetrequirements.We'llcomeback

toLWP.pmagainandagainaswediscussPerlandtheWebinthenext

fewchapters.

5.1.1.1LWP-LibraryforWWWaccessinPerl

ThemainfocusofLWPistoprovideclassesandfunctionsallowingthe

creationofInternetPerlclients.Thelibraryalsocontainsmodulesfor

moregeneraluse,evenmakingitpossibletocreatesimpleHTTP

servers.

Fortunatelyforus,GisleAashascollatedalloftherelatedLWPmodules

intoasingledownload,libwww-perl-5.64.tar.gz(oritslatestderivative).

However,LWPitselfreliesuponseveralotherrelatedmodules,as

detailedintheappropriateinstallationorder,inTable5-1.Ifyouwantto

installthesebyhand,downloadthelatesttarballsandprocessthemin



theusualperlMakefile.PLmanner.Alternatively,we'llacceptalittle

sneakyautomationhere.Thereisaveryhandycommandyoucanrun,

whichshouldloadeverythingrequiredforLWP,directlyovertheInternet,

injustoneline:

$perl-MCPAN-e'installBundle::LWP'

Anevensneakierroutineloadsthewholeofmod_perlandmanyofits

relatedmodules:

$perl-MCPAN-e'installBundle::Apache'

Thiswillloadeverymoduleyourequire,includingLWP.However,we'll

stillgothroughthemanualroute;thisway,wecandescribeallthebumps

intheroadandconfigureeverythingproperly.TheCPANmoduleisa

greattool,butitcansometimesbeunreliable,aswediscussedin

Chapter2,particularlywhenCPANmodulesarenotpreconfiguredby

theirauthorsinexactlythewaythatCPANisexpecting(manyInternet

modulesfallintothiscategory).

Table5-1.ModulesrequiredtoinstallLWP

Perlmodule



Digest::MD5



Description/downloadpage



PerlinterfacetotheMD5messagedigest

algorithm[4]

http://www.cpan.org/authors/id/GAAS



HTMLparserclassmoduleforPerl

HTML::Parser

http://www.cpan.org/authors/id/GAAS



Libnet(e.g.,libnet1.0704.tar.gz)



ManyrelatedPerlmodules

http://www.cpan.org/authors/id/GBARR



MIME::Base64



ModuleforencodinganddecodingofBase64

strings

http://www.cpan.org/authors/id/GAAS



UniformResourceIdentifiersmodule

URI

http://www.cpan.org/authors/id/GAAS



DatatableshandlerusefulforparsingHTML

HTML::Tagset

http://www.cpan.org/authors/id/S/SB/SBURKE



LWP(e.g.,libwww-perl5.64.tar.gz)



ThecompletelibraryforWWWaccessinPerl

http://www.cpan.org/authors/id/GAAS



[4]TolearnmoreaboutRonaldL.Rivest'sMD5messagedigestalgorithm,checkout:

http://theory.lcs.mit.edu/~rivest/homepage.html



TwootherCPANpackagesthatpeopleoftenusealongsideLWPinclude:

Storable

PersistentdatastorageusedtomakeHTTPlessstateless.

http://www.cpan.org/authors/id/A/AM/AMS

HTML-SimpleParse

AbarebonesHTMLparser.

http://www.cpan.org/authors/id/KWILLIAMS

5.1.1.2SSLSecureSocketsLayer

Ifyouneedenhancedsecurityatyoursite,youmayalsowanttousethe



popularSecureSocketsLayer(SSL)program.BeforeyouinstallLWP(or

re-installit),besuretocheckouttheprogramsandPerlextensionslisted

inTable5-2.

Table5-2.OptionalSSLmodulesforusewithLWP

PerlmoduleorC

program



Description/downloadpage



OpenSecureSocketsLayerprogram

OpenSSL

http://www.openssl.org



Crypt::SSLeay[5]



OpenSSLPerlglueprovidinghttpssupporttoLWP

http://www.cpan.org/authors/id/C/CH/CHAMAS



Net::SSLeay



PerlextensionforusingOpenSSLandhttps

sockets

http://www.cpan.org/authors/id/SAMPO



SSLsocketinterfaceclass

IO::Socket::SSL

http://www.cpan.org/authors/id/A/AS/ASPA



[5]SSLeayisnamedaftertheoriginal"SecureSocketsLayerworkbyEricA.Young."



5.1.1.3Installingmod_perl

Beforewebeginourinstallationofmod_perl,werecommendthatfor

securityreasonsyoushutdownallyourApacheprocesses,andthen

savetheentireApacherootstructure,perhapsinatarball,before

continuing.Wecanalwaysrevertbacktothissavedstructurelateron,

shouldmod_perlproveproblematic.



Todotheactualmod_perlinstallationonUnix,firstdownloadthelatest

andgreatestgoodsbyvisitingDougMacEachern'sCPANpage:

http://www.cpan.org/authors/id/DOUGM

Thenfollowthesesteps:

1. Beginwiththetime-honoredroutine:

$gzip-dmod_perl-1.26.tar.gz

$tarxvfmod_perl-1.26.tar

$cdmod_perl-1.26

$viREADMEINSTALL

Thereexistsabewilderingarrayofoptionsyoucanusetobuild

mod_perl.You'llfindallofthemdetailedintheINSTALLfile.We'rejust

goingtogoforthesimpleinstallofcompilingeveryoptionavailable,with

thecleverEVERYTHING=1switch:



$perlMakefile.PLEVERYTHING=1APACHE_PREFIX=/usr/local/apache

ThefirstthingMakefile.PLwilltrytodoisfindasourcedirectoryfor

Apachewithinthelocalvicinity.Thisshouldbeavailablefromthe

installationweperformedinthepreviouschapter:

Configuremod_perlwith../apache_1.3.24/src?[y]y

IfalocalApachedirectoryisunavailable,you'llbeaskedtosupplyone.

Answeraccordingly:



PleasetellmewhereIcanfindyourapachesrc[]
You'llthenbeaskedifyouwanttobuildthehttpdexecutableinthe

Apachesourcedirectoryyounominated.Wesaidyes:

ShallIbuildhttpdin../apache_1.3.24/srcforyou?[y]



(OnsomeUnixsystems,includingsomeSolarisflavors,itmaybebestto

alwaysusefullyqualifiedpathnames,becauseofsomeproblemswith

includepaths.Ifmod_perlfailstobuildasexpected,thoroughlycheckall

thedocumentationthatcomeswithmod_perlaswellastheonline

resourcesmentionedatthestartofthischapter,particularlythetopics

archive.)

Lotsofinformationwillthenappear,butassumingnoproblems,wecan

goaheadwiththecompilation:

$make

Themaketeststepishighlyrecommendedifyou'veloadedLWP.In

thefollowingexample,weincludeonlyafewlinesoftypicaloutput,but

muchmorethanthisshouldappear.Expectsometeststobeskipped

dependingonyourplatform:

$maketest

...



internal/table......ok



internal/taint......ok

Alltestssuccessful,6testsskipped.

Files=34,Tests=390,23wallclocksecs

(18.68cusr+1.75csys=20.43CPU)

Ifanytestsshouldfail,re-runmaketest,butthistimeinverbosemode:

$maketestTEST_VERBOSE=1

Beforeinstalling,goto/usr/local/apache/bindirectoryandsavetheold

httpdfile(justincase):



$cd/usr/local/apache/bin

$mvhttpdhttpd.old

Wecannowdotheinstall:

$makeinstall

Ifyouspecifieditearlier,youshouldalsofindanewhttpdlivingunder

theApachesourcedirectory,whichyoumayhavesuppliedonthe

Makefile.PLstep.Thiswillbeapproximatelyfourtimesthesizeofyour

oldhttpd.CopyittothemainApacheexecutables'bin:

$cd../apache_1.3.24/src

$cphttpd/usr/local/apache/bin

$cd/usr/local/apache/bin

$ls-lahttpd*

-rwxr-xr-x1rootroot1497133Apr115:47httpd



-rwxr-xr-x1rootroot410220Apr115:45httpd.o

Asasanitycheck,toensurethatwe'vesuccessfullyloadedmod_perl

intothehttpdbinary,trythefollowingcommand:

$./httpd-l

Compiled-inmodules:

...

mod_auth.c

mod_setenvif.c



mod_perl.c#Bingo!!!:-)

(Ifyoudidn'tbuildApacheandmod_perlyourself,thereisachancethat

mod_perlwillbedynamicallyloaded(followingtheDSObuildpattern).In

thiscase,itwon'tshowuponhttpd-l,whichshowsonlystatically

compiled-inmodules.)

5.1.1.4Specifyingthemod_perlApachelibrary

Afterarefreshingrest,wecanbeginagainbywritingourfirstmod_perl

serverscriptmodule,HelloApache.pm.(We'lldealwiththeconversionof

ordinaryCGIscriptslater.)Firstofall,weneedtoestablishwhereour

mainmod_perlApachelibrarywillbe.Wesuggestthatyoucreatea

../lib/perl/Apachedirectory:

$cd/usr/local/apache

$mkdir-plib/perl/Apache

Wenowhavetwooptionsfortellingmod_perlwherethislibrarywillbe

whenApachestartsrunning.Thefirstistoaddthefollowingline

somewherenearthetopofourhttpd.confconfigurationfile:

PerlSetEnvPERL5LIB/usr/local/apache/lib/perl

However,becausethisapproachaddsalittleoverheadtoeachHTTP

request,werecommendthesecondoptioninstead.Gotoyourconf

directoryandeditanewPerlfile:

$cd/usr/local/apache/conf

$vistartup.pl

$chmod755startup.pl

CreatethePerlscriptshowninExample5-1asyoursuperuser(to

ensurelatersecurity).Changedirectives,whereappropriate,suchasthe



locationoftheperlprogramintheshebangline(noticethatwe've

commentedoutApache::DBI,whichwe'llbecoveringlater):

Example5-1.startup.plApachemod_perlinitializationscript

#!/usr/bin/perl

#Setuptheincludepathtogetournewlib/perldirectory

BEGIN{

useApache();

uselibApache->server_root_relative('lib/perl');

}



#Insertthemostrequiredmodules



useApache::Registry();

useApache::Constants();

#useApache::DBI();#We'llgettothislater!:-)

useLWP();

useCGIqw(-compile:all);

useCGI::Carp();

1;#Mustfinishwithatruevalue



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

Chapter 5. Embedding Perl into Apache with mod_perl

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

×