This topic describes how to create an external store to associate Simple Log Service (SLS) with a MySQL database.
Prerequisites
-
You have collected data in Simple Log Service. For more information, see Data collection.
-
You have installed the Log Service CLI and configured an endpoint and AccessKey pair.
-
You have stored data in an ApsaraDB RDS for MySQL database, an AnalyticDB for MySQL database, or a self-managed MySQL database on an Alibaba Cloud Elastic Compute Service (ECS) instance.
-
The MySQL database is in an Alibaba Cloud Virtual Private Cloud (VPC). The ApsaraDB RDS for MySQL instance, AnalyticDB for MySQL instance, or ECS instance must be in the same region as the SLS project.
ImportantYou cannot directly connect to a MySQL database by using a public IP address.
Background information
The external store feature of Simple Log Service (SLS) lets you associate SLS with an ApsaraDB RDS for MySQL database, an AnalyticDB for MySQL database, or a self-managed MySQL database on an ECS instance. You can also write query and analysis results to the MySQL database for further processing.
Procedure
1. Configure a whitelist
ApsaraDB RDS for MySQL
Add the CIDR blocks 100.104.0.0/16, 11.194.0.0/16, and 11.201.0.0/16 to the whitelist. For more information, see Configure an IP address whitelist.
Self-managed MySQL on ECS
Add security group rules to allow access from the 100.104.0.0/16, 11.194.0.0/16, and 11.201.0.0/16 CIDR blocks. For more information, see Add a security group rule.
AnalyticDB for MySQL
Add the CIDR blocks 100.104.0.0/16, 11.194.0.0/16, and 11.201.0.0/16 to the whitelist. For more information, see Configure a whitelist.
2. Create an external store
-
Log on to the server where the CLI is installed. On the command line, run the
touchcommand to create the configuration file /home/shell/config.json. Add the following script to the config.json file. You must replace the values forregion,vpc-id,host,port,username,password,db, andtablewith your actual values.-
Parameters
Example
{ "externalStoreName":"sls_join_meta_store", "storeType":"rds-vpc", "parameter":{ "region":"cn-qingdao", "vpc-id":"vpc-m5eq4irc1pucp*******", "host":"rm-bp1******rm76.mysql.rds.aliyuncs.com", "port":"3306", "username":"user", "password":"****", "db":"scmc", "table":"join_meta" } }externalStoreNameThe name of the external store. The name must be in lowercase.
storeTypeThe type of the data source. Set this parameter to
rds-vpc.regionThe region where the database is located.
-
If you use an ApsaraDB RDS for MySQL database, set region to the region of the RDS instance.
-
If you use an AnalyticDB for MySQL database, set region to the region of the AnalyticDB for MySQL instance.
-
If you use a self-managed MySQL database on an ECS instance in a VPC, set region to the region of the ECS instance.
ImportantThe ApsaraDB RDS for MySQL instance, AnalyticDB for MySQL instance, or ECS instance must be in the same region as the SLS project.
vpc-idThe VPC ID.
-
If you use an ApsaraDB RDS for MySQL instance in a VPC, set vpc-id to the ID of the VPC where the instance is located.
-
If you use an AnalyticDB for MySQL instance in a VPC, set vpc-id to the ID of the VPC where the instance is located.
-
If you use a self-managed MySQL database on an ECS instance in a VPC, set vpc-id to the ID of the VPC where the instance is located.
hostIf you use an internal endpoint for a database in a VPC, SLS resolves it to a private IP address and caches it when the external store is created. If this IP address later changes (for example, due to instance migration), access to the external store is disrupted because the cached IP is not automatically refreshed. To resolve this, you must update or re-create the external store.
-
If you use an ApsaraDB RDS for MySQL database in a VPC, set host to the internal address of the RDS instance. The address can be an internal endpoint or a private IP address.
-
If you use an AnalyticDB for MySQL database in a VPC, set host to the internal address of the AnalyticDB for MySQL instance. The address can be an internal endpoint or a private IP address.
-
If you use a self-managed MySQL database on an ECS instance in a VPC, set host to the private IP address of the ECS instance.
portThe port number.
-
If you use an ApsaraDB RDS for MySQL database, set port to the port number of the RDS instance.
-
If you use an AnalyticDB for MySQL database, set port to the port number of the AnalyticDB for MySQL instance.
-
If you use a self-managed MySQL database on an ECS instance, set port to the service port of MySQL on the ECS instance.
usernameThe username for the database account.
passwordThe password for the database account.
dbThe name of the database.
tableThe name of the database table. The following formats are supported:
-
table_name, such as test.
-
schema_name.table_name, such as public.test.
-
-
-
Run the following command to create the external store. Replace project_name with the name of your project. This example uses
log-rds-demo.aliyunlog log create_external_store --project_name="log-rds-demo" --config="file:///home/shell/config.json" -
The create_external_store command returns no output on success. To verify the creation, run the
aliyunlog log get_external_store --project_name="log-rds-demo" --store_name="sls_join_meta_store" --format-output=jsoncommand to view the details of the external store. The following response is an example:{ "externalStoreName":"sls_join_meta_store", "storeType":"rds-vpc", "parameter":{ "db": "scmc", "host": "rm-bp1******rm76.mysql.rds.aliyuncs.com", "port": "3306", "region": "cn-qingdao", "table": "join_meta", "username": "user", "vpc-id": "vpc-m5eq4irc1pucp*******" } }
3. Use the external store
Run query and analysis
-
Use the external store
After associating the external data source, go to the SLS console. In the project named
log-rds-demo, click any logstore. Then, run the query and analysis statement* | select * from sls_join_meta_storeto query data from the associated MySQL table.On the Charts tab, the query result is a table with columns for
idandname. Two example records are (123, 'Bob') and (124, 'Lucy'). -
Use JOIN to associate a logstore with a MySQL table
-
The MySQL table in a JOIN operation must be smaller than 20 MB.
-
In a query and analysis statement, LogStore must be specified before the join keyword, and ExternalStore must be specified after the join keyword.
-
Use the external store name in the query. SLS automatically maps this name to the configured database and table. Do not use the MySQL table name directly.
Supported JOIN clauses include INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.
[ INNER ] JOIN LEFT [ OUTER ] JOIN RIGHT [ OUTER ] JOIN FULL [ OUTER ] JOIN* | select count(1) from log l join sls_join_meta_store m on l.projectid = cast( m.ikey as varchar) -
Save query results to MySQL
If a field in the target MySQL table is of thevarchartype, you must cast the corresponding field from the logstore to a compatible varchar type. For example, if thedetailfield in the MySQL table isvarchar(60), use thecastfunction on thecontentfield from the logstore:cast(content as varchar(60)). For more information about the cast function, see type conversion function.
You can use the INSERT syntax to save query results to a MySQL database:
* | insert into sls_join_meta_store select cast(method as varchar(65535)),count(1) from log group by method
SDK operations
Python sample code
# encoding: utf-8
from __future__ import print_function
from aliyun.log import *
from aliyun.log.util import base64_encodestring
from random import randint
import time
import os
from datetime import datetime
endpoint = os.environ.get('ALIYUN_LOG_SAMPLE_ENDPOINT', 'cn-chengdu.log.aliyuncs.com')
accessKeyId = os.environ.get('ALIYUN_LOG_SAMPLE_ACCESSID', '')
accessKey = os.environ.get('ALIYUN_LOG_SAMPLE_ACCESSKEY', '')
logstore = os.environ.get('ALIYUN_LOG_SAMPLE_LOGSTORE', '')
project = "ali-yunlei-chengdu"
client = LogClient(endpoint, accessKeyId, accessKey, '')
# Create an external store.
res = client.create_external_store(project,
ExternalStoreConfig(externalStoreName="rds_store", region="cn-chengdu",
storeType="rds-vpc",
vpcId="vpc-2vctx8reuqswmk********",
host='rm-2vc6x67972iv********.mysql.cn-chengdu.rds.aliyuncs.com',
port="3306", username="root", password="123456",
database="test_database", table="test"))
res.log_print()
# Get the details of the external store.
res = client.get_external_store(project,"rds_store")
res.log_print()
res = client.list_external_store(project,"")
res.log_print()
# Run a JOIN query.
req = GetLogsRequest(project,logstore,From,To,"","* | select count(1) from "+ logstore +" s join meta m on s.projectid = cast(m.ikey as varchar)")
res = client.get_logs(req)
res.log_print()
# Write the query and analysis results to the MySQL database.
req = GetLogsRequest(project,logstore,From,To,"","* | insert into rds_store select count(1) from "+ logstore )
res = client.get_logs(req)
res.log_print()
Related operations
-
Update a MySQL external store.
aliyunlog log update_external_store --project_name="log-rds-demo" --config="file:///home/shell/config.json" -
Delete a MySQL external store.
aliyunlog log delete_external_store --project_name="log-rds-demo" --store_name=sls_join_meta_store
References
-
For information about the best practices for creating a MySQL external store, see Associate a logstore with a MySQL database for query analysis.
-
To learn how to create a self-managed MySQL database on an Alibaba Cloud ECS instance, see Manually deploy a MySQL database (Linux).
-
To quickly create an AnalyticDB for MySQL database, see Quick start for Elastic mode clusters.
-
To quickly create an ApsaraDB RDS for MySQL database, see Quickly create an ApsaraDB RDS for MySQL instance.