from msilib.schema import AppId
from aliyun.log import LogClient, PutLogsRequest, LogItem, GetLogsRequest, IndexConfig
import time

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

# 配置AccessKey、服务入口、Project名称、Logstore名称等相关信息。
# 阿里云访问密钥AccessKey。更多信息，请参见访问密钥。
# 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维。
accessKeyId = "LTAI5tJAH6JrTM6BLx2t6nRF"  
accessKey = "sIdNS5eXJIIw0Rlx7EIYxVH4xa8iaz" 
# 日志服务的域名。更多信息，请参见服务入口。此处以杭州为例，其它地域请根据实际情况填写。
endpoint = "cn-hangzhou.log.aliyuncs.com" 

# 创建日志服务Client。 
client = LogClient(endpoint, accessKeyId, accessKey)

# Project名称。
project_name = "aliyun-test-project-fishyer"
#Logstore名称
logstore_name = "aliyun-test-logstore-fishyer"
# 查询语句。
query = "*| select dev,id from " + logstore_name
# 索引。
logstore_index = {'line': {
    'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n', '\t',
              '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'dev': {'type': 'text',
                                                                             'token': [',', ' ', "'", '"', ';', '=',
                                                                                       '(', ')', '[', ']', '{', '}',
                                                                                       '?', '@', '&', '<', '>', '/',
                                                                                       ':', '\n', '\t', '\r'],
                                                                             'caseSensitive': False, 'alias': '',
                                                                             'doc_value': True, 'chn': False},
                                                                     'id': {'type': 'long', 'alias': '',
                                                                            'doc_value': True}}, 'log_reduce': False,
    'max_text_len': 2048}

# from_time和to_time表示查询日志的时间范围，Unix时间戳格式。
from_time = int(time.time()) - 3600
to_time = time.time() + 3600

# 创建Project。
def create_project():
    print("ready to create project %s" % project_name)
    client.create_project(project_name, project_des="")
    print("create project %s success " % project_name)
    time.sleep(60)

# 创建Logstore。
def create_logstore():
    print("ready to create logstore %s" % logstore_name)
    client.create_logstore(project_name, logstore_name, ttl=3, shard_count=2)
    print("create logstore %s success " % project_name)
    time.sleep(30)

# 创建索引。
def create_index():
    print("ready to create index for %s" % logstore_name)
    index_config = IndexConfig()
    index_config.from_json(logstore_index)
    client.create_index(project_name, logstore_name, index_config)
    print("create index for %s success " % logstore_name)
    time.sleep(60 * 2)

# 向Logstore写入数据。
def put_logs():
    print("ready to put logs for %s" % logstore_name)
    log_group = []
    for i in range(0, 100):
        log_item = LogItem()
        contents = [
            ('dev', 'test_put'),
            ('id', str(i))
        ]
        log_item.set_contents(contents)
        log_group.append(log_item)
    request = PutLogsRequest(project_name, logstore_name, "", "", log_group, compress=False)
    client.put_logs(request)
    print("put logs for %s success " % logstore_name)
    time.sleep(60)


# 通过SQL查询日志。
def get_logs():
    print("ready to query logs from logstore %s" % logstore_name)
    request = GetLogsRequest(project_name, logstore_name, from_time, to_time, query=query)
    response = client.get_logs(request)
    for log in response.get_logs():
        for k, v in log.contents.items():
            print("%s : %s" % (k, v))
        print("*********************")

def get_token():
    # 创建AcsClient实例
    client = AcsClient(
    accessKeyId,
    accessKey,
    "cn-shanghai"
    )
    # 创建request，并设置参数。
    request = CommonRequest()
    request.set_method('POST')
    request.set_domain('nls-meta.cn-shanghai.aliyuncs.com')
    request.set_version('2019-02-28')
    request.set_action_name('CreateToken')
    response = client.do_action_with_exception(request)
    print(response)

if __name__ == '__main__':
    get_token()
    # # 创建Project。
    # create_project()
    # # 创建Logstore。
    # create_logstore()
    # # 创建索引。
    # create_index()
    # # 向Logstore写入数据。
    # put_logs()
    # # 通过SQL查询日志。
    # get_logs()