Академический Документы
Профессиональный Документы
Культура Документы
OracleAPIGatewayKeyPropertyStoreUserGuide
11gRelease2(11.1.2.4.0)
July2015
OracleAPIGatewayKeyPropertyStoreUserGuide,11gRelease2(11.1.2.4.0)
Copyright1999,2015,Oracleand/oritsaffiliates.Allrightsreserved.
Thissoftwareandrelateddocumentationareprovidedunderalicenseagreementcontainingrestrictionsonuseand
disclosureandareprotectedbyintellectualpropertylaws.Exceptasexpresslypermittedinyourlicenseagreementorallowed
bylaw,youmaynotuse,copy,reproduce,translate,broadcast,modify,license,transmit,distribute,exhibit,perform,
publish,ordisplayanypart,inanyform,orbyanymeans.Reverseengineering,disassembly,ordecompilationofthis
software,unlessrequiredbylawforinteroperability,isprohibited.
Theinformationcontainedhereinissubjecttochangewithoutnoticeandisnotwarrantedtobeerror-free.Ifyoufindany
errors,pleasereportthemtousinwriting.
IfthissoftwareorrelateddocumentationisdeliveredtotheU.S.GovernmentoranyonelicensingitonbehalfoftheU.S.
Government,thefollowingnoticeisapplicable:
U.S.GOVERNMENTRIGHTSPrograms,software,databases,andrelateddocumentationandtechnicaldatadeliveredtoU.S.
Governmentcustomersare"commercialcomputersoftware"or"commercialtechnicaldata"pursuanttotheapplicable
FederalAcquisitionRegulationandagency-specificsupplementalregulations.Assuch,theuse,duplication,disclosure,
modification,andadaptationshallbesubjecttotherestrictionsandlicensetermssetforthintheapplicableGovernment
contract,and,totheextentapplicablebythetermsoftheGovernmentcontract,theadditionalrightssetforthinFAR52.227-
19,CommercialComputerSoftwareLicense(December2007).OracleUSA,Inc.,500OracleParkway,RedwoodCity,CA
94065.
Thissoftwareisdevelopedforgeneraluseinavarietyofinformationmanagementapplications.Itisnotdevelopedor
intendedforuseinanyinherentlydangerousapplications,includingapplicationswhichmaycreateariskofpersonalinjury.If
youusethissoftwareindangerousapplications,thenyoushallberesponsibletotakeallappropriatefail-safe,backup,
redundancy,andothermeasurestoensurethesafeuseofthissoftware.OracleCorporationanditsaffiliatesdisclaimany
liabilityforanydamagescausedbyuseofthissoftwareindangerousapplications.
OracleisaregisteredtrademarkofOracleCorporationand/oritsaffiliates.Othernamesmaybetrademarksoftheirrespective
owners.
Thissoftwareanddocumentationmayprovideaccesstoorinformationoncontent,products,andservicesfromthirdparties.
OracleCorporationanditsaffiliatesarenotresponsibleforandexpresslydisclaimallwarrantiesofanykindwithrespectto
third-partycontent,products,andservices.OracleCorporationanditsaffiliateswillnotberesponsibleforanyloss,costs,or
damagesincurredduetoyouraccesstooruseofthird-partycontent,products,orservices.Thisdocumentationisin
prereleasestatusandisintendedfordemonstrationandpreliminaryuseonly.Itmaynotbespecifictothehardwareonwhich
youareusingthesoftware.OracleCorporationanditsaffiliatesarenotresponsibleforandexpresslydisclaimallwarrantiesof
anykindwithrespecttothisdocumentationandwillnotberesponsibleforanyloss,costs,ordamagesincurredduetothe
useofthisdocumentation.
Theinformationcontainedinthisdocumentisforinformationalsharingpurposesonlyandshouldbeconsideredinyour
capacityasacustomeradvisoryboardmemberorpursuanttoyourbetatrialagreementonly.Itisnotacommitmentto
deliveranymaterial,code,orfunctionality,andshouldnotberelieduponinmakingpurchasingdecisions.Thedevelopment,
release,andtimingofanyfeaturesorfunctionalitydescribedinthisdocumentremainsatthesolediscretionofOracle.
Thisdocumentinanyform,softwareorprintedmatter,containsproprietaryinformationthatistheexclusivepropertyof
Oracle.YouraccesstoanduseofthisconfidentialmaterialissubjecttothetermsandconditionsofyourOracleSoftware
LicenseandServiceAgreement,whichhasbeenexecutedandwithwhichyouagreetocomply.Thisdocumentand
informationcontainedhereinmaynotbedisclosed,copied,reproduced,ordistributedtoanyoneoutsideOraclewithout
priorwrittenconsentofOracle.Thisdocumentisnotpartofyourlicenseagreementnorcanitbeincorporatedintoany
contractualagreementwithOracleoritssubsidiariesoraffiliates.
27July2015
Contents
Preface 6
Whoshouldreadthisdocument 6
Howtousethisdocument 6
1 Introduction to KPS 8
KPSarchitecture 8
KPSdatastores 9
KPSclientapplications 9
WhentouseaKPS 9
Further information 72
Glossary 73
l Databaseconceptssuchastables,rows,andkeys
l APIGatewayconfigurationanddeployment
l APIGatewayselectors
l Usingcommandlinetools
l Databaseconfigurationwheredatabasestorageisrequired
FormoredetailsonAPIGatewayconfigurationandselectors,seetheAPIGatewayPolicyDeveloper
Guide.
l IntroductiontoKPSonpage8providesanoverviewoftheKPSarchitectureandfeatures.
l GetstartedwithKPSonpage10explainshowtodevelopanexampleKPStableformanaging
simpleuserinformation.
l ConfigureKPSinPolicyStudio onpage20providesmoredetailonhowtodefinegeneralKPS
configurationusingtheP olicyStudiographicaltool.
l AccessKPSdatausingselectorsonpage26explainshowtoaccessdatainpoliciesonthe
APIGatewayatruntime.
l ManageaKPSusingkpsadminonpage28explainshowtomanageaKPS,independentofdata
source.
l ConfigureApacheCassandraKPSstorageonpage34explainshowtostoreKPSdatainthe
defaultCassandraserverembeddedintheAPIGateway.
l ConfiguredatabaseKPSstorageonpage47explainshowtostoreKPSdatainarelational
database(forexample,Oracle,MySQL,IBMDB2,orMicrosoftSQLServer).
l Configurefile-basedKPSstorageonpage59explainshowtostoreKPSdatainadirectoryonthe
filesystem.
KPS architecture
Thefollowingdiagramshowsasimplerole-basedarchitecture:
AKPSistypicallyusedtostorepropertyvaluesthatareusedinp oliciesrunningonanAPIGateway.
KPSdataisinjectedintopoliciesusingselectorsthatarefirstcreatedinPolicyStudiobypolicy
developers.Selectorsareevaluatedandexpandeddynamicallyatruntime.Forexample,aKPStable
couldcontainauthorizationtokensfordifferentusers.Apolicycouldlookupthetokenforthe
currentuserandinsertitintoanHTTPrequest.
KPStablesareorganizedintocollections.Thetablesinacollectiontypicallyhavesomesortof
relationshiptooneanother.Forexample,theOAuthcollectioncontainsasetoftablesthatstoreall
OAuth-relateddata.EveryKPStableisassignedanaliassothatitc anbeeasilyreferredtoinapolicy
oraRESTrequest.KPSc ollectionsandtablescanbecreatedbypolicydevelopersusingP olicy
Studio.
KPSadministratorscanusetheAPIGatewayManagerwebconsoletoviewandmodifyKPSdataat
runtime.Thisisabusinessoroperationalrolethatmanagesdynamicpolicyconfigurationdataina
KPS(forexample,customerdetails,authorizationlevels,orquotas).Thismeansthatthis
informationdoesnotneedtobeconfiguredatdesigntimebypolicydevelopers.
FormoredetailsonAPIGatewayarchitecture,components,androles,seetheAPIGateway
ConceptsGuide.
l PolicyStudio:EnablespolicydeveloperstocreateKPScollectionsandtables,andtoconfigure
datasources.
l APIGatewayManager:Includesavisualweb-basedinterfacetoenableKPSadministratorsto
viewandmodifyKPSdataatruntime.
l kpsadminc ommand:SupportsKPSdataentryandotheradministrativefunctions.Itisdesigned
foruseinadevelopmentenvironment.
l KPSRESTAPI:Enablesremotep rogrammaticclientstoreadandwriteKPSdata.
l DataiscommontoallAPIGatewaysinanAPIGatewaygroup.KPSisnotsuitablefordatathatis
specifictooneparticularAPIGateway.
l Thedataschemaisrelativelysimple.EachKPStableisassumedtobeindependentofallothers,
andreferentialintegrityacrosstablesisnotsupported.
l DatacanchangewhileAPIGatewaysarerunning.UpdatingCassandra-backedordatabase-
backedKPStablesdoesnotrequireanAPIGatewayrestart.Changeabledatashouldthereforebe
storedinKPSinsteadofhard-codedintop olicies.
l Queriesalwaysinvolvelookingupakeyvalueinatabletoretrieveasingleobject.Thisisthe
usagemodelsupportedbyselectors.Adhocqueriesthatinvolvesearchingfornon-key
propertiesarenotsupported.
l Multi-operationtransactionsarenotrequired.EachreadorwritetoaKPStableisconsidereda
standaloneoperation.Lockingorrollbackacrossmultipleoperationsarenotsupported.
Example KPStable
ThefinalstructureoftheexampletableisdisplayedinPolicyStudioasfollows:
Thistablestructureisdescribedasfollows:
1. EnsurethatanAPIGatewayandanAdminNodeManagerarerunning.
2. StartPolicyStudio,andconnecttotheAdminNodeManager.
Formoredetails,seetheAPIGatewayInstallationGuide.
1. Definewherethedatawillbestored.
2. DefinetheKPStable.
3. Defineapolicythataccessesthetable.
4. Deploytheconfiguration.
1. InthePolicyStudiotree,right-clickthenewly-createdSamplescollection,andselectAdd
Table:
2. Inthedialog,enteraNameofUser,andprovideaDescription.
3. ClickAddtoassignanaliasofUsertothistable.Atablemusthaveatleastonealias.
4. Nextdefinethetablestructure.Thisconsistsofthetablecolumnsandthedatatypestoredin
eachcolumn.SelecttheUsertableandStructuretab,andclickAdd:
Note agehasanInteger(numeric)Type.AlltheothercolumnsareString.
5. WhenyouselecttheUsertable,youshouldhavethefollowingstructure:
6. Youwanttheemailfieldtobetheprimarykeyforthetable,soselectPrimary Keyforthis
field.
7. Youwantthepasswordfieldtobeencryptedwhenstoredinthedatasource,soselect
Encryptedforthisfield.
1. AddatestpolicywithaSet MessagefilterfromtheConversionfiltercategory.
2. Right-clickthefilter,andsetitastheStartfilterforthepolicy.
3. EnterafilterContent-Typeoftext/plain.
4. Enterthefollowing Message Bodyforuseinthepolicy:
========================
User
===
Email:${kps.User[http.querystring.id].email}
FirstName:${kps.User[http.querystring.id].firstName}
LastName:${kps.User[http.querystring.id].lastName}
Age:${kps.User[http.querystring.id].age}
========================
ThesesettingsaredisplayedasfollowsintheSet Messagefilter:
Themessagebodyvaluearespecifiedusingselectors,whichareevaluatedandexpanded
dynamicallyatruntime.Forexample,theuserageisspecifiedusingthefollowingselectorstring:
${kps.User[http.querystring.id].age}
Theselectorpartsareexplainedasfollows:
${ Indicatesthestartoftheselectorusinga{bracket.
kps SpecifiesthatselectorshouldqueryaKPStable.
.User Specifiesthealiasofthetabletoquery(inthiscase,User).
[ Indicatesthestartofatablepropertyreferenceusinga[bracket.
http.querystring.id ThisisadynamicquerybasedonanHTTPquerystringparameterof
id.Theprimarykeyvalueisretrievedfromthisparameter.Therow
withthiskeyvalueisreturnedfromtheUsertableifitexists.
] Indicatestheendofatablepropertyreferenceusinga]bracket.
.age Retrievestheagecolumn.
} Indicatestheendoftheselectorusinga}bracket.
5. Setupapathtothispolicy.Inthisexample,thepathis/kpsGetViaSelector:
ThispushestheconfigurationtotheAPIGatewaygroup.
Tip Ifyoudeployanincorrectconfiguration(forexample,specifyanincorrectprimarykey,
propertytype,orname)youcanusethekpsadmincommandtodropthetableinstorage.
Formoredetails,seeManageaKPSusingkpsadminonpage28.
Performthefollowingsteps:
1. ToaccessAPIGatewayManagerinyourbrowser,gotohttps://localhost:8090.
2. SelecttheSettings>Key Property Storestab.
3. SelecttheSamples>Usertable.
5. ClickSavetosavearecord.
Forexample,thetableshouldlookasfollows:
http://localhost:8080/kpsGetViaSelector?id=patrica.allen@acme.com
ThisURLspecifiestheuserID(email)aspatrica.allen@acme.com
Youmustspecifyanemailthatexistsinyourdata.Forexample:
Note Ifyouenteranemailthatdoesnotexist,youwillsee[invalidfield]results.For
example:
Note ThissettingenablesdebugtracingfortheentireAPIGateway,andnotjustfortheKPS.
FormoredetailsonAPIGatewaytracingandlogging,seetheAPIGatewayAdministratorGuide.
l ConfigureApacheCassandraKPSstorageonpage34
l ConfiguredatabaseKPSstorageonpage47
l Configurefile-basedKPSstorageonpage59
ThefollowingshowsaKPScollectioncreatedinPolicyStudio:
1. Right-clickaKPScollectioninthePolicyStudiotree,andselectAdd Table.
2. Specifythefollowingsettingsinthedialog:
l Name:AKPStablemusthaveauniquenameinthecollection.
l Description:Youcanprovideanoptionaldescription.
l Override the default data source with the following:Youcanspecifyadifferent
datasourcethanthecollectionifrequired.
3. Whenthetableiscreated,ifrequired,youcanusetheOverride the default data source
with the followingsettingtospecifyadifferentdatasourcethanthecollection:
4. Finally,clicktheStructuretab,andclickAddtodefinethestructureofthedatastoredinthe
table.Fordetailsonsupportedtypesandkeys,seethefollowing:
l KPStablestructureonpage22
l Querytablesusingpropertiesandkeysonpage23
KPS aliases
KPStablesareaccessedbyalias.Atablemusthaveatleastonealias.Aliasesmustbeuniqueinan
APIGatewayg roup.Youalsocanusetheoptionalaliasprefixforthecollectiontohelpensurethat
thealiasisunique.
Thefullaliasofatableisthecollectionaliasprefixandthetablealiascombined.Forexample,
samplesandUserg ivessamplesUser.Ifunspecified,thedefaultvalueofthealiasprefixforthe
collectionisanemptystring(forexample,Usero nly).
Type Description
String Javatype.
Boolean
Byte
Integer
Long
Double
List JavaListofanyoneoftheaboveJavatypes.
Map JavaMap.ThekeycanbeanyoneoftheaboveJavatypes.Thevaluecanbe
anyoneoftheaboveJavatypes.
Indexedpropertiesincludeprimarykeys,secondarykeys(whichareindexedimplicitly),ando ther
propertiesthatyouexplicitlyselectasIndexedinPolicyStudio.
Primary key
Youcandirectlyaccessanyrecordusingitsprimarykey.Allrecordsinthetablemustbeaccessible
usingauniqueprimarykey.YoumustselectonePrimary KeypertableinPolicyStudio.The
specifiedpropertymustbeanindexableproperty.Primarykeyvaluescannotbenull.
Secondary key
Youcanoptionallyaccessanyrecorddirectlyusingauniquesecondarykey.Thesecondarykeycan
beasimplekey(forexample,email) oracompositekey(forexample,appIdo rcompanyId) .
Thespecifiedpropertiesmustbeindexableproperties.Thesecondarykey(andpartsofacomposite
secondarykey)cannotbenull.Youcanspecifyonesecondarykeypertable.Acommonusecaseis
tospecifyaninternaluniqueIDasasprimarykey,andanexternaluserfacingIDasasecondarykey.
Forexample,idforinternalprimarykey,andemailforexternalIDasasecondarykey.
Selector access
YoucanaccessrecordsinaKPStableusinganAPIGatewayselector.Ifasecondarykeyisdefined
forthetable,youmustspecifyallsecondarykeyvaluesintheselector.Ifnosecondarykeyis
defined,youmustspecifytheprimarykeyvalueinstead.InPolicyStudio,youcanspecifya
secondarykeyoraprimarykeyintheUse the following property name(s) for looking up a
table from a selectorfield.
ForexamplesofaccessingKPStablesusingselectors,seethefollowing:
l GetstartedwithKPSonpage10
l AccessKPSdatausingselectorsonpage26
l ConfiguredatabaseKPSstorageonpage47
Auto-generated properties
InPolicyStudio,youcanselectthatStringfieldsareAutogenerated.Whenarecordiscreated,a
Javajava.util.UUIDisassignedtothefieldifitisempty.
Encrypted properties
InPolicyStudio,youcanselectthatStringfieldsareEncryptedinstorage.However,fields
selectedasIndexed(includingprimaryandsecondarykeyfields)cannotbeencrypted.Youcan
entervaluesforencryptedfieldsusingtheAPIGatewayManagerorthekpsadminc ommand.These
valuesareforwardedtotheAPIGatewayintheclearusingtheKPSRESTservice,andencrypted
beforebeingwrittentostorage.
Note TheKPSRESTservicemustalwaysrunoverHTTPS(thedefault).Youmustsetan
encryptionpassphrasefortheAPIGatewaygroup,becausethisisusedintheencryption
process.Formoredetails,seetheAPIGatewayAdministratorGuide.
WhenKPStablesareaccessedusingAPIGatewayselectorsatruntime,encryptedfieldsare
automaticallydecrypted.Selectorsdonotneedtobeawarethatparticularfieldsinatableare
encryptedinstorage.
WhenKPStablesarereadusingtheRESTAPI,dataisalwaysreturnedinitsencryptedstate.
SometimesyoumayneedtoviewdecrypteddatatohelpdebugproblemsonanAPIGateway.You
candothisusingdebugmodeinkpsadmin.Thisrequiresyoutoenterthepassphraseforthe
APIGatewaygroup.
Ifthein-builtKPSencryptionmechanismdoesnotsuityourneeds,youcanencryptandd ecrypt
dataoutsidetheKPS.Inthiscase,youshouldnotselectpropertiesinKPStablesasencryptedin
PolicyStudio.Encrypteddatamustbestring-encodedforstorage(forexample,base64-encoded).
Selectorsthataccessthedatamustdecryptitthemselves(forexample,usingad edicatedd ecryption
filterinPolicyStudio).
${kps.alias[key].property
Thepartsintheselectoraredescribedasfollows:
Selector Description
part
${ Indicatesthestartoftheselectorusinga{bracket.
kps SpecifiesthatselectorshouldqueryaKPStable.
[ Indicatesthestartofatablepropertyreferenceusinga[bracket.
key Thekeyvaluetoquerythetable(forexample,http.querystring.id).
] Indicatetheendofatablepropertyreferenceusinga]bracket.
. Thefieldtoretrievefromthereturnedrow(forexample,age).
property
} Indicatetheendoftheselectorusinga}bracket.
Youcanalsouseacompositekey,forexample:
${kps.alias[key1][key2].property}
ThefollowingtableshowsmoreexamplesofKPSselectors:
Selector Description
${kps.User l GetrowfromKPStablewithUseralias
[http.querystring.id].firstName}
l UsekeysuppliedinHTTPquerystring
(id)
l ReturnfirstNamefieldofrow
${kps.User l GetrowfromKPStablewithUseralias
["kathy.adams@acme.com"].age}
l Useconstantkey
"kathy.adams@acme.com"with
quotationmarks
l Returnagefieldofrow
${kps.User l GetrowfromKPStablewithUseralias
[http.querystring.firstName]
l UsekeysuppliedinHTTPquerystring
[http.querystring.lastName].email}
(firstNameandlastName)
l Returnemailfieldofrow
Formoredetailsonselectors,seetheAPIGatewayPolicyDeveloperGuide.
Note Inproduction,youshouldusedatasource-specifictoolsandadministrationproceduresfor
databackup,restore,security,optimization,monitoring,andsoon.
Start kpsadmin
Fromacommandprompt,startkpsadmin.Forexample:
Windows
INSTALL_DIR\Win32\bin\kpsadmin.bat
UNIX
INSTALL_DIR/posix/bin/kpsadmin
kpsadmin-v
l APIGatewaygrouptouse
l AdminAPIGatewayinthatgroupthathandlesKPSrequests
Note ThisistheAdminAPIGatewayusedforKPSpurposesonly,andshouldnotbeconfused
withtheAdminNodeManager.
l KPScollectiontouseinthegroup
l KPStabletouseinthecollection
Youcanchangethisselectionatanytime.
Table operations
Thekpsadmintableoperationsareasfollows:
CreateRow Createarowintheselectedtable.
ReadRow Readarowbyprimarykeyintheselectedtable.
UpdateRow Updatearowintheselectedtable.Therowisspecifiedbyprimarykey.
DeleteRow Deletearowintheselectedtable.Therowisspecifiedbyprimarykey.
ListRows Listallrowsinthetable.
Table Description
Administration
Clear Clearallrowsinthetable.
Backup Backupthetabledata.ThegeneratedbackupUUIDisrequiredwhen
restoringthedata.
Restore Restoretabledata.Thetablemustbeemptybeforeyourestore.
Re-encrypt Re-encryptencrypteddatainthetable.Usethisoptionwhenthe
encryptionpassphrasehasbeenchangedfortheAPIGatewaygroup.
Thetablewillbeofflineafterapassphrasechange.
Youmustusethisoptiontore-encryptthedata.Youmustentertheold
APIGatewaypassphrasetoproceed.Dataisre-encryptedusingthe
currentAPIGatewaypassphrase.
Table Description
Administration
Re-create Recreateatable.Thisisusefulindevelopmentifyouwishtochange
thetablestructure.Thisprocedureinvolvesdroppingandrecreating
thetable,soallexistingdatawillbelost.Thestepsareasfollows:
1. Backup(optional).
Backupthedataifnecessaryusingkpsadmin.
2. Deploythecorrectconfiguration.
FirstredeploythecorrectconfigurationusingPolicyStudio.This
mayresultinsomeKPSdeploymenterrors.Thechangesyouhave
mademaynolongermatchthestoreddatastructure.
3. Re-createthetablewiththecorrectconfiguration.
SelecttheRe-createoptionusingkpsadmin.
4. Restore(optional)
Restorethedatausingkpsadmin.Ifyouhavemadekeyorindex
changes,thedatashouldimportdirectly.Ifyouhavemademore
extensivechanges(forexample,renamingfieldsorchanging
types),youmustupgradethedatatomatchthenewtable
structure.
TableDetails Displayinformationaboutatableanditsproperties.
Collection Description
Administration
ClearAll Clearalldatainalltablesinthecollection.
BackupAll Backupalldatainalltablesinthecollection.
RestoreAll Restorealldatainalltablesinthecollection.
Re-encryptAll Re-encryptalldatainalltablesinthecollection.
CollectionDetails Displayinformationaboutalltablesinthecollection.
Cassandra Description
Administration
ShowConfiguration ShowthecurrentconfigurationfortheKPS-embeddedstorageservice
(ApacheCassandra).
General Description
ChangeTable Changethecurrentlyselectedtable.
ChangeCollection Changethecurrentlyselectedcollection,andselectatableinthat
collection.
ChangeGroupor Refreshtheconfiguration,andchangethecurrentlyselected
APIGateway APIGatewaygroupandKPSAdminAPIGateway.
DebugMode Enableordisabledebugmode.Toenable,youmustenterthe
APIGatewaygrouppassphrase.EncrypteddatainKPStablesisthen
shownintheclear.Thiscanbeusefulfordebuggingissuesonthe
APIGateway.
ThebackupUUIDishighlightedinthefollowingexample:
2. SelectthecollectionData Sourcestab.
3. ClickAdd>Add Fileatthebottomright.
4. EnterafiledatasourceNameandDescription.
5. EnteraDirectory Path(forexample,${VINSTDIR/kps/samples).
Tip Youcaninclude${VINSTDIR}or${VDISTDIR}toindicatetheAPIGatewayinstance
directoryorinstalldirectoryrespectively.Makesuretouse\onWindowsor/onUNIX.If
thedirectorydoesnotexist,itisautomaticallycreated.
6. SelectthecollectionPropertiestab.
7. ChangethecollectionDefault data sourcetousethenewdatasource:
1. Usingkpsadmin,selectoption22)RestoreAll.
2. EnterthebackupUUIDnotedinstep1.Forexample:
AsingleAPIGateway,non-HAsystemdoesnotrequireanyconfiguration.Foranoverviewofthis
configuration,seeSinglenode,out-of-the-box,non-HAconfigurationonpage37.
ThisguidedescribesusecasestestedwithAPIGateway.Forproductiondeployments,seethe
ApacheCassandraandDatastaxdocumentation.Youshouldensurethatyouarefamiliarwith
Cassandraconfigurationandadministrationrequirements.
Note nodetoolrepairmustberunatregularintervalstoensurethatdeleteddataremains
deletedinacluster.Forexampleusecases,seeApacheCassandraoperationsfor
APIGatewayonpage69.
Cassandra configuration
IntheAPIGateway,Cassandraconfigurationanddataarestoredinthefollowingdirectory:
INSTALL_DIR/groups/<group-id>/<instance-id>/conf/kps/cassandra
YoucanconfigureAPIGatewaytorunanembeddedCassandraserverandclient.TheCassandra
configurationisstoredasfollows:
File Description
cassandra.yaml Cassandraserverconfigurationfile.
client.yaml Cassandraclientconfigurationfile.
jvm.xml JMXconfigurationrequiredforCassandraadministration.
commitlog Cassandradatadirectory.
data Cassandradatadirectory.
saved_caches Cassandradatadirectory.
Cassandra ports
ThissectiondescribestheavailableportsintheCassandraconfigurationfiles:
cassandra.yaml
TheCassandraserverconfigurationfileincludesthefollowing:
client.yaml
TheCassandraclientconfigurationfileincludesthefollowing:
jvm.xml
TheJMXconfigurationfileincludesthefollowing:
Note Youmustensurethefollowing:
l conf/kps/cassandradirectoryisincludedaspartofyourAPIGatewaybackupplan.
Formoredetailsonbackup,seetheAPIGatewayAdministratorGuide.
l Changestocassandra.yaml,client.yaml,andjvm.xmlrequireanAPIGateway
restart.
l cassandra.yamlisuniquetoeachAPIGatewayinstancebecauseitcontainsaunique
listen_addressforeachAPIGateway.
Secure ports
Thefollowingfirewallrulesapplyforsecuringports:
l storage_port:listen_addressmustbeavailabletootherhostsinthecluster.
l rpc_port:rpc_addressandcom.sun.management.jmxremote.portcanberestrictedto
localaddresses.
l UseSSHtogettothemachinetorunCassandraclientandadministrationtoolssuchas
nodetoolandcassandra-cli.
Cassandra logging
CassandraloggingissettoERRORlevelbydefault.ToenableCassandradebugoutput,performthe
followingsteps:
1. Editthefollowingfile:
INSTALL_DIR/system/lib/log4j.properties
2. UpdateERRORtoDEBUGforlog4j.logger.org.apache.cassandra(server)and
me.prettyprint.cassandra(client).
3. RestartAPIGateway.
Cassandraconfiguration steps
ThemainCassandraconfigurationstepsareoutlinedasfollows:
1. ConfiguretheCassandratopologyincassandra.yaml,client.yaml,andjvm.xml.
2. StartAPIGatewayswithembeddedCassandraservers
3. ConfiguretheCassandrareplicationfactor
4. Configurerequestconsistencylevels
Thisconfigurationisdescribedasfollows:
l CassandraserverAistheseednode
l Serverservercommunicationonport7000(mustbethesameacrossthecluster)
l Clientsconnecttotheirlocalserver
l JMXisdisabled(notneededforsinglenodesystem)
l Consistentreadsandwrites
l NoHA
Thefollowingdiagramshowsanexampleconfiguration:
Note WhenaCassandraserverstartsupforthefirsttime,itcontactsaseednodetoobtain
informationaboutotherserversinthecluster.Inamulti-servercluster,atleastoneseed
nodemustbeavailablewhenstartingaCassandraserverforthefirsttime.
Note OnAPIGatewaysthatshouldrunasCassandraclients,renameorremovethe
cassandra.yamlfile,andrestarttheseAPIGateways.Ifaclientstartsupbeforeaserver,
youwillgetmultipleerrorssuchas:
me.prettyprint.hector.api.exceptions.HectorException:Allhostpoolsmarked
down.Retryburdenpushedouttoclient
However,thisisexpected.TheclientwillnotbeabletofieldCassandrarequestsuntilaserveris
available.
Thefollowingdiagramshowsanexampleconfiguration:
Note Thisisaclientserverconfiguration.IftheserverAPIGatewayisnotavailable,KPSdata
andfunctionalitywillnotbeavailabletoclientAPIGateways.Ifyouwanthigheravailability
withCassandra,configureasuitableHAconfigurationasdescribedinthefollowing
sections.
Windows
Editorcreatethefollowingfile:
C:\Windows\System32\drivers\etc\hosts
Addthefollowinglines:
127.0.0.1127.0.0.N
Linux
Enterthefollowingcommand:
sudoifconfiglo:N127.0.0.Nnetmask
255.0.0.0up
WhereNis2,3,4.
Thefollowingexampleshowsifconfigo utputonLinux:
l TwoCassandraserversAandBdefinedinacluster(serverAistheseednode)
l Serverservercommunicationonport7000.Thismustbethesameacrossthecluster
l Clientsconnecttotheirlocalserver
l JMXisenabledforadministration
TheCassandraparameterconfigurationincludesthefollowing:
l EventualConsistency:Read=Write=ONE
l Replicationfactor:2
l Cansurvivethelossofonenode
l Eachnodeholds100%ofthedata
Thefollowingdiagramshowsanexampleconfiguration:
Thisconfigurationisdescribedasfollows:
l ThreeserversA,B,andCdefinedinacluster(serverAistheseednode)
l Serverservercommunicationonport7000(mustbethesameacrossthecluster)
l Clientsconnecttotheirlocalserver
l JMXenabledforadministration
TheCassandraparameterconfigurationincludesthefollowing:
l Consistent:Read=Write=QUORUM
l Replicationfactor:3
l Cansurvivethelossofonenode
l Eachnodeholds100%ofthedata
l Thereareresourceusageissuesorrestrictionsoncertainserversinthecluster(forexample,disk,
memory,CPU,JARs,classpath,andports)
l Youdonotwanttostoredataatrestoncertainservers
l Youwanttoseparatethedatalayerfromtheapplicationlayer
Note IfeitherCassandraservergoesdown,theclientautomaticallyfailsovertotheotherserver.
Thefollowingdiagramshowsanexampleconfiguration:
1. Ensurethattheseednodeisstartedfirst.Waitforthisnodetostart.
2. Startupothernodesinturn.Waitforeachnodetostart.
Tip Youcanverifytheconfigurationbyrunning./kpsadminandselectingOption30)
Showconfiguration.
1. Runcassandra-cliinanAPIGatewaybindirectory.
2. Executethefollowingcommands:
./cassandra-cli-h127.0.0.2
usekps;
updatekeyspacekpswithstrategy_
options={replication_factor:2};
quit;
Inthisexample,thereplicationfactoris2.EnterthecorrectreplicationfactorforyourCassandra
topology.Formoredetails,seeStep1:ConfiguretheCassandratopologyonpage37.
3. Synchroniseandverifythischangeacrosstheclusterbyexecutingnodetoolrepairagainst
eachnode.Inthefollowingexample,nodetoolisexecutedagainstatwo-nodecluster
runningonIPaddressesof127.0.0.1and127.0.0.2:
./nodetool-h127.0.0.2repairkps
./nodetool-h127.0.0.3repairkps
./nodetool-h127.0.0.2ringkps
./nodetool-h127.0.0.3ringkps
Youshouldseeaneffectiveownershiponeachnodeof100%.Forexample:
Note Cassandra1.2.18nodetoolrequiresthelocationofcassandra.yaml.Youmustupdate
apigateway/system/conf/cassandra-tools-jvm.xmltospecifylocationof
cassandra.yaml.Donotuse$VINSTDIRbecausethesystemdoesnotknowwhich
APIGatewaytoresolveto.Forexample:
<ConfigurationFragment>
<!--forthewin32JVM,ensurethatthepathtothejvm.dllisavailable.POSIXstyle
hostsdothisusingscripts.-->
<PathAddname="PATH"value="$VDISTDIR/win32/jre/bin/server"/>
<JVMSettings>
<ClassDirname="$VDISTDIR/system/lib/modules"/>
<ClassDirname="$VDISTDIR/system/lib/modules/cassandra/server"/>
<SystemPropertyname="cassandra.config"
value="file://$VDISTDIR/groups/group-2/instance-
1/conf/kps/cassandra/cassandra.yaml"/>
</JVMSettings>
</ConfigurationFragment>
Toconfigurerequestconsistencylevels,performthefollowingsteps:
TodisableCassandrastorage,performthefollowingsteps:
1. RunthefollowingsamplescriptagainsttheAPIGateway.Thisupdatesthe APIGateway
configurationbyswitchinganyCassandrausagetofileusage.
Windows
cdINSTALL_DIR\samples\scripts
run.batcassandra/disableCassandra.py
UNIX
cdINSTALL_DIR/samples/scripts
./run.shcassandra/disableCassandra.py
2. RestarttheAPIGateway.
3. IfyouarerunningmultipleAPIGatewaysinthegroup,deploytheupdatedconfigurationto
theseAPIGatewaysandrestartthem.
l Oracle
l IBMDB2
l MicrosoftSQLServer
l MySQL
Theoptionsfordatabasestorageareasfollows:
INSTALL_DIR/system/conf/sql/DB_NAME/kps.sql
Note ForOracle,ensurethatthedatabaseiscreatedwiththeAL32UTF8charactersetencoding
tosupportUTF8.
ThefollowingshowsexampledatabaseconnectionsettingsinPolicyStudio:
Note ForMySQL,thetablecreationscriptspecifiesUTF8.YoumustalsousethecorrectJDBC
connectionURL.UpdatetheconnectionURLfieldtospecifyunicode&UTF8.For
example:
jdbc:mysql://testserver:3306/kps?useUnicode=true&characterEncoding=UTF-8
Foranexamplewithfilestorage,seeConfigurefile-basedKPSstorageonpage59.
l ThemaximumprimarykeylengthinaKPSrowis255characters
l ThemaximumKPStablenamelengthis255characters
l KPSrowsareJSONencoded
l Optimisticlockingisusedandisenforcedusingaversioncolumn
altertablekps_objectmodifycolumnlargevaluemediumtext;
INSTALL_DIR/apigateway/system/lib/log4j.properties
2. Addthefollowingsettings:
log4j.rootLogger=DEBUG,A1,Vordel
#OpenJPA
log4j.category.openjpa.Tool=DEBUG
log4j.category.openjpa.Runtime=DEBUG
log4j.category.openjpa.Remote=DEBUG
log4j.category.openjpa.DataCache=DEBUG
log4j.category.openjpa.MetaData=DEBUG
log4j.category.openjpa.Enhance=DEBUG
log4j.category.openjpa.Query=DEBUG
log4j.category.openjpa.jdbc.SQL=DEBUG
log4j.category.openjpa.jdbc.SQLDiag=DEBUG
log4j.category.openjpa.jdbc.JDBC=DEBUG
log4j.category.openjpa.jdbc.Schema=DEBUG
3. RestarttheAPIGateway.
4. Verifythatdebugstatementsarewrittentothelog.
1. Editthefollowingfile:
INSTALL_DIR/apigateway/system/lib/log4j.properties
2. SubstituteERRORforDEBUGinthelog4j.category.openjpasettings.
3. RestarttheAPIGateway.
4. Verifythatnodebugstatementsareprintedtothelog.
FormoreinformationonApacheOpenJPAlogging,see:
http://openjpa.apache.org/builds/2.2.2/apache-openjpa/docs/main.html
However,tablesthatuseper-tabledatabasestoragehavesignificantlimitations:
l DatacannotbeaddedthroughKPS,butonlydirectlythroughthedatabase
l DatacannotbeviewedinkpsadminorAPIGatewayManager,butcanonlybereadbyselectors
atruntime
l Tablescanonlycontainsimpledatatypes,notmapsorlists
KPStablescanbequeriedusingsimpleorcompositekeys.Thissectionshowsexamplesofboth.
CREATETABLEUser(
emailVARCHAR(100),
passwordVARCHAR(100),
firstNameVARCHAR(100),
lastNameVARCHAR(100),
ageINT
);
insertintoUser(email,password,firstName,lastName,age)values
("ralph.jones@acme.com","password","Ralph","Jones",30);
insertintoUser(email,password,firstName,lastName,age)values
("kathy.adams@acme.com","blah","Kathy","Adams",35);
2. SpecifytheDatabase Connectioninthedialog(forexample,TestDBConnection):
2. Enteranaliasinthedialog(forexamplemapUser):
3. Enteradatabase-specificJDBCSQLquerytoretrievetherequireddata.Forexample:
select*fromUserwhereemail=?
4. OnthePropertiestabofthenewKPStable,selectthenewdatabasedatasourceinOverride
the default data source with the following:
InthisSQLquery,emailistheprimarykey.Youspecifyemailasthepropertytousein
correspondingselectorqueries:
Forexample,youcanusethefollowingselector:
${kps.mapUser
["kathy.adams@acme.com"].age}
Note ThissyntaxusesASCIIquotationmarks(").
ThisselectorgeneratesthefollowingSQLquery:
select*fromUserwhereemail=
"kathy.adams@acme.com"
Torunthepolicyinyourbrowser,goto:
http://localhost:8080/kpsGetViaSelector?id=kathy.adams@acme.com
ThisURLspecifiestheuserID(email)askathy.adams@acme.com.
Forexample,theresultisasfollows:
TomodifytheKPStable,performthefollowingsteps:
1. OnthePropertiestabintheQueryfield,enterthefollowing:
select*fromUserwherefirstName=
?andlastName=?
Forexample:
2. Onthe Structuretab,changetheselectorpropertiestofirstName,lastName:
EnterthefollowingintheMessage Bodyfield,usingasinglelineforeachentry(Email,First
Name,LastName,andAge):
========================
User
===
Email:${kps.mapUser[http.querystring.firstName]
[http.querystring.lastName].email}
FirstName:${kps.mapUser[http.querystring.firstName]
[http.querystring.lastName].firstName}
LastName:${kps.mapUser[http.querystring.firstName]
[http.querystring.lastName].lastName}
Age:${kps.mapUser[http.querystring.firstName]
[http.querystring.lastName].age}
========================
Torunthepolicyinabrowser,gotothefollowingURL:
http://localhost:8080/kpsGetViaSelector?firstName=Kathy&lastName=Adams
Forexample,theresultisasfollows:
Note File-basedKPSstorageismostsuitedtosingleAPIGatewaydeployments.Inamulti-
APIGatewayscenario,filereplicationorashareddiskisrequiredtoensurethatall
APIGatewaysusethesamedata.
File-basedKPStablesarereadandcachedbyAPIGatewayswhentheystartup.Ifdataismodified,
allAPIGatewaysmustberestartedtopickupthechanges.
Thesesettingsaredescribedasfollows:
Name Description
Name Collection-uniquedatasourcename.
Description Optionaldescription.
Directory Thedirectorynamewheretabledataforthecollectionisstored.Ifthe
Path directorydoesnotexist,itisautomaticallycreated.Ifthisdirectoryisnot
specified,thedirectorypathdefaultsto${VINSTDIR}/conf/kps.
ThepathcanincludeVDISTDIRorVINSTDIRvariables.Theseareresolvedto
theAPIGatewayinstanceandinstallationdirectories.Forexample,
${VDISTDIR}/mydata/samples.Remembertousethecorrectpath
separator(/onUNIXand\onWindows).
ThisappendixanswersthefrequentlyaskedquestionsonKPSandAPIGateway,KPSstorage,and
ApacheCassandra.
Withfilestorage,dataisconsistentinasingleAPIGateway.Withsupporteddatabasestorage,data
isconsistent.CassandrastorageallowsconsistencylevelstobesetperKPStable.KPSdoesnot
providetransactionsacrossmultipleoperations.YoucannotissueasetofKPSoperationsandroll
themback.
1. Editthefollowingfile:
INSTALL_DIR/policy_studio/policystudio.ini
2. Settheshow.internal.kps.collectionsystempropertytotrue.Forexample:
3. RestartPolicyStudio.
Note YouwillneedtoeditthesehiddencollectionsifyouwishtochangeCassandraconsistency
levels(forexample,whenswitchingtoanHAsetup).
1. ChangethegrouppassphraseinPolicyStudio.Fordetails,seetheAPIGatewayAdministrator
Guide.
2. Inkpsadmin,selecttheCollectionAdministration,Re-encryptAlloptiontore-
encryptthedataineachcollection.
3. YouwillbeaskedtoentertheoldAPIGatewaypassphrase.Thispassphraseisusedtodecrypt
thedata.Thedataisthenre-encryptedwiththecurrentAPIGatewaypassphrase.
Formoredetails,seeManageaKPSusingkpsadminonpage28.
1. Backupthedataforacollectionusingkpsadmin.
2. Addandconfigureanewdatasource(file,database,orCassandra)usingPolicyStudio.
3. DeploytheconfigurationinPolicyStudio.
4. Restorethedatausingkpsadmin.
Formoredetails,seetheexampleinManageaKPSusingkpsadminonpage28.
Apache Cassandra
ThissectionincludesfrequentlyaskedquestionsontheApacheCassandradatabase:
ThisappendixdescribesvariousKPSerrormessages,andexplainshowtoresolvethem.
All platforms
ThissectionexplainshowtotroubleshootKPSerrorsonallplatforms:
Toresolvethisissue,performthefollowingsteps:
l Checkthatallportsandaddressesarecorrectincassandra.yamltoverifythattheendpoints
arewhatyouexpect.
l Runkpsdamin,andselectCassandraAdministration,ShowConfigurationtoreadthis
configuration.Andverifytheresultiswhatyouexpect.Formoredetails,seeManageaKPSusing
kpsadminonpage28.
l EnableCassandradebuglogging.
FormoredetailsonCassandraconfigurationandlogging,seeConfigureApacheCassandra
KPSstorageonpage34.
Failedtoconnectto'REMOTE_IP:7199:Connectionrefused'
Toresolvethisissue,performthefollowingsteps:
1. Oneachnode,editthejvm.xmlfileinthefollowingdirectory:
INSTALL_DIR/apigateway/groups/GROUP_ID/INSTANCE_ID/conf/kps/cassandra
2. AddthefollowingJVMargument:
java.rmi.server.hostname=BIND_ADDRESS
FormoredetailsonCassandraconfiguration,seeConfigureApacheCassandraKPSstorageonpage
34.
Toresolvethisissue,youmustensurethatthereplicationiscorrectly.Forexample,youcanusethe
followingnodetoolcommand:
./nodetool-h127.0.0.2ringkps
Datacenter:datacenter1
==========
Replicas:1xxxxx
AddressRackStatusState
LoadOwnsToken7564491331177403445
127.0.0.2rack1UpNormal1.19MB35.10%-
1090016113642762867
127.0.0.3rack1UpNormal2.17MB64.90%-
7564491331177403445
Note Inthiscase,thenumberofreplicasis1andOwnsisnot100%pernode.Youshouldset
thereplicationfactor,synchronizethechanges,andverifyasdescribedinConfigure
ApacheCassandraKPSstorageonpage34
Windows only
ThissectionexplainshowtotroubleshootKPSerrorsonWindowsonly:
Toresolvethisissue,performthefollowingsteps:
1. Editcassandra.yamlandclient.yaml.
2. ChangelocalhosttoIPnameoraddress.
3. RestartAPIGateway.
FormoredetailsonCassandraconfiguration,seeConfigureApacheCassandraKPSstorageonpage
34.
TheFSUTILutilityrequiresalocalNTFSvolume.at
org.apache.cassandra.utils.FBUtilities.exec(FBUtilities.java:573)
ThisisanWindowsXPissue,whichalsoappliestoNTFS(notjustFATxx).Formoredetails,see:
http://support.microsoft.com/kb/322275
java.io.IOException:Exceptionwhileexecutingthecommand:cmd/c
mklink...
commanderrorCode:1,commandoutput:Thesystemcannotfindthepath
specified.
Toresolvethisissue,performthefollowingsteps:
1. UseashortpathforCassandradata.
2. Updatethecassandra.yamldatadirectories:
data_file_directories:[dir-x]
commitlog_directory:dir-x
saved_caches_directory:dir-x
3. RestarttheAPIGateway.
FormoredetailsonCassandraconfiguration,seeConfigureApacheCassandraKPSstorageonpage
34.
Toresolvethisissue,youshoulddropindividualcolumnfamiliesandthekps_schemarecord.For
example,forasamples_usertable,pastethefollowingintocassandra-cli:
usekps;
assumekps_schemavalidatorasutf8;
assumekps_schemacomparatorasutf8;
assumekps_schemakeysasutf8;
assumesamples_uservalidatorasutf8;
assumesamples_usercomparatorasutf8;
assumesamples_userkeysasutf8;
dropcolumnfamilysamples_user;
delkps_schema['samples_user'];
Note Theassumecommandsmustbeexecutedonce.
ThisappendixdescribesimportantApacheCassandraoperationsfornoderepair,andbackupand
recovery.
nodetool repair
ThenodetoolrepaircommandrepairsinconsistenciesacrossallCassandrareplicasforagiven
rangeofdata.Formoredetails,see:
http://www.datastax.com/documentation/cassandra/1.2/cassandra/operations/ops_repair_
nodes_c.html
Youshouldexecutethiscommandweekly,atoff-peaktimes,andstaggerexecutionondifferent
nodes.
Thefollowingisasimplecrontabcommandthatexecutesrepairevery10minutes:
vagrant@node-3:~$crontab
*/10****/home/vagrant/from/apigateway/posix/bin/nodetool-hnode-3
repairkps>>/home/vagrant/nodetool.log
Note Thisisasimpleexamplefromadevelopmenttest.Inproduction,donotexecuterepair
every10minutes.
http://www.datastax.com/documentation/cassandra/1.2/cassandra/operations/ops_backup_
restore_c.html
Note Whenrestoringfromasnapshot,youshouldfollowthenoderestartmethod.
INSTALL_DIR/apigateway/group-n/conf
Youshouldregularlybackupthisdirectory.
INSTALL_DIR/apigateway/group-n/instance-m/conf/kps/cassandra
ThiscontainstheCassandraconfiguration(cassandra.yaml,client.yaml,andjvm.xmlfiles).
ItalsoincludestheCassandraruntimedatainthedata,saved_caches,andcommitlog
subdirectories.
Youshouldregularlybackupthisdirectory.
Note FormoredetailsonAPIGatewaybackupanddisasterrecovery,seetheAPIGateway
AdministratorGuide.
http://www.datastax.com/documentation/cassandra/1.2/cassandra/operations/ops_replace_
node_t.html
TheprocedureforAPIGatewayisasfollows:
1. Confirmthatthenodeisdeadusingnodetoolstatus(seetheCassandraprocedureabove).
2. Notetheaddressofthedeadnode(thisisusedinthelaststep).
3. InstallanewAPIGateway,orrestoreabackupofanexistingAPIGateway.Donotstartthe
APIGateway.
4. TheAPIGatewayCassandradirectoryis:
INSTALL_DIR/apigateway/group-n/instance-m/conf/kps/cassandra
Copycassandra.yaml,client.yamlandjvm.xmlfromabackuporrecreateinthe
APIGatewayCassandradirectory.
5. Backupandremovethedata,saved_caches,andcommitlogd irectoriesiftheyexist.
cassandra-topology.propertiesisrequiredformulti-datacentreconfiguration.Oracle
currentlydonottestorsupportthiskindofconfiguration.Formoredetailsonthe
cassandra.yamlfile,seethestandardCassandraprocedureabove.
Note auto_bootstrapshouldnotbelistedorshouldbesettofalse
6. StarttheAPIGatewaywiththe-Dcassandra.replace_addressoption.EnsureJMXis
enabled.Forexample:
./startinstance
-gTeamA
-napi2
-Dcassandra.replace_address=192.168.99.12
-DenableJMX
7. Remembertoremovethe-Dcassandra.replace_addressoptionforsubsequentstarts.
Feature Documentation
Apache FordetailsonCassandraversion1.2.x,seethefollowing:
Cassandra
l http://cassandra.apache.org/
l http://www.datastax.com/documentation/cassandra/1.2
Apache FordetailsonCassandraparameterconfiguration,seethefollowing:
Cassandra http://www.ecyrd.com/cassandracalculator/
parameter
configuration
KPS
KeyPropertyStore.DatamanagementcomponentintheAPIGateway.
KPS alias
AnalternativenameforaKPStablethatisuniqueinanAPIGatewaygroup.
KPS collection
AcollectionofrelatedKPStables.
KPS table
AuserdefinedtablethatismanagedbytheKPSintheAPIGateway.
Selector
AspecialsyntaxthatenablesAPIGatewayconfigurationsettingstobeevaluatedandexpanded
atruntimebasedonmetadatavalues(forexample,fromaKPS,messageattribute,or
environmentvariable).