1. 程式人生 > 資料庫 >mysql-centos7安裝mysql自動化運維平臺

mysql-centos7安裝mysql自動化運維平臺

mysql-centos7安裝mysql自動化運維平臺
https://blog.csdn.net/xujiamin0022016/article/details/81980393
碼雲地址(forked from 爛泥行天下/archer)
https://gitee.com/jiaminxu/archer
docker 地址分別如下 
https://dev.aliyun.com/detail.html?spm=5176.1972343.2.12.7b475aaaLiCfMf&repoId=142093
https://dev.aliyun.com/detail.html?spm=5176.1972343.2.38.XtXtLh&repoId=142147
1 安裝docker
#yum install報錯:Another app is currently holding the yum lock; waiting for it to exit...
#解決:yum被鎖定了,rm -rf /var/run/yum.pid 強制殺死程序來解決

yum install -y yum-utils device-mapper-persistent-data lvm2
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum makecache fast
yum -y install docker-ce
service docker start
#設定docker開機自啟動
systemctl enable docker

2 pull 所需映象
docker pull registry.cn-hangzhou.aliyuncs.com/lihuanhuan/archer
docker pull registry.cn-hangzhou.aliyuncs.com/lihuanhuan/inception
#下載完之後檢視映象
docker images
 
3 建立配置檔案/etc/inc.cnf
#10.6.11.199替換為192.168.92.111
cat >>/etc/inc.cnf<<EOF
[inception]
general_log=1
general_log_file=inception.log
port=6669
socket=/tmp/inc.socket
character-set-client-handshake=0
character-set-server=utf8
#備份庫資訊
inception_remote_system_password=Hangzhou@123
inception_remote_system_user=root
inception_remote_backup_port=3306
inception_remote_backup_host=192.168.92.111
inception_support_charset=utf8,utf8mb4
inception_enable_nullable=0
inception_check_primary_key=1
inception_check_column_comment=1
inception_check_table_comment=1
inception_osc_on=OFF
inception_osc_bin_dir=/usr/bin
inception_osc_min_table_size=1
inception_osc_chunk_time=0.1
inception_enable_blob_type=1
inception_check_column_default_value=1
EOF
 
#指定配置檔案和埠啟動
docker run --name inception -v /etc/inc.cnf:/etc/inc.cnf  -p 6669:6669 -dti registry.cn-hangzhou.aliyuncs.com/lihuanhuan/inception
#啟動inspection 
docker start inception

4 安裝mysql5.7(個人喜好)
因為自己有寫指令碼 所以安裝了mysql5.7.12
安裝完畢之後  建立django初始化的/etc/settings.py
紅色標註為需要根據自身伺服器修改的地方   如果出現報錯 注意配置中間是否有多餘空行
vi /etc/settings.py

# -*- coding: UTF-8 -*- 
"""
Django settings for archer project.
Generated by 'django-admin startproject' using Django 1.8.17.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import pymysql
pymysql.install_as_MySQLdb()
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'hfusaf2m4ot#7)fkw#di2bu6(cv0@opwmafx5n#6=3d%x^hpl6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# 解決nginx部署跳轉404
USE_X_FORWARDED_HOST = True
# Application definition
INSTALLED_APPS = (
    'django_admin_bootstrapped',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_apscheduler',
    'sql',
)
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'sql.check_login_middleware.CheckLoginMiddleware',
    'sql.exception_logging_middleware.ExceptionLoggingMiddleware',
)
ROOT_URLCONF = 'archer.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'sql/static')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'sql.processor.global_info',
            ],
        },
    },
]
WSGI_APPLICATION = 'archer.wsgi.application'
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = False
# 時間格式化
USE_L10N = False
DATETIME_FORMAT = 'Y-m-d H:i:s'
DATE_FORMAT = 'Y-m-d'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# 擴充套件django admin裡users欄位用到,指定了sql/models.py裡的class users
AUTH_USER_MODEL = "sql.users"
###############以下部分需要使用者根據自己環境自行修改###################
# session 設定
SESSION_COOKIE_AGE = 60 * 30  # 30分鐘
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True  # 關閉瀏覽器,則COOKIE失效
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
# 該專案本身的mysql資料庫地址
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'archer_github',
        'USER': 'root',
        'PASSWORD': 'Hangzhou@123',
        'HOST': '192.168.92.111',
        'PORT': '3306'
    }
}
# inception元件所在的地址
INCEPTION_HOST = '192.168.92.111'
INCEPTION_PORT = '6669'
# 查看回滾SQL時候會用到,這裡要告訴archer去哪個mysql裡讀取inception備份的回滾資訊和SQL.
# 注意這裡要和inception元件的inception.conf裡的inception_remote_XX部分保持一致.
INCEPTION_REMOTE_BACKUP_HOST = '192.168.92.111'
INCEPTION_REMOTE_BACKUP_PORT = 3306
INCEPTION_REMOTE_BACKUP_USER = 'inception'
INCEPTION_REMOTE_BACKUP_PASSWORD = 'inception'
# 賬戶登入失敗鎖定時間(秒)
LOCK_TIME_THRESHOLD = 300
# 賬戶登入失敗 幾次 鎖賬戶
LOCK_CNT_THRESHOLD = 5
# LDAP
ENABLE_LDAP = False
if ENABLE_LDAP:
    import ldap
    # from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
    from django_auth_ldap.config import LDAPSearch, GroupOfUniqueNamesType
    AUTHENTICATION_BACKENDS = (
        'django_auth_ldap.backend.LDAPBackend',  # 配置為先使用LDAP認證,如通過認證則不再使用後面的認證方式
        'django.contrib.auth.backends.ModelBackend',  # sso系統中手動建立的使用者也可使用,優先順序靠後。注意這2行的順序
    )
    # if use self signed certificate, Remove AUTH_LDAP_GLOBAL_OPTIONS annotations
    # AUTH_LDAP_GLOBAL_OPTIONS={
    #    ldap.OPT_X_TLS_REQUIRE_CERT: ldap.OPT_X_TLS_NEVER
    # }
    AUTH_LDAP_BIND_DN = "cn=xx,dc=xx,dc=xx"
    AUTH_LDAP_BIND_PASSWORD = "xx"
    AUTH_LDAP_SERVER_URI = "ldap://ldap.xx.com"
    AUTH_LDAP_BASEDN = "dc=xx,dc=xx"
    AUTH_LDAP_USER_DN_TEMPLATE = "cn=%(user)s,ou=xx,dc=xx,dc=xx"
    AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=xx,dc=xx,dc=xx",
                                        ldap.SCOPE_SUBTREE, "(objectClass=groupOfUniqueNames)"
                                        )
    AUTH_LDAP_GROUP_TYPE = GroupOfUniqueNamesType()
    AUTH_LDAP_ALWAYS_UPDATE_USER = True  # 每次登入從ldap同步使用者資訊
    AUTH_LDAP_USER_ATTR_MAP = {  # key為archer.sql_users欄位名,value為ldap中欄位名,用於同步使用者資訊
        "username": "xx",
        "display": "xx",
        "email": "xx"
    }
    # AUTH_LDAP_MIRROR_GROUPS = True  # 直接把ldap的組複製到django一份,和AUTH_LDAP_FIND_GROUP_PERMS互斥.使用者每次登入會根據ldap來更新資料庫的組關係
    # AUTH_LDAP_FIND_GROUP_PERMS = True  # django從ldap的組許可權中獲取許可權,這種方式,django自身不建立組,每次請求都呼叫ldap
    # AUTH_LDAP_CACHE_GROUPS = True  # 如開啟FIND_GROUP_PERMS後,此配置生效,對組關係進行快取,不用每次請求都呼叫ldap
    # AUTH_LDAP_GROUP_CACHE_TIMEOUT = 600  # 快取時間
# 開啟以下配置註釋,可以幫助除錯ldap整合
LDAP_LOGS = '/tmp/ldap.log'
DEFAULT_LOGS = '/tmp/default.log'
stamdard_format = '[%(asctime)s][%(threadName)s:%(thread)d]' + \
                  '[task_id:%(name)s][%(filename)s:%(lineno)d] ' + \
                  '[%(levelname)s]- %(message)s'
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {  # 詳細
            'format': stamdard_format
        },
    },
    'handlers': {
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': DEFAULT_LOGS,
            'maxBytes': 1024 * 1024 * 100,  # 5 MB
            'backupCount': 5,
            'formatter': 'standard',
        },
        'ldap': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': LDAP_LOGS,
            'maxBytes': 1024 * 1024 * 100,  # 5 MB
            'backupCount': 5,
            'formatter': 'standard',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'default': {  # default日誌,存放於log中
            'handlers': ['default'],
            'level': 'DEBUG',
        },
        # 'django.db': {  # 列印SQL語句到console,方便開發
        #     'handlers': ['console'],
        #     'level': 'DEBUG',
        #     'propagate': False,
        # },
        'django.request': {  # 列印錯誤堆疊資訊到console,方便開發
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': False,
        },
        'django_auth_ldap': {  # django_auth_ldap模組相關日誌列印到console
            'handlers': ['ldap'],
            'level': 'DEBUG',
            'propagate': True,  # 選擇關閉繼承,不然這個logger繼承自預設,日誌就會被記錄2次了(''一次,自己一次)
        }
    }
}
# 是否開啟郵件提醒功能:發起SQL上線後會傳送郵件提醒稽核人稽核,執行完畢會發送給DBA. on是開,off是關,配置為其他值均會被archer認為不開啟郵件功能
MAIL_ON_OFF = 'off'
MAIL_SSL = False # 是否使用SSL
MAIL_REVIEW_SMTP_SERVER = 'mail.xxx.com'
MAIL_REVIEW_SMTP_PORT = 25
MAIL_REVIEW_FROM_ADDR = '[email protected]'  # 發件人,也是登入SMTP server需要提供的使用者名稱
MAIL_REVIEW_FROM_PASSWORD = ''  # 發件人郵箱密碼,如果為空則不需要login SMTP server
# 是否過濾【DROP DATABASE】|【DROP TABLE】|【TRUNCATE PARTITION】|【TRUNCATE TABLE】等高危DDL操作:
# on是開,會首先用正則表示式匹配sqlContent,如果匹配到高危DDL操作,則判斷為“自動稽核不通過”;off是關,直接將所有的SQL語句提交給inception,對於上述高危DDL操作,只備份元資料
CRITICAL_DDL_ON_OFF = 'off'
# 是否開啟SQL查詢功能,關閉會隱藏選單和相關功能
QUERY = True
# 當inception語法樹列印失敗時線上查詢的結果控制,建議修改inception變數inception_enable_select_star=OFF,否則select * 會報錯
# True是開啟校驗,失敗不允許繼續執行並返回錯,
# False是關閉校驗,繼續執行,關閉校驗會導致解析失敗的查詢表許可權驗證和脫敏功能失效
CHECK_QUERY_ON_OFF = True
# 是否開啟動態脫敏查詢,採取正則遍歷處理結果集的方式,會影響部分查詢效率
DATA_MASKING_ON_OFF = True
# 管理員線上查詢的結果集限制
ADMIN_QUERY_LIMIT = 5000
# 是否開啟慢日誌管理,關閉會隱藏選單和相關功能
SLOWQUERY = False
# sqladvisor的路徑配置,如'/opt/SQLAdvisor/sqladvisor/sqladvisor',''代表關閉,隱藏選單和相關功能
SQLADVISOR = '/opt/SQLAdvisor/sqladvisor/sqladvisor'
# 是否開啟AliYunRDS管理
ALIYUN_RDS_MANAGE = False
 
5 建立一個archer_github的資料庫
#我用的編碼格式utf8mb4_bin
create database archer_github character set utf8mb4 collate utf8mb4_bin;

#在mysql中執行如下sql   否則回滾sql時 會提示inception賬號的一系列問題哦
grant all privileges on *.* to 'inception'@'%' identified by 'inception' with grant option;
flush privileges; 
 
建立完資料庫之後  執行容器
#docker rm 67fbcb242d09 刪除已存在容器 按CONTAINER ID
docker run --name archer -v /etc/settings.py:/opt/archer/archer/settings.py  -e NGINX_PORT=9123 -p 9123:9123 -dti registry.cn-hangzhou.aliyuncs.com/lihuanhuan/archer:latest

#報錯:
docker: Error response from daemon: driver failed programming external connectivity on endpoint archer (67a3a5c01bb71ecbd0a951687d80f0993248bfcc5396634f0096795f344b1576):  (iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport 9123 -j DNAT --to-destination 172.17.0.4:9123 ! -i docker0: iptables: No chain/target/match by that name.
 (exit status 1)).
解決:
systemctl stop firewalld
systemctl restart docker
docker rm archer
docker run --name archer -v......
 
6 進入容器  執行初始化命令
docker exec -ti archer /bin/bash
cd /opt/archer
source /opt/venv4archer/bin/activate
修改 archer/settings.py    修改其中 資料庫的地址及賬號密碼  否則makemigrations會報錯
不知道為什麼掛載進來的settings.py沒有替換原來資料夾中的settings.py  2個檔案同時存在



python3 manage.py makemigrations sql

#輸出如下:
Migrations for 'sql':
  0001_initial.py:
    - Create model SlowQuery
    - Create model SlowQueryHistory
    - Create model users
    - Create model AliyunAccessKey
    - Create model AliyunRdsConfig
    - Create model DataMaskingColumns
    - Create model DataMaskingRules
    - Create model master_config
    - Create model QueryLog
    - Create model QueryPrivileges
    - Create model QueryPrivilegesApply
    - Create model slave_config
    - Create model workflow
    - Create model WorkflowAudit
    - Create model WorkflowAuditDetail
    - Create model WorkflowAuditSetting
    - Alter unique_together for workflowaudit (1 constraint(s))
    - Add field cluster_name to aliyunrdsconfi

python3 manage.py migrate

#輸出如下:
Operations to perform:
  Synchronize unmigrated apps: messages, django_admin_bootstrapped, staticfiles
  Apply all migrations: auth, sql, contenttypes, sessions, admin, django_apscheduler
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sql.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying django_apscheduler.0001_initial... OK
  Applying django_apscheduler.0002_auto_20180412_0758... OK
  Applying sessions.0001_initial... OK

# 建立管理員賬號:django使用者,用來建立新使用者和新增資料庫
#輸入Username: django,密碼相同,郵箱為qq
python3 manage.py createsuperuser

#建立完畢 檢視容器狀態
#推出初始化環境venv4archer
exit
docker ps -a

7 關閉防火牆或新增防火牆規則訪問
http://10.6.11.199:9123
http://192.168.92.111:9123/allworkflow/

申請釋出sql工單流程
普通使用者登入http://10.6.11.199:9123
create database test character set utf8mb4 collate utf8mb4_bin;
alter table test.test add PRIMARY key(id);
create table test.test(id int,name varchar(200));
insert into test.test select 1,'n1';
insert into test.test select 2,'n2';
select * from test.test where id=2;
update test.test set name='nn22' where id=2;


輸入你要執行的sql


 
審批人賬號收到郵件

 
用審批人賬號登入

稽核通過


DBA賬號收到郵件

用DBA賬號登入
執行

 
回滾同理
 


 
 
 
如果需要加入阿里雲RDS修改配置檔案settings.py

也可以加上郵件通知

重啟archer 的docker服務 就可以了

測試回滾功能

稽核並執行

執行成功

檢視資料庫中備份

提交回滾請求   需要檢測之後提交



切換dba賬號執行回滾

回滾成功

郵件也收到了 只不過我為了測試  郵件通知人 都是自己

需要修改的話直接在    後臺資料管理 中修改
 

如果資料庫名太長的話 會報錯
Global environment  error
 
The backup dbname 'rm-bp1570xxxfo.mysql.rds.aliyuncs.com-3306- lse_home_prod ' is too long.
 

原因是RDS庫名+埠+資料庫名太長了  超過了mysql 的information_schema中欄位的值64
所以庫名不要超過11位元組 就不會報上述錯誤了(sql錯誤請忽略 我就是拿來演示的)
 

 
 
要不就ping一下阿里雲的RDS地址  把RDS地址換成ip即可
在工單介面 也是看不到具體ip的

 

 
 
再安裝一個80埠的nginx  解析到docker的9123的nginx 埠
只需要新增下面一條設定即可


把9123 80 3306 6669埠加入防火牆  並reload
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=9123/tcp --permanent
firewall-cmd --zone=public --add-port=3306/tcp --permanent
firewall-cmd --zone=public --add-port=6669/tcp --permanent
firewall-cmd --reload
 
如果你的sql 比較大,可能會報錯

 
 
修改archer 容器裡nginx配置中client_max_body_size 
設定大一點就可以了

加入ldap    由於之前搭建的伺服器是沒有介入內網ldap的  配置ldap的時候就一模一樣再裝了一遍
ldap配置可參考https://www.cnblogs.com/chenminklutz/p/9642277.html     
不過我的ou帶有空格 cn帶有空格所以自己重新配置了用“”把欄位括起來了
紅色框框處需要自行根據ou進行修改

 
可以先安裝ldapsearch  測試
yum install -y openldap-servers openldap-clients migrationtools
 
ldapsearch -x -W -h  172.16.5.1 -p 389 -b "dc=tiansoft,dc=com" -D "cn=Jiamin Xu(Hugo),ou=FTE,ou=Domain Users,dc=tiansoft,dc=com"

至此mysql自動化運維平臺已經搭建完畢  配置方面請根據個人需求配置。