openstack nova 原始碼分析4-nova目錄下的driver.py
阿新 • • 發佈:2020-10-09
還是有許多地方可能錯了 希望大嬸們 看見 給予意見 !
這個檔案位於\nova\virt,是一個底層的driver.py,原始碼如下(和以前一樣添加了些註釋,另外把我 覺得比較重要的computerDriver類列出來 了,並將下面的每個函式分離 加以註釋《見下面圖片》!我看見後面好多函式都是繼承的ComputerDriver比如nova\virt\libvirt下面的connection.py裡面的class LibvirtConnection(driver.ComputeDriver):):
- """
- Driverbase-classes:
- (Beginningof)thecontractthatcomputedriversmustfollow,andshared
- typesthatsupportthatcontract
- """
- fromnova.computeimportpower_state
- classInstanceInfo(object):
- def__init__(self,name,state):
- self.name=name
- assertstateinpower_state.valid_states(),"Badstate:%s"%state
- self.state=state
- defblock_device_info_get_root(block_device_info):
- block_device_info=block_device_info
- returnblock_device_info.get('root_device_name')
- defblock_device_info_get_swap(block_device_info):
- block_device_info=block_device_infoor{}
- returnblock_device_info.get('swap')or{'device_name':None,
- 'swap_size':0}
- defswap_is_usable(swap):
- returnswapandswap['device_name']andswap['swap_size']>0
- defblock_device_info_get_ephemerals(block_device_info):
- block_device_info=block_device_infoor{}
- ephemerals=block_device_info.get('ephemerals')or[]
- returnephemerals
- defblock_device_info_get_mapping(block_device_info):
- block_device_info=block_device_infoor{}
- block_device_mapping=block_device_info.get('block_device_mapping')or[]
- returnblock_device_mapping
- classComputeDriver(object):
- """Baseclassforcomputedrivers.
- Theinterfacetothisclasstalksintermsof'instances'(AmazonEC2and
- internalNovaterminology),bywhichwemean'runningvirtualmachine'
- (XenAPIterminology)ordomain(Xenorlibvirtterminology).
- AninstancehasanID,whichistheidentifierchosenbyNovatorepresent
- theinstancefurtherupthestack.Thisisunfortunatelyalsocalleda
- 'name'elsewhere.Asfarasthislayerisconcerned,'instanceID'and
- 'instancename'aresynonyms.
- NotethattheinstanceIDornameisnothuman-readableor
- customer-controlled--it'saninternalIDchosenbyNova.Atthe
- nova.virtlayer,instancesdonothavehuman-readablenamesatall--such
- thingsareonlyknownhigherupthestack.
- Mostvirtualizationplatformswillalsohavetheirownidentityschemes,
- touniquelyidentifyaVMordomain.TheseIDsmuststayinternaltothe
- platform-specificlayer,andneverescapetheconnectioninterface.The
- platform-specificlayerisresponsibleforkeepingtrackofwhichinstance
- IDmapstowhichplatform-specificID,andviceversa.
- Incontrast,thelist_disksandlist_interfacescallsmayreturn
- platform-specificIDs.Theseidentifyaspecificvirtualdiskorspecific
- virtualnetworkinterface,andtheseIDsareopaquetotherestofNova.
- Somemethodsheretakeaninstanceofnova.compute.service.Instance.This
- isthedatastructureusedbynova.computetostoredetailsregardingan
- instance,andpassthemintothislayer.Thislayerisresponsiblefor
- translatingthatgenericdatastructureintotermsthatarespecifictothe
- virtualizationplatform.
- """
- #此處為了讓大家看的明白將ComputerDriver的類圖列出來
- definit_host(self,host):
- """Initializeanythingthatisnecessaryforthedrivertofunction,
- includingcatchingupwithcurrentlyrunningVM'sonthegivenhost."""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defget_info(self,instance_name):
- """Getthecurrentstatusofaninstance,byname(notID!)
- Returnsadictcontaining:
- :state:therunningstate,oneofthepower_statecodes
- :max_mem:(int)themaximummemoryinKBytesallowed
- :mem:(int)thememoryinKBytesusedbythedomain
- :num_cpu:(int)thenumberofvirtualCPUsforthedomain
- :cpu_time:(int)theCPUtimeusedinnanoseconds
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- deflist_instances(self):
- """
- Returnthenamesofalltheinstancesknowntothevirtualization
- layer,asalist.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- deflist_instances_detail(self):
- """ReturnalistofInstanceInfoforallregisteredVMs"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defspawn(self,context,instance,
- network_info=None,block_device_info=None):
- """
- Createanewinstance/VM/domainonthevirtualizationplatform.
- Oncethissuccessfullycompletes,theinstanceshouldbe
- running(power_state.RUNNING).
- Ifthisfails,anypartialinstanceshouldbecompletely
- cleanedup,andthevirtualizationplatformshouldbeinthestate
- thatitwasbeforethiscallbegan.
- :paramcontext:securitycontext
- :paraminstance:InstanceobjectasreturnedbyDBlayer.
- Thisfunctionshouldusethedatatheretoguide
- thecreationofthenewinstance.
- :paramnetwork_info:
- :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
- :paramblock_device_info:
- """
- raiseNotImplementedError()
- defdestroy(self,instance,network_info,cleanup=True):
- """Destroy(shutdownanddelete)thespecifiedinstance.
- Iftheinstanceisnotfound(forexampleifnetworkingfailed),this
- functionshouldstillsucceed.It'sprobablyagoodideatologa
- warninginthatcase.
- :paraminstance:InstanceobjectasreturnedbyDBlayer.
- :paramnetwork_info:
- :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
- :paramcleanup:
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defreboot(self,instance,network_info):
- """Rebootthespecifiedinstance.
- :paraminstance:InstanceobjectasreturnedbyDBlayer.
- :paramnetwork_info:
- :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defsnapshot_instance(self,context,instance_id,p_w_picpath_id):
- raiseNotImplementedError()
- defget_console_pool_info(self,console_type):
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defget_console_output(self,instance):
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defget_ajax_console(self,instance):
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defget_diagnostics(self,instance):
- """ReturndataaboutVMdiagnostics"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defget_host_ip_addr(self):
- """
- RetrievestheIPaddressofthedom0
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defattach_volume(self,context,instance_id,volume_id,mountpoint):
- """Attachthediskatdevice_pathtotheinstanceatmountpoint"""
- raiseNotImplementedError()
- defdetach_volume(self,context,instance_id,volume_id):
- """Detachthediskattachedtotheinstanceatmountpoint"""
- raiseNotImplementedError()
- defcompare_cpu(self,cpu_info):
- """Comparesgivencpuinfoagainsthost確保vm能執行
- BeforeattemptingtomigrateaVMtothishost,
- compare_cpuiscalledtoensurethattheVMwill
- actuallyrunhere.
- :paramcpu_info:(str)JSONstructuredescribingthesourceCPU.
- :returns:Noneifmigrationisacceptable
- :raises::py:class:`~nova.exception.InvalidCPUInfo`ifmigration
- isnotacceptable.
- """
- raiseNotImplementedError()
- defmigrate_disk_and_power_off(self,instance,dest):
- """
- Transfersthediskofarunninginstanceinmultiplephases,turning
- offtheinstancebeforetheend.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defsnapshot(self,context,instance,p_w_picpath_id):
- """
- Snapshotsthespecifiedinstance.
- :paramcontext:securitycontext
- :paraminstance:InstanceobjectasreturnedbyDBlayer.
- :paramp_w_picpath_id:Referencetoapre-createdp_w_picpaththatwill
- holdthesnapshot.
- """
- raiseNotImplementedError()
- deffinish_migration(self,context,instance,disk_info,network_info,
- resize_instance):
- #開啟一個遷移的例項,完成一個調整
- """Completesaresize,turningonthemigratedinstance
- :paramnetwork_info:
- :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
- """
- raiseNotImplementedError()
- defrevert_migration(self,instance):
- #返回一個調整,推動回到例項?
- """Revertsaresize,poweringbackontheinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defpause(self,instance,callback):
- """Pausethespecifiedinstance."""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defunpause(self,instance,callback):
- """UnpausepausedVMinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defsuspend(self,instance,callback):
- #掛起指定的例項
- """suspendthespecifiedinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defresume(self,instance,callback):
- """resumethespecifiedinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defrescue(self,context,instance,callback,network_info):
- #恢復指定的例項
- """Rescuethespecifiedinstance"""
- raiseNotImplementedError()
- defunrescue(self,instance,callback,network_info):
- """Unrescuethespecifiedinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defupdate_available_resource(self,ctxt,host):
- #在computeNode表中更新電腦資源管理的資訊
- """UpdatescomputemanagerresourceinfoonComputeNodetable.
- Thismethodiscalledwhennova-computelaunches,and
- wheneveradminexecutes"nova-manageserviceupdate_resource".
- :paramctxt:securitycontext
- :paramhost:hostnamethatcomputemanageriscurrentlyrunning
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- deflive_migration(self,ctxt,instance_ref,dest,
- post_method,recover_method):
- #分發處理高負荷,當有高負荷操作時候,大量生成live_mirgration
- """Spawninglive_migrationoperationfordistributinghigh-load.
- :paramctxt:securitycontext
- :paraminstance_ref:
- nova.db.sqlalchemy.models.Instanceobject
- instanceobjectthatismigrated.
- :paramdest:destinationhost
- :parampost_method:
- postoperationmethod.
- expectednova.compute.manager.post_live_migration.
- :paramrecover_method:
- recoverymethodwhenanyexceptionoccurs.
- expectednova.compute.manager.recover_live_migration.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defrefresh_security_group_rules(self,security_group_id):
- #改變安全組之後呼叫
- """Thismethodiscalledafterachangetosecuritygroups.
- Allsecuritygroupsandtheirassociatedrulesliveinthedatastore,
- andcallingthismethodshouldapplytheupdatedrulestoinstances
- runningthespecifiedsecuritygroup.
- Anerrorshouldberaisediftheoperationcannotcomplete.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defrefresh_security_group_members(self,security_group_id):
- #當一個安全組被新增到一個例項,這個方法被呼叫
- """Thismethodiscalledwhenasecuritygroupisaddedtoaninstance.
- Thismessageissenttothevirtualizationdriversonhoststhatare
- runninganinstancethatbelongstoasecuritygroupthathasarule
- thatreferencesthesecuritygroupidentifiedby`security_group_id`.
- Itistheresponsiblityofthismethodtomakesureanyrules
- thatauthorizetrafficflowwithmembersofthesecuritygroupare
- updatedandanynewmemberscancommunicate,andanyremovedmembers
- cannot.
- Scenario:
- *wearerunningonhost'H0'andwehaveaninstance'i-0'.
- *instance'i-0'isamemberofsecuritygroup'speaks-b'
- *group'speaks-b'hasaningressrulethatauthorizesgroup'b'
- *anotherhost'H1'runsaninstance'i-1'
- *instance'i-1'isamemberofsecuritygroup'b'
- When'i-1'launchesorterminateswewillrecievethemessage
- toupdatemembersofgroup'b',atwhichtimewewillmake
- anychangesneededtotherulesforinstance'i-0'toallow
- ordenytrafficcomingfrom'i-1',dependingonifitisbeing
- addedorremovedfromthegroup.
- Inthisscenario,'i-1'couldjustaseasilyhavebeenrunningonour
- host'H0'andthismethodwouldstillhavebeencalled.Thepointwas
- thatthismethodisn'tcalledonthehostwhereinstancesofthat
- grouparerunning(asisthecasewith
- :method:`refresh_security_group_rules`)butiscalledwherereferences
- aremadetoauthorizingthoseinstances.
- Anerrorshouldberaisediftheoperationcannotcomplete.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defrefresh_provider_fw_rules(self,security_group_id):
- #這觸發一個基於資料庫改變的防火牆的更新
- """Thistriggersafirewallupdatebasedondatabasechanges.
- Whenthisiscalled,ruleshaveeitherbeenaddedorremovedfromthe
- datastore.Youcanretrieveruleswith
- :method:`nova.db.api.provider_fw_rule_get_all`.
- Providerrulestakeprecedenceoversecuritygrouprules.IfanIP
- wouldbeallowedbyasecuritygroupingressrule,butblockedby
- aproviderrule,thenpacketsfromtheIParedropped.Thisincludes
- intra-projecttrafficinthecaseoftheallow_project_net_traffic
- flagforthelibvirt-derivedclasses.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defreset_network(self,instance):
- """resetnetworkingforspecifiedinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- pass
- defensure_filtering_rules_for_instance(self,instance_ref,network_info):
- #設定過濾規則,並等待它完成
- """Settingupfilteringrulesandwaitingforitscompletion.
- Tomigrateaninstance,filteringrulestohypervisors
- andfirewallsareinevitableondestinationhost.
- (Waitingonlyforfilteringrulestohypervisor,
- sincefilteringrulestofirewallrulescanbesetfaster).
- Concretely,thebelowmethodmustbecalled.
- -setup_basic_filtering(fornova-basic,etc.)
- -prepare_instance_filter(fornova-instance-instance-xxx,etc.)
- to_xmlmayhavetobecalledsinceitdefinesPROJNET,PROJMASK.
- butlibvirtmigratesthosevaluethroughmigrateToURI(),
- so,noneedtobecalled.
- Don'tusethreadforthismethodsincemigrationshould
- notbestartedwhensetting-upfilteringrulesoperations
- arenotcompleted.
- :paramsinstance_ref:nova.db.sqlalchemy.models.Instanceobject
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defunfilter_instance(self,instance,network_info):
- """Stopfilteringinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defset_admin_password(self,context,instance_id,new_pass=None):
- """
- Settherootpasswordonthespecifiedinstance.
- Thefirstparameterisaninstanceofnova.compute.service.Instance,
- andsotheinstanceisbeingspecifiedasinstance.name.Thesecond
- parameteristhevalueofthenewpassword.
- """
- raiseNotImplementedError()
- definject_file(self,instance,b64_path,b64_contents):
- """在指定的例項上寫檔案
- Writesafileonthespecifiedinstance.
- Thefirstparameterisaninstanceofnova.compute.service.Instance,
- andsotheinstanceisbeingspecifiedasinstance.name.Thesecond
- parameteristhebase64-encodedpathtowhichthefileistobe
- writtenontheinstance;thethirdisthecontentsofthefile,also
- base64-encoded.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defagent_update(self,instance,url,md5hash):
- #在指定的例項中更新代理
- """
- Updateagentonthespecifiedinstance.
- Thefirstparameterisaninstanceofnova.compute.service.Instance,
- andsotheinstanceisbeingspecifiedasinstance.name.Thesecond
- parameteristheURLoftheagenttobefetchedandupdatedonthe
- instance;thethirdisthemd5hashofthefileforverification
- purposes.
- """
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- definject_network_info(self,instance,nw_info):
- #為指定的例項注入網路資訊
- """injectnetworkinfoforspecifiedinstance"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- pass
- defpoll_rescued_instances(self,timeout):
- #輪詢已經恢復的例項
- """Pollforrescuedinstances"""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defhost_power_action(self,host,action):
- """Reboots,shutsdownorpowersupthehost."""
- raiseNotImplementedError()
- defset_host_enabled(self,host,enabled):
- #設定指定的主機有能力接受新的例項
- """Setsthespecifiedhost'sabilitytoacceptnewinstances."""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defplug_vifs(self,instance,network_info):
- """PlugsinVIFstonetworks."""
- #TODO(Vek):Needtopasscontextinforaccesstoauth_token
- raiseNotImplementedError()
- defupdate_host_status(self):
- """Refreshhoststats"""
- raiseNotImplementedError()
- defget_host_stats(self,refresh=False):
- """Returncurrentlyknownhoststats"""
- raiseNotImplementedError()
- deflist_disks(self,instance_name):
- """
- ReturntheIDsofallthevirtualdisksattachedtothespecified
- instance,asalist.TheseIDsareopaquetothecaller(theyare
- onlyusefulforgivingbacktothislayerasaparameterto
- disk_stats).TheseIDsonlyneedtobeuniqueforagiveninstance.
- NotethatthisfunctiontakesaninstanceID.
- """
- raiseNotImplementedError()
- deflist_interfaces(self,instance_name):
- """
- ReturntheIDsofallthevirtualnetworkinterfacesattachedtothe
- specifiedinstance,asalist.TheseIDsareopaquetothecaller
- (theyareonlyusefulforgivingbacktothislayerasaparameterto
- interface_stats).TheseIDsonlyneedtobeuniqueforagiven
- instance.
- NotethatthisfunctiontakesaninstanceID.
- """
- raiseNotImplementedError()
- defresize(self,instance,flavor):
- """
- Resizes/Migratesthespecifiedinstance.
- TheflavorparameterdetermineswhetherornottheinstanceRAMand
- diskspacearemodified,andifso,towhatsize.
- """
- raiseNotImplementedError()
- defblock_stats(self,instance_name,disk_id):
- """
- Returnperformancecountersassociatedwiththegivendisk_idonthe
- giveninstance_name.Thesearereturnedas[rd_req,rd_bytes,wr_req,
- wr_bytes,errs],whererdindicatesread,wrindicateswrite,reqis
- thetotalnumberofI/Orequestsmade,bytesisthetotalnumberof
- bytestransferred,anderrsisthenumberofrequestsheldupduetoa
- fullpipeline.
- Allcountersarelongintegers.
- Thismethodisoptional.Onsomeplatforms(e.g.XenAPI)performance
- statisticscanberetrieveddirectlyinaggregateform,withoutNova
- havingtodotheaggregation.Onthoseplatforms,thismethodis
- unused.
- NotethatthisfunctiontakesaninstanceID.
- """
- raiseNotImplementedError()
- definterface_stats(self,instance_name,iface_id):
- """
- Returnperformancecountersassociatedwiththegiveniface_idonthe
- giveninstance_id.Thesearereturnedas[rx_bytes,rx_packets,
- rx_errs,rx_drop,tx_bytes,tx_packets,tx_errs,tx_drop],whererx
- indicatesreceive,txindicatestransmit,bytesandpacketsindicate
- thetotalnum
- berofbytesorpacketstransferred,anderrsanddropped
- isthetotalnumberofpacketsfailed/dropped.
- Allcountersarelongintegers.
- Thismethodisoptional.Onsomeplatforms(e.g.XenAPI)performance
- statisticscanberetrieveddirectlyinaggregateform,withoutNova
- havingtodotheaggregation.Onthoseplatforms,thismethodis
- unused.
- NotethatthisfunctiontakesaninstanceID.
- """
- raiseNotImplementedError()
1:
2:
4: 4
轉載於:https://blog.51cto.com/brucemars/967409