PageRenderTime 75ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/grid.py

https://github.com/valeriewang/pyraos
Python | 389 lines | 382 code | 7 blank | 0 comment | 2 complexity | e55ac6a3cedf5404f1519b1c948050a3 MD5 | raw file
  1. import subprocess
  2. import MySQLdb
  3. import uuid
  4. import chilkat
  5. import os
  6. import xmlrpclib
  7. import urllib, urllib2
  8. import xml.dom.minidom
  9. import time
  10. class Grid:
  11. def __init__(self,configpath):
  12. self.configpath=configpath
  13. self.ParseConfig(configpath)
  14. def ParseConfig(self,path):
  15. cf=ConfigParser.ConfigParser()
  16. cf.read(path)
  17. self.name=cf.get('grid','name')
  18. self.type=cf.get('grid','type')
  19. self.version=cf.get('grid','version')
  20. print 'name='+self.name+' type='+self.type+' version='+self.version
  21. self.DataServerPath=cf.get('grid','DataServerPath')
  22. self.grid_port=cf.get('grid','DataServerConfigPath')
  23. self.node_port=cf.get('grid','RegionDataPath')
  24. self.GatherPath=cf.get('grid','GatherPath')
  25. self.serverlist=cf.get('grid','serverlist').split(',')
  26. def BuildServer(self):
  27. print self.serverlist
  28. mydb=DataBase(dblist=self.serverlist,host="localhost",username="opensim",password="1234")
  29. mydb.StartUp()
  30. mydb.PrepDatabase()
  31. if self.IsGrid():
  32. self.robust=RobustServer(self.serverlist[0],self.configpath,self.version)
  33. self.opensim=[]
  34. for osname in self.serverlist[1:len(self.serverlist)]:
  35. myopensim=GridOpenSimServer(osname,self.configpath,self.version)
  36. def IsGrid(self):
  37. return self.type=='grid'
  38. class ServerInstant:
  39. ServerDataCenter="http://localhost/"
  40. app=""
  41. loc=""
  42. ConfigList={}
  43. state=False
  44. Version="0.1"
  45. fileType=".rar"
  46. def __init__(self,name,type,location,version):
  47. self.id=uuid.uuid4()
  48. self.name=name
  49. self.type=type
  50. self.loc=location
  51. self.Version=version
  52. def GetServer(self):
  53. url=self.ServerDataCenter+'server/'+self.Version+self.fileType
  54. print "[GetServer]url:"+url
  55. dst=self.loc+self.Version+self.fileType
  56. print "dst:"+dst
  57. if not os.path.exists(dst):
  58. print "begin get server from "+url
  59. response=urllib2.urlopen(url)
  60. output=open(dst,'wb')
  61. output.write(response.read())
  62. output.close()
  63. print "server download ok"
  64. else:
  65. print "server data exists"
  66. def InstallServer(self):
  67. if self.fileType==".rar":
  68. unCompress=chilkat.CkRar()
  69. elif self.fileType==".zip":
  70. unCompress=chilkat.CkZip()
  71. print "begin installServer"
  72. dst=self.loc+self.Version+self.fileType
  73. unCompress.Open(dst)
  74. unCompress.Unrar(self.loc)
  75. print "install ok"
  76. if os.path.exists(self.loc+self.name):
  77. for root, dirs, files in os.walk(self.loc+self.name, topdown=False):
  78. for name in files:
  79. os.remove(os.path.join(root, name))
  80. for name in dirs:
  81. os.rmdir(os.path.join(root, name))
  82. #os.chdir(self.loc)
  83. os.removedirs(self.loc+self.name)
  84. os.rename(self.loc+"bin",self.loc+self.name)
  85. def StartUp(self):
  86. print "startup server..."
  87. print self.loc+self.name+"/"
  88. print self.loc+self.name+"/"+self.app
  89. self.soProc=subprocess.Popen(["start {0} -console rest".format(self.loc+self.name+"/"+self.app)],cwd=self.loc+self.name+"/",shell=True)
  90. state=True
  91. url="http://localhost:9070"
  92. self.server = xmlrpclib.Server(url)
  93. print self.server
  94. def ShutDown(self):
  95. params = {}
  96. if milliseconds is not 0:
  97. params['shutdown'] = 'delayed'
  98. params['milliseconds'] = milliseconds
  99. self.server.admin_shutdown(params)
  100. state=False
  101. class RobustServer(ServerInstant):
  102. def __init__(self,name,path,version):
  103. self.app="Robust.exe"
  104. self.ParseConfig(name,path)
  105. ServerInstant.__init__(self,self.name,"Robust",self.loc,version)
  106. self.GetServer()
  107. #self.InstallServer()
  108. self.SetConfig()
  109. self.StartUp()
  110. time.sleep(10) #check if the server startup
  111. self.CreateUser()
  112. def ParseConfig(self,name,path):
  113. self.name=name
  114. cf=ConfigParser.ConfigParser()
  115. cf.read(path)
  116. print 'robust server name:'+name
  117. self.loc=cf.get(name,'Location')
  118. self.DBProvider=cf.get(name,'DBProvider')
  119. self.ConnString=cf.get(name,'ConnString')
  120. self.DBTable=self.ConnString.split(';')[1].split('=')[1]
  121. print 'robust database table is '+self.DBTable
  122. self.RemoteUser=cf.get(name,"RemoteUser")
  123. self.RemotePsw=cf.get(name,"RemotePsw")
  124. self.RemotePath=cf.get(name,"RemotePath")
  125. self.RemotePort=cf.get(name,'RemotePort')
  126. self.LoginPath=cf.get(name,'loginhost')
  127. self.AssetLoader=cf.get(name,'AssetLoader')
  128. print 'robust login path is '+self.LoginPath
  129. ulist=cf.get(name,"UserList").split(';')
  130. self.userlist=[]
  131. for userstring in ulist:
  132. print "user:"+userstring
  133. user=User(userstring)
  134. self.userlist.append(user)
  135. def SetConfig(self):
  136. configtype="Robust.ini"
  137. source=self.ServerDataCenter+"config/"+configtype
  138. dst=self.loc+self.name+"/"+configtype
  139. print 'get {0} from {1} to {2}'.format(configtype,source,dst)
  140. response=urllib2.urlopen(source)
  141. output=open(dst,'w')
  142. s=''
  143. for line in response.readlines():
  144. s=s+line.lstrip()
  145. output.write(s)
  146. output.close()
  147. cf=CAppConfig(dst)
  148. cf.set('DatabaseService','StorageProvider','\"'+self.DBProvider+'\"')
  149. cf.set('DatabaseService','ConnectionString','\"'+self.ConnString+'\"')
  150. #cf.set('AssetService','AssetLoaderEnabled',self.AssetLoader)
  151. cf.set('Network','ConsoleUser',self.RemoteUser)
  152. cf.set('Network','ConsolePass',self.RemotePsw)
  153. cf.set('Network','ConsolePort',self.RemotePort)
  154. fp=open(dst,'wb')
  155. cf.write(fp)
  156. fp.close()
  157. def CreateUser(self,startRegionX=128,startRegionY=128):
  158. print "remotepath="+self.RemotePath
  159. console=UserConsoleClient(self.RemotePath)
  160. for user in self.userlist:
  161. cmd="create user "+user.firstname+" "+user.lastname+" "+user.password+" "+user.email
  162. print "[create user]cmd="+cmd
  163. console.do_cmd(cmd)
  164. console.close()
  165. class GridOpenSimServer(ServerInstant):
  166. def __init__(self,name,path,version):
  167. self.app="opensim.exe"
  168. self.ParseConfig(name,path)
  169. ServerInstant.__init__(self,self.name,"OpenSim",self.loc,version)
  170. self.GetServer()
  171. #self.InstallServer()
  172. self.SetConfig()
  173. self.SetRegions()
  174. self.StartUp()
  175. time.sleep(10) #check if the server startup
  176. #self.EditEstate()
  177. def ParseConfig(self,name,path):
  178. self.name=name
  179. cf=ConfigParser.ConfigParser()
  180. cf.read(path)
  181. print 'server name is '+name
  182. self.loc=cf.get(name,'Location')
  183. self.DBProvider=cf.get(name,'DBProvider')
  184. self.ConnString=cf.get(name,'ConnString')
  185. self.DBTable=self.ConnString.split(';')[1].split('=')[1]
  186. print 'database table is '+self.DBTable
  187. self.RemoteUser=cf.get(name,"RemoteUser")
  188. self.RemotePsw=cf.get(name,"RemotePsw")
  189. self.RemotePath=cf.get(name,"RemotePath")
  190. self.RemotePort=cf.get(name,'RemotePort')
  191. self.httplistenerport=cf.get(name,"httplistenerport")
  192. rlist=cf.get(name,"Regions").split(';')
  193. self.RegionsList=[]
  194. for regionstring in rlist:
  195. print "region:"+regionstring
  196. region=Region(regionstring)
  197. self.RegionsList.append(region)
  198. def SetConfig(self):
  199. configtype="OpenSim.ini"
  200. source=self.ServerDataCenter+"config/"+configtype
  201. dst=self.loc+self.name+"/"+configtype
  202. response=urllib2.urlopen(source)
  203. output=open(dst,'wb')
  204. s=''
  205. for line in response.readlines():
  206. s=s+line.lstrip()
  207. output.write(s)
  208. output.close()
  209. cf=CAppConfig(dst)
  210. cf.set('Architecture','Include-Architecture',"config-include/Grid.ini")
  211. cf.set('Network','http_listener_port',self.httplistenerport)
  212. cf.set('Network','ConsoleUser',self.RemoteUser)
  213. cf.set('Network','ConsolePass',self.RemotePsw)
  214. cf.set('Network','ConsolePort',self.RemotePort)
  215. fp=open(dst,'wb')
  216. cf.write(fp)
  217. fp.close()
  218. configtype="GridCommon.ini"
  219. source=self.ServerDataCenter+"config/"+configtype
  220. dst=self.loc+self.name+"/config-include/"+configtype
  221. response=urllib2.urlopen(source)
  222. output=open(dst,'wb')
  223. s=''
  224. for line in response.readlines():
  225. s=s+line.lstrip()
  226. output.write(s)
  227. output.close()
  228. cf=CAppConfig(dst)
  229. cf.set('DatabaseService','Storage',self.DBProvider)
  230. cf.set('DatabaseService','ConnectionString',self.ConnString)
  231. fp=open(dst,'wb')
  232. cf.write(fp)
  233. fp.close()
  234. def SetRegions(self):
  235. dst=self.loc+self.name+"/Regions/Regions.ini"
  236. fp=open(dst,'w')
  237. fp.close()
  238. cf=ConfigParser.ConfigParser()
  239. cf.read(dst)
  240. for region in self.RegionsList:
  241. cf.add_section(region.name)
  242. cf.set(region.name,'RegionUUID',region.uuid)
  243. cf.set(region.name,'Loction',region.locx+','+region.locy)
  244. cf.set(region.name,'InternalAddress','0.0.0.0')
  245. cf.set(region.name,'InternalPort',region.port)
  246. cf.set(region.name,'AllowAlternatePorts','False')
  247. cf.set(region.name,'ExternalHostName','SYSTEMIP')
  248. fp=open(dst,'wb')
  249. cf.write(fp)
  250. fp.close()
  251. def LoadRegions(self):
  252. console=UserConsoleClient(self.RemotePath)
  253. for region in self.RegionList:
  254. cmd="change region "+region.name
  255. console.do_cmd(cmd)
  256. cmd='load oar '+self.oar
  257. console.do_cmd(cmd)
  258. console.close()
  259. # def EditEstate(self):
  260. # print self.RemotePath
  261. # console=UserConsoleClient(self.RemotePath)
  262. # cmd="MyEatate"
  263. # console.do_cmd(cmd)
  264. # cmd="test"
  265. # console.do_cmd(cmd)
  266. # cmd="user"
  267. # console.do_cmd(cmd)
  268. # for Region in self.RegionList:
  269. # cmd="yes"
  270. # console.do_cmd(cmd)
  271. # console.close()
  272. class DataBase:
  273. path="C:/wamp"
  274. app="/wampmanager.exe"
  275. host="localhost"
  276. user="opensim"
  277. psw="1234"
  278. dbList=[]
  279. conn=""
  280. state=False
  281. def __init__(self,host="localhost",username="opensim",password="1234",dblist=["robust","opensim0,opensim1,opensim2"],path="C:/wamp",app="/wampmanager.exe"):
  282. self.host=host
  283. self.app=app
  284. self.user=username
  285. self.psw=password
  286. self.path=path
  287. self.dbList=dblist
  288. def PrepDatabase(self):
  289. if self.state==True:
  290. print "[PrepDataBase]begin prepare Database"
  291. self.conn=MySQLdb.connect(host=self.host,user=self.user,passwd=self.psw)
  292. cur=self.conn.cursor()
  293. for i in self.dbList:
  294. sql="CREATE DATABASE IF NOT EXISTS "+i
  295. print "[PrepDataBase]sql:"+sql
  296. cur.execute(sql)
  297. print "Database is prepared"
  298. def ClearDatabase(self):
  299. if self.state==True:
  300. print "[ClearDatabase] begin clear database"
  301. self.conn=MySQLdb.connect(host=self.host,user=self.user,passwd=self.psw)
  302. cur=self.conn.cursor()
  303. for i in self.dbList:
  304. sql="DROP DATABASE IF EXISTS "+i
  305. print "[ClearDatabase] sql:"+sql
  306. cur.execute(sql)
  307. def StartUp(self):
  308. self.mysqlProc=subprocess.Popen([self.path+self.app],cwd=self.path)
  309. print self.mysqlProc.returncode
  310. print "DataBase have been run"
  311. self.state=True
  312. success=False
  313. while not success:
  314. try:
  315. self.conn=MySQLdb.connect(host=self.host,user=self.user,passwd=self.psw)
  316. success=True
  317. except:
  318. success=False
  319. class User:
  320. def __init__(self,userstring):
  321. self.firstname,self.lastname,self.password,self.email=userstring.split(',')
  322. class Region:
  323. def __init__(self,regionstring):
  324. self.uuid=uuid.uuid4()
  325. self.name,self.locx,self.locy,self.port,self.oar=regionstring.split(',')
  326. class UserConsoleClient():
  327. def __init__(self, addr):
  328. self.addr = addr
  329. url = self.addr + 'StartSession/'
  330. params = urllib.urlencode({
  331. 'USER': 'User', # REST username
  332. 'PASS': '1234' # REST password
  333. })
  334. print url
  335. data = urllib2.urlopen(url, params).read()
  336. print data
  337. dom = xml.dom.minidom.parseString(data)
  338. elem = dom.getElementsByTagName('SessionID')
  339. self.sessionid = elem[0].childNodes[0].nodeValue
  340. def close(self):
  341. url = self.addr + 'CloseSession/'
  342. params = urllib.urlencode({
  343. 'ID': self.sessionid
  344. })
  345. print urllib2.urlopen(url, params).read()
  346. def do_cmd(self, cmd):
  347. url = self.addr + 'SessionCommand/'
  348. params = urllib.urlencode({
  349. 'ID': self.sessionid,
  350. 'COMMAND': cmd
  351. })
  352. print urllib2.urlopen(url, params).read()
  353. def read_buffer(self):
  354. url = self.addr + 'ReadResponses/' + self.sessionid + '/'
  355. params = urllib.urlencode({
  356. 'ID': self.sessionid
  357. })
  358. print urllib2.urlopen(url, params).read()
  359. if __name__=='__main__':
  360. myGridManager=GridManager('./MainConfig.ini')
  361. myGridManager.Start()
  362. # mygrid=Grid('./MainConfig.ini')
  363. # mygrid.BuildServer()