1. # coding: UTF-8
  2. import platform
  3. from _utils.patrol2 import run_cmd, data_format, report_format
  4. import os, sys, re, json, copy
  5. import stat
  6. import socket
  7. import stat
  8. import sqlite3
  9.  
  10. #
  11. # conn=sqlite3.connect(':memory:')
  12. if os.path.exists('was_patrol.db'):
  13. os.remove('was_patrol.db')
  14. conn = sqlite3.connect('was_patrol.db')
  15. c = conn.cursor()
  16. c.execute('''CREATE TABLE WAS
  17. (ID INT PRIMARY KEY NOT NULL,
  18. CELL CHAR(50),
  19. HOME CHAR(50),
  20. CLUSTER CHAR(50),
  21. NODE CHAR(50),
  22. SERVER CHAR(50),
  23. STATE CHAR(50),
  24. PORTS CHAR(500),
  25. HOST CHAR(50));''')
  26. print "Table created successfully"
  27. conn.commit()
  28.  
  29. version = version.split('.')[0]
  30. content = """import sys, java
  31. def get_names(type,parent_obj=None):
  32. if not parent_obj:
  33. obj_list = AdminConfig.list(type)
  34. else:
  35. obj_list = AdminConfig.list(type, parent_obj)
  36. if len(obj_list) == 0:
  37. return [],None
  38. obj_lists = obj_list.split(lineSeparator)
  39. names=[]
  40. for obj in obj_lists:
  41. name = AdminConfig.showAttribute(obj, "name")
  42. names.append(name)
  43. return names,obj_lists
  44.  
  45. lineSeparator = java.lang.System.getProperty('line.separator')
  46.  
  47. cell_names,cells=get_names("Cell")
  48. reports = []
  49. print cell_names,cells
  50. for cell in cells:
  51. cell_name=AdminConfig.showAttribute(cell, "name")
  52.  
  53. cluster_names,clusters=get_names("ServerCluster",parent_obj=cell)
  54. node_names, nodes = get_names("Node", parent_obj=cell)
  55.  
  56. for node in nodes:
  57. nname = AdminConfig.showAttribute(node, "name")
  58. server_names, servers = get_names("Server", parent_obj=node)
  59. hostname= AdminConfig.showAttribute(node, "hostName")
  60.  
  61. print 'node:',node
  62. print 'servers:',servers
  63. for server in servers:
  64. type=AdminConfig.showAttribute(server, "serverType")
  65. if type=='NODE_AGENT':
  66. continue
  67. sname = AdminConfig.showAttribute(server, "name")
  68. cname = AdminConfig.showAttribute(server, "clusterName")
  69.  
  70. runserv = AdminConfig.getObjectName(server)
  71. if len(runserv) > 0:
  72. state = AdminControl.getAttribute(runserv, "state")
  73. else:
  74. state='down'
  75.  
  76. other_port=id=''
  77. if int('{version}')>=6:
  78. ports=AdminTask.listServerPorts(sname, '[-nodeName '+nname+']')
  79. else:
  80. ports=[]
  81. endpoints=AdminConfig.list('EndPoint', server).split(lineSeparator)
  82. print endpoints
  83. #endpoints=AdminConfig.list('EndPoint', AdminConfig.getid( '/Cell:'+cell_name+'/Node:'+nname+'/Server:'+sname+'/')).split(lineSeparator)
  84. for endpoint in endpoints[1:]:
  85. end_result=AdminConfig.show(endpoint).split(lineSeparator)
  86. print end_result
  87. if end_result:
  88. ports.append(end_result[1].split()[1].split(']')[0])
  89. ports=','.join(ports)
  90. print ports
  91.  
  92. id=AdminConfig.getid( '/Cell:'+cell_name+'/VirtualHost:default_host/')
  93. if not id:
  94. id=AdminConfig.getid( '/Cell:'+cell_name+'/VirtualHost:admin_host/')
  95. if id:
  96. other_port=AdminConfig.list('HostAlias',id ).split(lineSeparator)[0]
  97. other_port=AdminConfig.showAttribute(other_port,'port')
  98. if not cname:
  99. # no cluster and has server
  100. reports.append({{'cell': cell_name, 'cluster': 'N/A', 'server': sname, 'node': nname,'obj':server,'state':state,'ports':ports,'host':hostname,'other_port':other_port}})
  101. else:
  102. # has cluster and node
  103. reports.append({{'cell': cell_name, 'cluster': cname, 'server': sname, 'node': nname,
  104. 'obj': server,'state':state,'ports':ports,'host':hostname,'other_port':other_port}})
  105. print 'clusters',clusters
  106. reports1=[]
  107. if clusters:
  108. for cluster in clusters:
  109. cluster_name = AdminConfig.showAttribute(cluster, "name")
  110. memberList = AdminConfig.showAttribute(cluster, "members")
  111.  
  112. if memberList!='[]' and memberList!=[] :
  113. #has cluster and node
  114. #pass
  115. members = memberList[1:len(memberList)-1].split(" ")
  116. for member in members:
  117. mname = AdminConfig.showAttribute(member, "memberName")
  118. nname = AdminConfig.showAttribute(member, "nodeName")
  119. reports1.append({{'cell':cell_name,'cluster':cluster_name,'server':mname,'node':nname,'obj':server}})
  120. else:
  121. # has cluster and no node
  122. reports1.append({{'cell':cell_name,'cluster':cluster_name,'server':'N/A','node':'N/A','obj':None}})
  123.  
  124. print "==data=="
  125. print reports
  126. print "==data=="
  127. print "==datas=="
  128. print reports1
  129. print "==datas=="
  130. """.format(version=version)
  131.  
  132. if 'Windows' in platform.system():
  133. tmp_script = 'C:\\patrol.py'
  134. else:
  135. tmp_script = '/tmp/patrol.py'
  136. with open(tmp_script, 'w') as f:
  137. f.write(content)
  138. os.chmod(tmp_script, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
  139.  
  140. hostname = platform.node()
  141.  
  142. was_homes = was_home
  143. datas = {'cell': [], 'cluster': [], 'node': [], 'server': []}
  144. all_reports = []
  145. cell_reports = []
  146. cluster_reports = []
  147. server_reports = []
  148. resource = []
  149. count = 0
  150. for was_home in was_homes.split(','):
  151. run_script = os.path.join('{}'.format(was_home), 'bin/wsadmin.sh')
  152. if mw_password:
  153. password = '-password {}'.format(mw_password)
  154. else:
  155. password = ''
  156.  
  157. if 'Windows' in platform.system():
  158. run_script = os.path.join('{}'.format(was_home), 'bin', 'wsadmin.bat')
  159. cmd = '"{}" -username {} {} -lang jython -f {}'.format(run_script, mw_user, password,
  160. tmp_script)
  161. else:
  162. cmd = 'su {} -c "{} -username {} {} -lang jython -f {}"'.format(os_was_user,
  163. run_script, mw_user,
  164. password,
  165. tmp_script)
  166. print cmd
  167. code, out = run_cmd(cmd)
  168. print out
  169. if 'Ensure that user and password are correct' in out:
  170. print '请确认输入的用户名和密码是否正确'
  171. sys.exit(1)
  172. if code:
  173. print out
  174. sys.exit(1)
  175. try:
  176. res = re.findall(r'==data==([\s\S]*)==data==', out)
  177. if not res:
  178. print '无输出'
  179. sys.exit(1)
  180. res = eval(res[0].strip())
  181.  
  182. res1 = re.findall(r'==datas==([\s\S]*)==datas==', out)
  183. if not res1:
  184. print '无输出'
  185. sys.exit(1)
  186. res1 = eval(res1[0].strip())
  187. print '集群信息', res1
  188.  
  189. except Exception as e:
  190. print e
  191. sys.exit(1)
  192. resource.append({'res': res, 'washome': was_home})
  193.  
  194. cell_name = None
  195. for i in res:
  196. cell_name = i['cell']
  197. if i['cell'] not in datas['cell']:
  198. datas['cell'].append(i['cell'])
  199. if i['cluster'] not in datas['cluster']:
  200. datas['cluster'].append(i['cluster'])
  201. if i['node'] not in datas['node']:
  202. datas['node'].append(i['node'])
  203. if i['server'] not in datas['server']:
  204. datas['server'].append(i['server'])
  205.  
  206. c = conn.cursor()
  207.  
  208. port = ''
  209. ports = i.get('ports', '')
  210. if int(version) >= 6:
  211. for j in ports.split('\n'):
  212. if j.startswith('[[WC_adminhost ') and i['server'] == 'dmgr':
  213. port = j.rstrip('] ]]] ]').split(' ')[-1]
  214. if not port:
  215. for j in ports.split('\n'):
  216. if j.startswith('[[WC_defaulthost '):
  217. port = j.rstrip('] ]]] ]').split(' ')[-1]
  218. if not port:
  219. for j in ports.split('\n'):
  220. if j.startswith('[[WEBSERVER_ADDRESS '):
  221. port = j.rstrip('] ]]] ]').split(' ')[-1]
  222. else:
  223. print '端点:', ports
  224. import requests
  225.  
  226. for j in ports.split(','):
  227. print j
  228. try:
  229. res = requests.get('http://localhost:{}/snoop'.format(j))
  230. if res.status_code == 200:
  231. port = j
  232. break
  233. if not port:
  234. res = requests.get('https://localhost:{}/snoop'.format(j), is_verify=False)
  235. if res.status_code == 200:
  236. port = j
  237. break
  238. except:
  239. pass
  240. if not port:
  241. port = ports.split(',')[0]
  242.  
  243. print 'port',port
  244.  
  245. state= i.get('state','')
  246. if int(version) <= 5:
  247. cmd = "netstat -Aan|grep -w '*.{}'".format(port)
  248. code, res = run_cmd(cmd)
  249. if res and 'LISTEN' in res.split()[-1]:
  250. state = 'STARTED'
  251.  
  252. c.execute("INSERT INTO WAS (ID,CELL,HOME,CLUSTER,NODE,SERVER,STATE,PORTS,HOST) \
  253. VALUES ({}, '{}', '{}', '{}', '{}','{}','{}','{}','{}' )".format(count,
  254. i['cell'],
  255. was_home,
  256. i['cluster'],
  257. i['node'],
  258. i['server'],state,
  259. port,
  260. i.get('host',
  261. '')))
  262. count += 1
  263.  
  264. conn.commit()
  265. print datas
  266.  
  267. cursor = conn.execute("SELECT distinct CELL from WAS")
  268. cells = []
  269. for row in cursor:
  270. cell = row[0]
  271. if cell not in cells:
  272. cells.append(cell)
  273. cell_reports.append(data_format('单元名称', cell, alert=0, group_name="单元情况"))
  274. cell_num = len(cells)
  275. if cell_num == 1:
  276. all_reports.append(report_format("{}".format(hostname), cell_reports))
  277. else:
  278. all_reports.append(report_format("{}".format(hostname), childs=cell_reports))
  279.  
  280. cell_clusters = []
  281. cell_cluster_report = {}
  282. cursor = conn.execute("SELECT id, cell, home,cluster,node, server,state,ports,host from WAS")
  283. for row in cursor:
  284. cell = row[1]
  285. node = row[4]
  286. server = row[5]
  287. home = row[2]
  288. cluster = row[3]
  289. if cell_num == 1:
  290. cell_cluster = '{}'.format(hostname)
  291. else:
  292. cell_cluster = '{}/{}'.format(hostname, cell)
  293. if cell_cluster not in cell_clusters:
  294. cell_cluster_report.update({cell_cluster: []})
  295. cell_clusters.append(cell_cluster)
  296. if cluster not in cell_cluster_report[cell_cluster]:
  297. cell_cluster_report[cell_cluster].append(cluster)
  298.  
  299. reports = []
  300. for k, v in cell_cluster_report.items():
  301. for i in v:
  302. reports.append(data_format('集群名称', i, alert=0, group_name="集群名称"))
  303. all_reports.append(report_format(k, childs=reports))
  304.  
  305. reports = json.dumps(all_reports)
  306. print reports

  

sqlite处理数据的更多相关文章

  1. Android 一键直接查看Sqlite数据库数据

    转自:http://www.cnblogs.com/trinea/archive/2012/11/16/2773656.html 本文主要介绍Android开发中如何一键直接查看sqlite数据库中的 ...

  2. 解决sqlite删除数据后,文件大小不变问题(VACUUM)

    删除表格的全部数据: DELETE FROM [Name] 当在sqlite中删除了大量数据后,数据库文件的大小还是那样,没有变.原因是:从Sqlite删除数据后,未使用的磁盘空间被添加到一个内在的” ...

  3. Python读取和处理文件后缀为".sqlite"的数据文件

    最近在弄一个项目分析的时候,看到有一个后缀为”.sqlite”的数据文件,由于以前没怎么接触过,就想着怎么用python来打开并进行数据分析与处理,于是稍微研究了一下. SQLite是一款非常流行的关 ...

  4. 解决sqlite删除数据或者表后,文件大小不变的问题

    原因分析: sqlite采用的是变长纪录存储,当你从Sqlite删除数据后,未使用的磁盘空间被添加到一个内在的"空闲列表"中用于存储你下次插入的数据,用于提高效率,磁盘空间并没有丢 ...

  5. 解决sqlite删除数据后,文件大小不变问题 转载

    原文地址:http://blog.csdn.net/yangchun1213/article/details/7656146   说了这么多,没进主题,我的主题是给Sqlite在删除数据后擦屁股. 大 ...

  6. Android开发之利用SQLite进行数据存储

    Android开发之利用SQLite进行数据存储 Android开发之利用SQLite进行数据存储 SQLite数据库简单介绍 Android中怎样使用SQLite 1 创建SQLiteOpenHel ...

  7. sqlite删除数据

    sqlite删除数据 某日, 在使用sqlite的时候发现查询速度极慢, 查看了一下文件大小, sqlite数据库文件已经达到了 22G! 对于一个文件数据库来说, 已经相当致命了,先不说后面如果解决 ...

  8. C#(.net)实现用apache activemq传递SQLite的数据

    版权声明:本文为搜集借鉴各类文章的原创文章,转载请注明出处:http://www.cnblogs.com/2186009311CFF/p/6382623.html. C#(.net)实现用apache ...

  9. mono for android中使用dapper或petapoco对sqlite进行数据操作

    在mono for android中使用dapper或petapoco,很简单,新建android 类库项目,直接把原来的文件复制过来,对Connection连接报错部分进行注释和修改就可以运行了.( ...

  10. 从SQLite获取数据完成一个产品信息展示

    在ios实际开发当中,我们常常用到Core Data做为数据储存首选.但在处理一些大量复杂的数据值且数据之间相互关联的时候,这就不得不使用关系型数据库来实现.例如一个导航程序,自身应该包含大量的地图自 ...

随机推荐

  1. SpringBoot实战一:发送邮件

    目录 邮件协议 引入邮件包 创建邮件类和测试类,写yml文件 文本邮件,HTML邮件,附件邮件,图片邮件 模板邮件 异常处理 来进行一个SpringBoot项目的实战,发送一下邮件,这里我们先了解一下 ...

  2. 16、JDBC-DBUtils封装

    使用DBUtils写个通用CURD小工具 依赖配置 pom.xml <?xml version="1.0" encoding="UTF-8"?> & ...

  3. 清理sql2012数据库日志

    --1.先把数据库设置为简单模式(右击数据库名->点'属性'->点'选项'->恢复模式改成'简单'->点'确定'按钮,--2.再执行下面的语句(或者右击数据库点'任务'-> ...

  4. Web前端框架与移动应用开发第八章

    Web前端框架与移动应用开发:制作58招聘专题页 1.html代码: <!DOCTYPE html><html><head> <meta charset=&q ...

  5. 自学python 2.

    1.T or F 1>1 or 3<4 or 4>5 and 2>1 and 9>8 or 7<6 t not 2>1 and 3<4 or 4> ...

  6. Vector集合

    Vector集合也是List接口的一个实现类,但是它是同步的,这就意味着是单线程的,速度比较慢,被ArrayList集合所取代了(PS:为什么我现在也还不知道,先记录了)

  7. python中\r的意义及用法

    \r的意义 \r 表示将光标的位置回退到本行的开头位置 \b表示将光标的位置回退一位 在python里print会默认进行换行,可以通过修改参数让其不换行 (1) python2中可以在print语句 ...

  8. Sliverlight常见错误集锦

    1. 使用GridSplitter时候(参考),出现如下错误 C# 中的错误Error 2 The type 'sp:GridSplitter' was not found. Verify…… 对程序 ...

  9. js 操作对象 记录

    js 对象记录一下: let obj_1 = { name : 'james', age : '22', sex: '1' } for ( i in obj_1 ) { console.log(i) ...

  10. .Net结合JQuery实现向aspx后台函数进行请求。

    $.ajax({     url: "Default.aspx/aaaa",     async: false,     type: "POST",     c ...