1. 程式人生 > 實用技巧 >openstack nova 原始碼分析4-nova目錄下的driver.py

openstack nova 原始碼分析4-nova目錄下的driver.py

還是有許多地方可能錯了 希望大嬸們 看見 給予意見 !

這個檔案位於\nova\virt,是一個底層的driver.py,原始碼如下(和以前一樣添加了些註釋,另外把我 覺得比較重要的computerDriver類列出來 了,並將下面的每個函式分離 加以註釋《見下面圖片》!我看見後面好多函式都是繼承的ComputerDriver比如nova\virt\libvirt下面的connection.py裡面的class LibvirtConnection(driver.ComputeDriver):):

  1. """
  2. Driverbase-classes:
  3. (Beginningof)thecontractthatcomputedriversmustfollow,andshared
  4. typesthatsupportthatcontract
  5. """
  6. fromnova.computeimportpower_state
  7. classInstanceInfo(object):
  8. def__init__(self,name,state):
  9. self.name=name
  10. assertstateinpower_state.valid_states(),"Badstate:%s"%state
  11. self.state=state
  12. defblock_device_info_get_root(block_device_info):
  13. block_device_info=block_device_info
    or{}
  14. returnblock_device_info.get('root_device_name')
  15. defblock_device_info_get_swap(block_device_info):
  16. block_device_info=block_device_infoor{}
  17. returnblock_device_info.get('swap')or{'device_name':None,
  18. 'swap_size':0}
  19. defswap_is_usable(swap):
  20. returnswapandswap['device_name']andswap['swap_size']>0
  21. defblock_device_info_get_ephemerals(block_device_info):
  22. block_device_info=block_device_infoor{}
  23. ephemerals=block_device_info.get('ephemerals')or[]
  24. returnephemerals
  25. defblock_device_info_get_mapping(block_device_info):
  26. block_device_info=block_device_infoor{}
  27. block_device_mapping=block_device_info.get('block_device_mapping')or[]
  28. returnblock_device_mapping
  29. classComputeDriver(object):
  30. """Baseclassforcomputedrivers.
  31. Theinterfacetothisclasstalksintermsof'instances'(AmazonEC2and
  32. internalNovaterminology),bywhichwemean'runningvirtualmachine'
  33. (XenAPIterminology)ordomain(Xenorlibvirtterminology).
  34. AninstancehasanID,whichistheidentifierchosenbyNovatorepresent
  35. theinstancefurtherupthestack.Thisisunfortunatelyalsocalleda
  36. 'name'elsewhere.Asfarasthislayerisconcerned,'instanceID'and
  37. 'instancename'aresynonyms.
  38. NotethattheinstanceIDornameisnothuman-readableor
  39. customer-controlled--it'saninternalIDchosenbyNova.Atthe
  40. nova.virtlayer,instancesdonothavehuman-readablenamesatall--such
  41. thingsareonlyknownhigherupthestack.
  42. Mostvirtualizationplatformswillalsohavetheirownidentityschemes,
  43. touniquelyidentifyaVMordomain.TheseIDsmuststayinternaltothe
  44. platform-specificlayer,andneverescapetheconnectioninterface.The
  45. platform-specificlayerisresponsibleforkeepingtrackofwhichinstance
  46. IDmapstowhichplatform-specificID,andviceversa.
  47. Incontrast,thelist_disksandlist_interfacescallsmayreturn
  48. platform-specificIDs.Theseidentifyaspecificvirtualdiskorspecific
  49. virtualnetworkinterface,andtheseIDsareopaquetotherestofNova.
  50. Somemethodsheretakeaninstanceofnova.compute.service.Instance.This
  51. isthedatastructureusedbynova.computetostoredetailsregardingan
  52. instance,andpassthemintothislayer.Thislayerisresponsiblefor
  53. translatingthatgenericdatastructureintotermsthatarespecifictothe
  54. virtualizationplatform.
  55. """
  56. #此處為了讓大家看的明白將ComputerDriver的類圖列出來
  57. definit_host(self,host):
  58. """Initializeanythingthatisnecessaryforthedrivertofunction,
  59. includingcatchingupwithcurrentlyrunningVM'sonthegivenhost."""
  60. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  61. raiseNotImplementedError()
  62. defget_info(self,instance_name):
  63. """Getthecurrentstatusofaninstance,byname(notID!)
  64. Returnsadictcontaining:
  65. :state:therunningstate,oneofthepower_statecodes
  66. :max_mem:(int)themaximummemoryinKBytesallowed
  67. :mem:(int)thememoryinKBytesusedbythedomain
  68. :num_cpu:(int)thenumberofvirtualCPUsforthedomain
  69. :cpu_time:(int)theCPUtimeusedinnanoseconds
  70. """
  71. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  72. raiseNotImplementedError()
  73. deflist_instances(self):
  74. """
  75. Returnthenamesofalltheinstancesknowntothevirtualization
  76. layer,asalist.
  77. """
  78. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  79. raiseNotImplementedError()
  80. deflist_instances_detail(self):
  81. """ReturnalistofInstanceInfoforallregisteredVMs"""
  82. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  83. raiseNotImplementedError()
  84. defspawn(self,context,instance,
  85. network_info=None,block_device_info=None):
  86. """
  87. Createanewinstance/VM/domainonthevirtualizationplatform.
  88. Oncethissuccessfullycompletes,theinstanceshouldbe
  89. running(power_state.RUNNING).
  90. Ifthisfails,anypartialinstanceshouldbecompletely
  91. cleanedup,andthevirtualizationplatformshouldbeinthestate
  92. thatitwasbeforethiscallbegan.
  93. :paramcontext:securitycontext
  94. :paraminstance:InstanceobjectasreturnedbyDBlayer.
  95. Thisfunctionshouldusethedatatheretoguide
  96. thecreationofthenewinstance.
  97. :paramnetwork_info:
  98. :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
  99. :paramblock_device_info:
  100. """
  101. raiseNotImplementedError()
  102. defdestroy(self,instance,network_info,cleanup=True):
  103. """Destroy(shutdownanddelete)thespecifiedinstance.
  104. Iftheinstanceisnotfound(forexampleifnetworkingfailed),this
  105. functionshouldstillsucceed.It'sprobablyagoodideatologa
  106. warninginthatcase.
  107. :paraminstance:InstanceobjectasreturnedbyDBlayer.
  108. :paramnetwork_info:
  109. :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
  110. :paramcleanup:
  111. """
  112. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  113. raiseNotImplementedError()
  114. defreboot(self,instance,network_info):
  115. """Rebootthespecifiedinstance.
  116. :paraminstance:InstanceobjectasreturnedbyDBlayer.
  117. :paramnetwork_info:
  118. :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
  119. """
  120. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  121. raiseNotImplementedError()
  122. defsnapshot_instance(self,context,instance_id,p_w_picpath_id):
  123. raiseNotImplementedError()
  124. defget_console_pool_info(self,console_type):
  125. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  126. raiseNotImplementedError()
  127. defget_console_output(self,instance):
  128. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  129. raiseNotImplementedError()
  130. defget_ajax_console(self,instance):
  131. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  132. raiseNotImplementedError()
  133. defget_diagnostics(self,instance):
  134. """ReturndataaboutVMdiagnostics"""
  135. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  136. raiseNotImplementedError()
  137. defget_host_ip_addr(self):
  138. """
  139. RetrievestheIPaddressofthedom0
  140. """
  141. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  142. raiseNotImplementedError()
  143. defattach_volume(self,context,instance_id,volume_id,mountpoint):
  144. """Attachthediskatdevice_pathtotheinstanceatmountpoint"""
  145. raiseNotImplementedError()
  146. defdetach_volume(self,context,instance_id,volume_id):
  147. """Detachthediskattachedtotheinstanceatmountpoint"""
  148. raiseNotImplementedError()
  149. defcompare_cpu(self,cpu_info):
  150. """Comparesgivencpuinfoagainsthost確保vm能執行
  151. BeforeattemptingtomigrateaVMtothishost,
  152. compare_cpuiscalledtoensurethattheVMwill
  153. actuallyrunhere.
  154. :paramcpu_info:(str)JSONstructuredescribingthesourceCPU.
  155. :returns:Noneifmigrationisacceptable
  156. :raises::py:class:`~nova.exception.InvalidCPUInfo`ifmigration
  157. isnotacceptable.
  158. """
  159. raiseNotImplementedError()
  160. defmigrate_disk_and_power_off(self,instance,dest):
  161. """
  162. Transfersthediskofarunninginstanceinmultiplephases,turning
  163. offtheinstancebeforetheend.
  164. """
  165. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  166. raiseNotImplementedError()
  167. defsnapshot(self,context,instance,p_w_picpath_id):
  168. """
  169. Snapshotsthespecifiedinstance.
  170. :paramcontext:securitycontext
  171. :paraminstance:InstanceobjectasreturnedbyDBlayer.
  172. :paramp_w_picpath_id:Referencetoapre-createdp_w_picpaththatwill
  173. holdthesnapshot.
  174. """
  175. raiseNotImplementedError()
  176. deffinish_migration(self,context,instance,disk_info,network_info,
  177. resize_instance):
  178. #開啟一個遷移的例項,完成一個調整
  179. """Completesaresize,turningonthemigratedinstance
  180. :paramnetwork_info:
  181. :py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
  182. """
  183. raiseNotImplementedError()
  184. defrevert_migration(self,instance):
  185. #返回一個調整,推動回到例項?
  186. """Revertsaresize,poweringbackontheinstance"""
  187. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  188. raiseNotImplementedError()
  189. defpause(self,instance,callback):
  190. """Pausethespecifiedinstance."""
  191. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  192. raiseNotImplementedError()
  193. defunpause(self,instance,callback):
  194. """UnpausepausedVMinstance"""
  195. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  196. raiseNotImplementedError()
  197. defsuspend(self,instance,callback):
  198. #掛起指定的例項
  199. """suspendthespecifiedinstance"""
  200. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  201. raiseNotImplementedError()
  202. defresume(self,instance,callback):
  203. """resumethespecifiedinstance"""
  204. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  205. raiseNotImplementedError()
  206. defrescue(self,context,instance,callback,network_info):
  207. #恢復指定的例項
  208. """Rescuethespecifiedinstance"""
  209. raiseNotImplementedError()
  210. defunrescue(self,instance,callback,network_info):
  211. """Unrescuethespecifiedinstance"""
  212. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  213. raiseNotImplementedError()
  214. defupdate_available_resource(self,ctxt,host):
  215. #在computeNode表中更新電腦資源管理的資訊
  216. """UpdatescomputemanagerresourceinfoonComputeNodetable.
  217. Thismethodiscalledwhennova-computelaunches,and
  218. wheneveradminexecutes"nova-manageserviceupdate_resource".
  219. :paramctxt:securitycontext
  220. :paramhost:hostnamethatcomputemanageriscurrentlyrunning
  221. """
  222. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  223. raiseNotImplementedError()
  224. deflive_migration(self,ctxt,instance_ref,dest,
  225. post_method,recover_method):
  226. #分發處理高負荷,當有高負荷操作時候,大量生成live_mirgration
  227. """Spawninglive_migrationoperationfordistributinghigh-load.
  228. :paramctxt:securitycontext
  229. :paraminstance_ref:
  230. nova.db.sqlalchemy.models.Instanceobject
  231. instanceobjectthatismigrated.
  232. :paramdest:destinationhost
  233. :parampost_method:
  234. postoperationmethod.
  235. expectednova.compute.manager.post_live_migration.
  236. :paramrecover_method:
  237. recoverymethodwhenanyexceptionoccurs.
  238. expectednova.compute.manager.recover_live_migration.
  239. """
  240. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  241. raiseNotImplementedError()
  242. defrefresh_security_group_rules(self,security_group_id):
  243. #改變安全組之後呼叫
  244. """Thismethodiscalledafterachangetosecuritygroups.
  245. Allsecuritygroupsandtheirassociatedrulesliveinthedatastore,
  246. andcallingthismethodshouldapplytheupdatedrulestoinstances
  247. runningthespecifiedsecuritygroup.
  248. Anerrorshouldberaisediftheoperationcannotcomplete.
  249. """
  250. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  251. raiseNotImplementedError()
  252. defrefresh_security_group_members(self,security_group_id):
  253. #當一個安全組被新增到一個例項,這個方法被呼叫
  254. """Thismethodiscalledwhenasecuritygroupisaddedtoaninstance.
  255. Thismessageissenttothevirtualizationdriversonhoststhatare
  256. runninganinstancethatbelongstoasecuritygroupthathasarule
  257. thatreferencesthesecuritygroupidentifiedby`security_group_id`.
  258. Itistheresponsiblityofthismethodtomakesureanyrules
  259. thatauthorizetrafficflowwithmembersofthesecuritygroupare
  260. updatedandanynewmemberscancommunicate,andanyremovedmembers
  261. cannot.
  262. Scenario:
  263. *wearerunningonhost'H0'andwehaveaninstance'i-0'.
  264. *instance'i-0'isamemberofsecuritygroup'speaks-b'
  265. *group'speaks-b'hasaningressrulethatauthorizesgroup'b'
  266. *anotherhost'H1'runsaninstance'i-1'
  267. *instance'i-1'isamemberofsecuritygroup'b'
  268. When'i-1'launchesorterminateswewillrecievethemessage
  269. toupdatemembersofgroup'b',atwhichtimewewillmake
  270. anychangesneededtotherulesforinstance'i-0'toallow
  271. ordenytrafficcomingfrom'i-1',dependingonifitisbeing
  272. addedorremovedfromthegroup.
  273. Inthisscenario,'i-1'couldjustaseasilyhavebeenrunningonour
  274. host'H0'andthismethodwouldstillhavebeencalled.Thepointwas
  275. thatthismethodisn'tcalledonthehostwhereinstancesofthat
  276. grouparerunning(asisthecasewith
  277. :method:`refresh_security_group_rules`)butiscalledwherereferences
  278. aremadetoauthorizingthoseinstances.
  279. Anerrorshouldberaisediftheoperationcannotcomplete.
  280. """
  281. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  282. raiseNotImplementedError()
  283. defrefresh_provider_fw_rules(self,security_group_id):
  284. #這觸發一個基於資料庫改變的防火牆的更新
  285. """Thistriggersafirewallupdatebasedondatabasechanges.
  286. Whenthisiscalled,ruleshaveeitherbeenaddedorremovedfromthe
  287. datastore.Youcanretrieveruleswith
  288. :method:`nova.db.api.provider_fw_rule_get_all`.
  289. Providerrulestakeprecedenceoversecuritygrouprules.IfanIP
  290. wouldbeallowedbyasecuritygroupingressrule,butblockedby
  291. aproviderrule,thenpacketsfromtheIParedropped.Thisincludes
  292. intra-projecttrafficinthecaseoftheallow_project_net_traffic
  293. flagforthelibvirt-derivedclasses.
  294. """
  295. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  296. raiseNotImplementedError()
  297. defreset_network(self,instance):
  298. """resetnetworkingforspecifiedinstance"""
  299. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  300. pass
  301. defensure_filtering_rules_for_instance(self,instance_ref,network_info):
  302. #設定過濾規則,並等待它完成
  303. """Settingupfilteringrulesandwaitingforitscompletion.
  304. Tomigrateaninstance,filteringrulestohypervisors
  305. andfirewallsareinevitableondestinationhost.
  306. (Waitingonlyforfilteringrulestohypervisor,
  307. sincefilteringrulestofirewallrulescanbesetfaster).
  308. Concretely,thebelowmethodmustbecalled.
  309. -setup_basic_filtering(fornova-basic,etc.)
  310. -prepare_instance_filter(fornova-instance-instance-xxx,etc.)
  311. to_xmlmayhavetobecalledsinceitdefinesPROJNET,PROJMASK.
  312. butlibvirtmigratesthosevaluethroughmigrateToURI(),
  313. so,noneedtobecalled.
  314. Don'tusethreadforthismethodsincemigrationshould
  315. notbestartedwhensetting-upfilteringrulesoperations
  316. arenotcompleted.
  317. :paramsinstance_ref:nova.db.sqlalchemy.models.Instanceobject
  318. """
  319. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  320. raiseNotImplementedError()
  321. defunfilter_instance(self,instance,network_info):
  322. """Stopfilteringinstance"""
  323. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  324. raiseNotImplementedError()
  325. defset_admin_password(self,context,instance_id,new_pass=None):
  326. """
  327. Settherootpasswordonthespecifiedinstance.
  328. Thefirstparameterisaninstanceofnova.compute.service.Instance,
  329. andsotheinstanceisbeingspecifiedasinstance.name.Thesecond
  330. parameteristhevalueofthenewpassword.
  331. """
  332. raiseNotImplementedError()
  333. definject_file(self,instance,b64_path,b64_contents):
  334. """在指定的例項上寫檔案
  335. Writesafileonthespecifiedinstance.
  336. Thefirstparameterisaninstanceofnova.compute.service.Instance,
  337. andsotheinstanceisbeingspecifiedasinstance.name.Thesecond
  338. parameteristhebase64-encodedpathtowhichthefileistobe
  339. writtenontheinstance;thethirdisthecontentsofthefile,also
  340. base64-encoded.
  341. """
  342. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  343. raiseNotImplementedError()
  344. defagent_update(self,instance,url,md5hash):
  345. #在指定的例項中更新代理
  346. """
  347. Updateagentonthespecifiedinstance.
  348. Thefirstparameterisaninstanceofnova.compute.service.Instance,
  349. andsotheinstanceisbeingspecifiedasinstance.name.Thesecond
  350. parameteristheURLoftheagenttobefetchedandupdatedonthe
  351. instance;thethirdisthemd5hashofthefileforverification
  352. purposes.
  353. """
  354. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  355. raiseNotImplementedError()
  356. definject_network_info(self,instance,nw_info):
  357. #為指定的例項注入網路資訊
  358. """injectnetworkinfoforspecifiedinstance"""
  359. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  360. pass
  361. defpoll_rescued_instances(self,timeout):
  362. #輪詢已經恢復的例項
  363. """Pollforrescuedinstances"""
  364. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  365. raiseNotImplementedError()
  366. defhost_power_action(self,host,action):
  367. """Reboots,shutsdownorpowersupthehost."""
  368. raiseNotImplementedError()
  369. defset_host_enabled(self,host,enabled):
  370. #設定指定的主機有能力接受新的例項
  371. """Setsthespecifiedhost'sabilitytoacceptnewinstances."""
  372. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  373. raiseNotImplementedError()
  374. defplug_vifs(self,instance,network_info):
  375. """PlugsinVIFstonetworks."""
  376. #TODO(Vek):Needtopasscontextinforaccesstoauth_token
  377. raiseNotImplementedError()
  378. defupdate_host_status(self):
  379. """Refreshhoststats"""
  380. raiseNotImplementedError()
  381. defget_host_stats(self,refresh=False):
  382. """Returncurrentlyknownhoststats"""
  383. raiseNotImplementedError()
  384. deflist_disks(self,instance_name):
  385. """
  386. ReturntheIDsofallthevirtualdisksattachedtothespecified
  387. instance,asalist.TheseIDsareopaquetothecaller(theyare
  388. onlyusefulforgivingbacktothislayerasaparameterto
  389. disk_stats).TheseIDsonlyneedtobeuniqueforagiveninstance.
  390. NotethatthisfunctiontakesaninstanceID.
  391. """
  392. raiseNotImplementedError()
  393. deflist_interfaces(self,instance_name):
  394. """
  395. ReturntheIDsofallthevirtualnetworkinterfacesattachedtothe
  396. specifiedinstance,asalist.TheseIDsareopaquetothecaller
  397. (theyareonlyusefulforgivingbacktothislayerasaparameterto
  398. interface_stats).TheseIDsonlyneedtobeuniqueforagiven
  399. instance.
  400. NotethatthisfunctiontakesaninstanceID.
  401. """
  402. raiseNotImplementedError()
  403. defresize(self,instance,flavor):
  404. """
  405. Resizes/Migratesthespecifiedinstance.
  406. TheflavorparameterdetermineswhetherornottheinstanceRAMand
  407. diskspacearemodified,andifso,towhatsize.
  408. """
  409. raiseNotImplementedError()
  410. defblock_stats(self,instance_name,disk_id):
  411. """
  412. Returnperformancecountersassociatedwiththegivendisk_idonthe
  413. giveninstance_name.Thesearereturnedas[rd_req,rd_bytes,wr_req,
  414. wr_bytes,errs],whererdindicatesread,wrindicateswrite,reqis
  415. thetotalnumberofI/Orequestsmade,bytesisthetotalnumberof
  416. bytestransferred,anderrsisthenumberofrequestsheldupduetoa
  417. fullpipeline.
  418. Allcountersarelongintegers.
  419. Thismethodisoptional.Onsomeplatforms(e.g.XenAPI)performance
  420. statisticscanberetrieveddirectlyinaggregateform,withoutNova
  421. havingtodotheaggregation.Onthoseplatforms,thismethodis
  422. unused.
  423. NotethatthisfunctiontakesaninstanceID.
  424. """
  425. raiseNotImplementedError()
  426. definterface_stats(self,instance_name,iface_id):
  427. """
  428. Returnperformancecountersassociatedwiththegiveniface_idonthe
  429. giveninstance_id.Thesearereturnedas[rx_bytes,rx_packets,
  430. rx_errs,rx_drop,tx_bytes,tx_packets,tx_errs,tx_drop],whererx
  431. indicatesreceive,txindicatestransmit,bytesandpacketsindicate
  432. thetotalnum

  433. berofbytesorpacketstransferred,anderrsanddropped
  434. isthetotalnumberofpacketsfailed/dropped.
  435. Allcountersarelongintegers.
  436. Thismethodisoptional.Onsomeplatforms(e.g.XenAPI)performance
  437. statisticscanberetrieveddirectlyinaggregateform,withoutNova
  438. havingtodotheaggregation.Onthoseplatforms,thismethodis
  439. unused.
  440. NotethatthisfunctiontakesaninstanceID.
  441. """
  442. raiseNotImplementedError()

1:

2:

3:

4:
4 

轉載於:https://blog.51cto.com/brucemars/967409