Grafana-監控-報警-運維文檔


Grafana運維文檔

2019/09/23 Chenxin Wuweiwei

參考資料
https://grafana.com/grafana
https://blog.52itstyle.vip/archives/1984/
https://blog.52itstyle.vip/archives/2014/
https://blog.52itstyle.vip/archives/2029/
https://blog.52itstyle.vip/archives/2049/
https://blog.52itstyle.vip/archives/2059/
https://blog.csdn.net/liuxiao723846/article/details/79627092
https://www.cnblogs.com/txwsqk/p/3974915.html
https://www.cnblogs.com/smallSevens/p/7837361.html

其他Grafana,Zabbix,Nagios,Ganglia,Open-Falcon 方案,請參考<Zabbix監控方案>文檔內的說明.

簡介

官方簡介
The analytics platform for all your metrics
Grafana allows you to query, visualize, alert on and understand your metrics no matter where they are stored. Create, explore, and share dashboards with your team and foster a data driven culture.
使用GO,JS語言開發.有以下特點
可視化:快速和靈活的客戶端圖形.面板插件.
報警:可視化地為最重要的指標定義警報規則。Grafana將持續評估它們,並發送通知。
通知:警報更改狀態時,它會發出通知。接收電子郵件通知。
動態儀表盤:使用模板變量創建動態和可重用的儀表板,這些模板變量作為下拉菜單出現在儀表板頂部。
混合數據源:在同一個圖中混合不同的數據源!可以根據每個查詢指定數據源。這甚至適用於自定義數據源。
注釋:注釋來自不同數據源圖表。將鼠標懸停在事件上可以顯示完整的事件元數據和標記。
過濾器:過濾器允許您動態創建新的鍵/值過濾器,這些過濾器將自動應用於使用該數據源的所有查詢。

可以使用Grafana對接阿里雲的日志服務(Grafana是一個日志模板展示的工具,界面的展示需要另一方平台提供日志數據源),Grafana可以在接受到數據源后,新增自己支持的圖形界面插件(包括條形圖、餅狀圖、世界地圖)來展示日志數據,一個展示界面稱為Panel.

官網注冊賬號

以便獲取如worldPing的插件支持.
http://grafana.com/profile/api-keys
郵箱 38042484@qq.com
用戶名 Chanix
pw: xxx
AK: eyJrI...MwNzl9

安裝部署

Hardware requirements
Grafana does not use a lot of resources and is very lightweight in use of memory and CPU. Minimum recommendation is 255mb of memory and 1 CPU.

下載grafana包
wget https://dl.grafana.com/oss/release/grafana-6.3.6-1.x86_64.rpm
yum localinstall grafana-6.3.6-1.x86_64.rpm

安裝完后,官網說明(修改配置文件)
Choose your Configuration Options
The Grafana backend has a number of configuration options defined in its config file (usually located at /etc/grafana/grafana.ini on linux systems).
In this config file you can change things like the default admin password, http port, grafana database (sqlite3, mysql, postgres), authentication options (google, github, ldap, auth proxy) along with many other options.
Start your grafana server. Login with your admin user (default admin/admin). Open side menu (click the Grafana icon in top menu) head to Data Sources and add your data source.

目錄文件結構與配置文件說明

官方配置文件說明 https://grafana.com/docs/installation/configuration/

啟停
/etc/rc.d/init.d/grafana-server 將init.d腳本復制到 /etc/init.d/grafana-server 啟停腳本.會調用二進制以及多個配置文件和變量定義文件.
/usr/sbin/grafana-cli,grafana-server 二進制文件,由啟停腳本調用
/usr/lib/systemd/system/grafana-server.service  systemd服務

配置
/etc/sysconfig/grafana-server   grafana的環境變量,如LOG_DIR,DATA_DIR,CONF_FILE,PLUGINS_DIR,PID_FILE_DIR.被啟停腳本調用.
/etc/grafana/grafana.ini    主配文件.優先級最高的配置文件,會覆蓋之前的配置文件設置.啟停腳本調用它.
/etc/grafana/ldap.toml  被grafana.ini配置文件引用(ini里默認關閉)

日志
/var/log/grafana/    日志目錄

數據
/var/lib/grafana/    默認配置指定sqlite3數據庫 /var/lib/grafana/grafana.db.升級時,需要提前備份該數據文件.

其他
/usr/share/grafana  含bin,conf,public,scripts,tools文件夾
/usr/share/grafana/public/sass/grafana.dark.scss
/usr/share/grafana/public/img/grafana_net_logo.svg
/usr/share/grafana/public/fonts/grafana-icons.svg
/usr/share/grafana/public/app/plugins/datasource/ 插件數據源
/usr/share/grafana/public/build/grafana.dark.4cb59bbda465c391ae8e.css
...

配置文件修改:
端口,認證方式等.具體略.

啟停管理

systemd方式
systemctl daemon-reload
systemctl start grafana-server
systemctl status grafana-server

開機自啟
systemctl enable grafana-server.service

啟動后進程與開放端口

/usr/sbin/grafana-server --config=/etc/grafana/grafana.ini --pidfile=/var/run/grafana/grafana-server.pid --packaging=rpm cfg:default.paths.logs=/var/log/grafana cfg:default.paths.data=/var/lib/grafana cfg:default.paths.plugins=/var/lib/grafana/plugins cfg:default.paths.provisioning=/etc/grafana/provisioning

tcp6       0      0 :::3000                 :::*                    LISTEN      16549/grafana-serve 

用戶與權限

登陸提示修改默認密碼
admin / admin
admin / Grxxxx.....123456
之后可以對接LDAP,請移步對應章節.

grafana 的權限分為三個等級:Viewer、Editor 和 Admin,Viewer 只能查看 grafana 已經存在的面板而不能編輯,Editor 可以編輯面板,Admin 則擁有全部權限例如添加數據源、添加插件、增加 API KEY。

CLI使用

參考
https://grafana.com/docs/administration/cli/

插件

參考 https://grafana.com/docs/plugins/installation/

官方插件支持grafana-cli plugins install xxx /git/unzip 3種安裝方式.
第三方插件支持git/unzip 2種安裝方式.
會安裝到 /var/lib/grafana/plugins/ 目錄.

使用grafana-cli工具安裝
獲取可用插件列表 grafana-cli plugins list-remote
grafana-cli plugins install raintank-worldping-app 各地到站點的網絡情況監測
grafana-cli plugins install grafana-piechart-panel 增加餅狀(官方插件)安裝
grafana-cli plugins install grafana-clock-panel 鍾表形展示
grafana-cli plugins install briangann-gauge-panel
grafana-cli plugins install natel-discrete-panel
grafana-cli plugins install vonage-status-panel

插件卸載
例:grafana-cli plugins uninstall vonage-status-panel
安裝和卸載后需要重啟grafana才能夠生效

數據源的配置

數據源定義
Grafana需要提供數據后才能在模板中展示圖形,數據的格式大部分是一個json格式,里面包括各種數據的key-value鍵值對.

阿里雲數據源

阿里雲支持兩種數據源格式,
1.阿里雲官方的 GMS 雲監控數據源.
2.阿里雲的 LogService雲日志數據源.
GMS和LogService相比,使用更簡單,但是由於模板固定,當數據源傳過來的數據與模板兼容性低的時候,監控界面效果很亂.
LogService使用時因為要書寫查詢語句,難度相對要高很多,但是監控效果相比GMS要更好,實際使用時可根據兩者合並使用來提高監控效果;

coinw使用了以上2個.CMS數據源,在添加監控項的時候僅僅選擇已有的監控指標就可以.LogService數據源,通過此數據源來添加監控項的,需要根據阿里的官方文檔來寫sql的查詢語句.

阿里雲logservice數據源
參考
阿里雲文檔:
日志服務>查詢與分析>可視化分析>其他可視化方案>對接Grafana 對應網址 https://help.aliyun.com/document_detail/60952.html?spm=a2c4g.11186623.6.887.8e217c69jBQoV6
阿里雲此文檔有很多地方無法適用(查詢放入Grafana后就會卡死).

日志服務 >查詢與分析>查詢語法與功能>查詢語法 對應網址
https://help.aliyun.com/document_detail/29060.html?spm=a2c4g.11186623.6.793.28ec735djvrmG1
使用logservice數據源需要自己手寫監控查詢的語句,但是監控查詢語句較復雜.

1.安裝阿里雲日志服務插件
cd /var/lib/grafana/plugins/ 插件目錄
git clone https://github.com/aliyun/aliyun-log-grafana-datasource-plugin
systemctl restart grafana-server 重啟grafana

2.添加Log-Service 數據源
選擇左邊工具欄里面
Configuration -> datasource -> add datasource
選擇Grafana提供的Log-Service模板后,進入配置界面.配置如下.
HTTP URL: http://waf-project-1783799610063532-ap-southeast-1.ap-southeast-1.log.aliyuncs.com
Auth: 保持默認.
log service details的Project名稱: waf-project-1783799610063532-ap-southeast-1
logstore名稱: waf-logstore
AK信息: LTAIseUbaRxeHLeu ayoI3FUJg891bMRfimV4NVYudOy1th
保存.之后需要創建DashBoard(請移步對應章節).

阿里雲CMS數據源
參考
阿里雲文檔:
雲監控 >用戶指南 >可視化報表 >對接Grafana 對應網址
https://help.aliyun.com/document_detail/109434.html?spm=5176.10695662.1996646101.searchclickresult.356e2509mNXR10

1.安裝CMS插件
cd /var/lib/grafana/plugins/
git clone https://github.com/aliyun/aliyun-cms-grafana.git
systemctl restart grafana-server 重啟grafana

2.添加數據源
Name: 隨意
HTTP URL: metrics.cn-hongkong.aliyuncs.com
AK: 略

3.增加panel(具體參考對應章節)
至DashBoard里,增加新的panel->選擇對應的數據源(CMS的)->增加Query(Project里輸入幫助信息里的acs_esc_dashboard(阿里雲插件里的)->Metric、period、Y軸和X軸等.
每個ECS可以一個Query,多個ECS,就多個查詢.
完成后,數據會展示出來.通過Visualization修改圖形展示細節.

DashBoard(儀表盤),Variables(模板變量)與Panel(看板)

創建1個DashBoard
New->DashBoard

配置變量(模板,或者叫"維度"比較合適)
創建模板(配置模板變量),比如根據不同的時間段/域名展示.

添加時間間隔維度:
選擇對應的DashBoard>DashBoard Setting>Variables>Edit. 
General如下
Name:   myinterval
Type:   Interval(下拉選擇)
Label:  time interval
Interval Options如下
Values: 1m,10m,30m,1h,6h,12h,1d,7d,14d,30d

添加域名維度:
General
Name:   hostname
Type:   Custom(下拉選擇)
Label:  Domain-Name
Custom Options
Values separated by comma:  *,coinw.ai,www.coinw.ai,api.coinw.ai,byw.ai,www.byw.ai

模板變量的說明(摘抄網上部分)
配置路徑 dashboard-01>Settings>Variables>New
當表格中出現數據后,需要通過篩選條件進行篩選,grafana提供了模板變量用於自定義篩選字段。
Type:定義變量類型
Query:這個變量類型允許您編寫一個數據源查詢,該查詢通常返回一個 metric names, tag values or keys。例如,返回erver names, sensor ids or data centers列表的查詢。
interval:interval值。這個變量可以代表時間跨度。不要按時間或日期直方圖間隔硬編碼一個組,使用這種類型的變量。
Datasource:此類型允許您快速更改整個儀表板的數據源。如果在不同環境中有多個數據源實例,則非常有用。
Custom:使用逗號分隔列表手動定義變量選項。
Constant:定義一個隱藏常數。有用的metric路徑前綴的dashboards,你想分享。在dashboard export,期間,常量變量將作為一個重要的選項。
Ad hoc filters:非常特殊類型的變量,目前只對某些數據源,InfluxDB及Elasticsearch。它允許您添加將自動添加到使用指定數據源的所有metric查詢的key/value 過濾器。

添加與配置Panel
配置PV(頁面訪問量),UV(獨立訪客)
Add Panel,添加panel,分為4步.
Queries(查詢語句)->Visualization(圖標模板)->General(修改標題)->Alert(報警).
Queries配置.
在Metrics配置中,選擇datasource為logservice,輸入Query、Y軸和X軸.

Query:  $hostname| select approx_distinct(remote_addr) as uv ,count(1) as pv , __time__ - __time__ % $$myinterval as time group by time order by time limit  1000

X軸: time
Y軸: uv,pv

之前創建的"維度"會出現在這個Panel的上方(可以根據不同的維度來變化顯示).

panel的Queries配置項解析
Project:項目名稱,因是從阿里雲日志服務獲取,所以固定為ace_ecs_dashboard;
Metric:選擇監控的指標,可以選取cpu、memory、network等監控信息;
Period:監控圖標刷新時間,一般每隔一分鍾刷新一次;
Dimensions:選擇監控實例,即選擇阿里雲中ecs的實例ID;
Group:監控項目組,選了組的類別后,需要在Dimensions 設置顯示模板;
Y-column :顯示Y軸數據類別,有最大、最小、平均三種;

Queries說明

Query的構建,由Grafana進行,解析后的語句,發給對應的數據源,由數據源完成解析.不同數據源,對應的Query也不同.比如Prometheus就是PromQL.
比如阿里雲 log-service,獲取uv,pv如下:

$hostname| select approx_distinct(remote_addr) as uv ,count(1) as pv , __time__ - __time__ % $$myinterval as time group by time order by time limit  1000
其中的$hostname由Grafana進行解析.也可以硬編碼為阿里雲的說明,為"__topic__: waf_access_log"(這個是阿里雲waf導入到阿里雲日志服務的).

主機類指標監控項目

CPU,內存,磁盤空間,IOPS,進出網絡流量,負載情況.
這里采用Prometheus的數據源(請參考Prometheus筆記內容).Prometheus幾乎可以獲取到任何相關數據.
磁盤使用率,數據源為Prometheus,在metric里,需要輸入的PromQL語句為(在Queries里輸入的時候,會有自動提示):

100-node_filesystem_free_bytes{mountpoint="/"}/node_filesystem_size_bytes{mountpoint="/"}*100

參考: https://songjiayang.gitbooks.io/prometheus/content/promql/summary.html PromQL 基本使用
PromQL (Prometheus Query Language) 是 Prometheus 自己開發的數據查詢 DSL 語言,語言表現力非常豐富,內置函數很多,在日常數據可視化以及rule 告警中都會使用到它。

報警(郵件,釘釘)

Grafana的報警不是實時的,因為是先獲取數據源,根據查詢情況,再進行是否報警.時效性可能會差一些.建議采用其他方案的報警.比如雲平台自身的報警服務.

開啟告警
目前只有Graph支持報警功能,所以我們選擇Graph相關圖表。
grafana的告警通知渠道有很多種,像Email、Teams、釘釘等都有支持。

在grafana.ini中開啟告警:

#################################### Alerting ############################
[alerting]
# Disable alerting engine & UI features
enabled = true   #開啟
# Makes it possible to turn off alert rule execution but alerting UI is visible
execute_alerts = true  #開啟
# Default setting for new alert rules. Defaults to categorize error and timeouts as alerting. (alerting, keep_state)
;error_or_timeout = alerting
# Default setting for how Grafana handles nodata or null values in alerting. (alerting, no_data, keep_state, ok)
;nodata_or_nullvalues = no_data
# Alert notifications can include images, but rendering many images at the same time can overload the server
# This limit will protect the server from render overloading and make sure notifications are sent out quickly
;concurrent_render_limit = 5

STMP服務器配置
要能發送郵件通知,首先需要在配置文件grafana.ini中配置郵件服務器等信息:

#################################### SMTP / Emailing ##########################
[smtp]
enabled = true #是否允許開啟
host =  #發送服務器地址,可以再郵箱的配置教程中找到:
user = 你的郵箱
# If the password contains # or ; you have to wrap it with trippel quotes. Ex """#password;"""
password = 這個密碼是你開啟smtp服務生成的密碼
;cert_file =
;key_file =
skip_verify = true
from_address = 你的郵箱
from_name = Grafana
# EHLO identity in SMTP dialog (defaults to instance_name)
;ehlo_identity = dashboard.example.com
[emails]
;welcome_email_on_sign_up = false

釘釘
申請釘釘機器人獲取對應token
釘釘里的機器人管理,新增一個自定義(通過Webhook接入自定義服務)的釘釘機器人.

在Grafana控制台->Alerting->新增.
Name: 釘釘報警
Type: DingDing
URL: 釘釘的token.

到具體的Panel里去指向這個報警.

Redis監控

參考 https://blog.52itstyle.vip/archives/2049/
安裝對應插件.配置(指定對應的IP:PORT,password).
修改Prometheus配置文件.重啟Prometheus.

Mysql監控

參考 https://blog.52itstyle.vip/archives/2059/
安裝mysqld_exporter插件.略.

Ldap對接

參考 https://grafana.com/docs/auth/ldap/
申請多個用戶,分別屬於不同訪問權限組.

Freeipa
Freeipa的LDAP申請用戶與組信息

1.申請用戶 對應DN
grafana-test DN: uid=grafana-test,cn=users,cn=accounts,dc=chanix,dc=top 計划放到admin組
chenxin DN: uid=chenxin,cn=users,cn=accounts,dc=chanix,dc=top
wuweiwei DN: uid=wuweiwei,cn=users,cn=accounts,dc=chanix,dc=top 計划放到editor組
jumpserver DN: uid=jumpserver,cn=users,cn=accounts,dc=chanix,dc=top 不放到admin和edit組,作為other用戶測試

2.創建組 對應DN
grafana DN: cn=grafana,cn=groups,cn=accounts,dc=chanix,dc=top 包含grafana-test,chenxin這2個用戶(擁有grafana的admin權限)
test DN: cn=test,cn=groups,cn=accounts,dc=chanix,dc=top 包含wuweiwei用戶(擁有edit權限,無法修改數據源等)
其他組 (只有view權限)

/etc/grafana/ldap.toml
1.grafana主配文件 /etc/grafana/grafana.ini 修改

#################################### Auth LDAP ##########################
[auth.ldap]
enabled = true  #開啟
config_file = /etc/grafana/ldap.toml    #LDAP配置文件路徑
;allow_sign_up = true   #允許用戶注冊LDAP用戶(關閉)

# LDAP backround sync (Enterprise only)
# At 1 am every day
;sync_cron = "0 0 1 * * *"
;active_sync_enabled = true

2.LDAP配置文件/etc/grafana/ldap.toml 示例

# To troubleshoot and get more log info enable ldap debug logging in grafana.ini
# [log]
# filters = ldap:debug

[[servers]]
# Ldap server host (specify multiple hosts space separated)
#host = "127.0.0.1"
host = "47.91.215.12"   # LDAP地址
# Default port is 389 or 636 if use_ssl = true
port = 389      #LDAP端口
# Set to true if ldap server supports TLS
use_ssl = false
# Set to true if connect ldap server with STARTTLS pattern (create connection in insecure, then upgrade to secure connection with TLS)
start_tls = false
# set to true if you want to skip ssl cert validation
ssl_skip_verify = false
# set to the path to your root CA certificate or leave unset to use system defaults
# root_ca_cert = "/path/to/certificate.crt"
# Authentication against LDAP servers requiring client certificates
# client_cert = "/path/to/client.crt"
# client_key = "/path/to/client.key"

# Search user bind dn
bind_dn = "uid=grafana-test,cn=users,cn=accounts,dc=chanix,dc=top"  #綁定一個DN用於認證
# Search user bind password
# If the password contains # or ; you have to wrap it with triple quotes. Ex """#password;"""
bind_password = 'xxx'    #密碼

# User search filter, for example "(cn=%s)" or "(sAMAccountName=%s)" or "(uid=%s)"
#search_filter = "(cn=%s)"
search_filter = "(uid=%s)"  #使用uid進行匹配用戶

# An array of base dns to search through
#search_base_dns = ["dc=grafana,dc=org"]
search_base_dns = ["cn=users,cn=accounts,dc=chanix,dc=top"] #搜索用戶的路徑,勿注釋,否則無法認證,會報LDAP config file is missing option: search_base_dns"

## For Posix or LDAP setups that does not support member_of attribute you can define the below settings
## Please check grafana LDAP docs for examples
# group_search_filter = "(&(objectClass=posixGroup)(memberUid=%s))"
# group_search_base_dns = ["ou=groups,dc=grafana,dc=org"]
# group_search_base_dns = ["cn=groups,cn=accounts,dc=chanix,dc=top"]  #用戶所屬組的路徑(組要匹配).可以注釋掉.
# group_search_filter_user_attribute = "uid"

# Specify names of the ldap attributes your ldap uses
[servers.attributes]    #這里好像沒什么影響
name = "givenName"
surname = "sn"
#username = "cn"
username = "uid"    #使用UID
member_of = "memberOf"
email =  "email"

# Map ldap groups to grafana org roles.組映射(將ldap的組映射為grafana的).
[[servers.group_mappings]]
group_dn = "cn=grafana,cn=groups,cn=accounts,dc=chanix,dc=top"
org_role = "Admin"  #grafana管理員組
# To make user an instance admin  (Grafana Admin) uncomment line below
# grafana_admin = true
# The Grafana organization database id, optional, if left out the default org (id 1) will be used
# org_id = 1

[[servers.group_mappings]]
group_dn = "cn=test,cn=groups,cn=accounts,dc=chanix,dc=top"
#group_dn = "cn=users,dc=grafana,dc=org"
org_role = "Editor" #可編輯grafana的組(但不能修改數據源等配置)

[[servers.group_mappings]]
# If you want to match all (or no ldap groups) then you can use wildcard
group_dn = "*"
org_role = "Viewer" #可查看的.默認為所有ldap用戶都可以查看

備份與恢復

主要為配置文件,以及數據庫文件
/etc/grafana/
/var/lib/grafana/grafana.db

世界地圖

世界地圖插件目前使用的數據庫為InfluxDB數據庫,是一個時空序列的數據格式,使用時先安裝InfluxDB,然后到Grafana上面對接數據源,InfluxDB安裝及簡單的增刪改查參考如下:
Influxdb安裝 : https://blog.51cto.com/oybw88/2107228
(后面會通過python先對阿里雲日志服務的數據進行清洗,然后寫進InfluxDB,讓Grafana可以實時監控阿里雲服務業務情況)

阿里雲waf

python獲取waf日志腳本:

#! /usr/bin/python3
import time
from aliyun.log import *
import pygeohash
import pymysql
import requests
import json


def getLocation(Longitude,Latitude):


   ak = "nwBNILPav66Baa0OHZNtVUwVcxmNKaBG"
    # url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak={}&output=json&coordtype=wgs84ll&location={},{}".format(ak,Latitude,Longitude)
    url= 'http: //ditu.aliyun.com/regeocoding?l={},{}&type=111'.format(Latitude,Longitude)
requests.get(url='http://api.map.baidu.com/geocoder/v2/', params={'location':'39.934,116.329','ak':'nwBNILPav66Baa0OHZNtVUwVcxmNKaBG','output':'json'})
    r = requests.get(url)
    print (r.json())
    country = r.json()["result"]["addressComponent"]["country"]
    province = r.json()["result"]["addressComponent"]["province"]
    return (country,province)

def main():
    access_key = "LTAIseUbaRxeHLeu"
    serect_key = "ayoI3FUJg891bMRfimV4NVYudOy1th"
    endpoint = "http://ap-southeast-1.log.aliyuncs.com"
    project = "waf-project-1783799610063532-ap-southeast-1"
    logstore = "waf-logstore"

   query1 = "__topic__: waf_access_log | SELECT ip_to_country(if(real_client_ip='-', remote_addr, real_client_ip)) as country, count(1) as accesstimes group by country"
    query2 = "__topic__: waf_access_log | SELECT ip_to_geo(if(real_client_ip='-', remote_addr, real_client_ip)) as country, count(1) as accesstimes group by country"
    query3 = "* | select count(1) as accesstimes, ip_to_country(if(real_client_ip='-', remote_addr, real_client_ip)) as country, ip_to_geo(real_client_ip) as geo group by country,geo"
    topic = ""
    From = int(time.time()) - 3000
    To = int(time.time())

   client = LogClient(endpoint, access_key, serect_key)
    sql = []
    req1 = GetLogsRequest(project, logstore, From, To, topic, query1, 10, 0, False)
    req2 = GetLogsRequest(project, logstore, From, To, topic, query3, 10, 0, False)
    times = 0
    while (True):
        try:
            response2 = client.get_logs(req2).get_body()
            times += 1
            print ("************************")
            print (times)
        except Exception as  e:
            print (e.message)
        if (len(response2)>= 50):
            break
        if (times > 4):
            print ("重試五次獲取日志后失敗")
            break
            
   for i in range(len(response2)):
        # print (response2)
        if (response2[i]['geo']==''):
            response2[i]['geo'] = '22,118'
        location_geolist = response2[i]['geo'].split(",")
        location_geohash = pygeohash.encode(float(location_geolist[0]),float(location_geolist[1]))
        location_country = location_province = response2[i]['country']
        location_accesstimes = response2[i]['accesstimes']
        sql.append("insert into coinw_location values(now(),'{}','{}',{},'{}');".format(
            location_geohash,
            location_province,
            location_accesstimes,
            location_country))
    return sql


def mysqlConnection(sql):
    # 初始化數據庫信息
   host = "localhost"
    user = "root"
    passwd = "coinw_grafana"
    database = "legend_grafana"
    port=10306
    delete_sql = "delete from coinw_location where datediff(curdate(), time)>=3;"
    conn = pymysql.connect(host,user,passwd,database,port)


   cursor = conn.cursor()
    
  // 根據傳進來的sql,依次執行sql語句
   for i in range(len(sql)):
        cursor.execute(sql[i])

   cursor.execute(delete_sql)
    conn.commit()
    cursor.close()
    conn.close()

def mysqltest(sql):
    host = "localhost"
    user = "root"
    passwd = "coinw_grafana"
    database = "legend_grafana"
    port = 10306

   conn = pymysql.connect(host, user, passwd, database, port)
    cursor = conn.cursor()
    print (cursor.execute(sql))
    cursor.close()
    conn.close()

if __name__ == "__main__":
    sql = main()
    print ("----------------")
    mysqlConnection(sql)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM