前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >sqlite 的分布式实现方案:rqlite

sqlite 的分布式实现方案:rqlite

作者头像
谢伟
发布2018-06-06 13:30:04
5.1K1
发布2018-06-06 13:30:04
举报
文章被收录于专栏:GopherCoderGopherCoder

rqlite 相关操作说明

项目总为实现 sqlite 添加账号和密码,以满足信息安全的需求。 鉴于对 sqlite 实现添加账号和密码比较复杂和困难,项目中使用了分布式 rqlite ,故转而研究 rqlite 如何添加账号和密码。

项目概况:

开发语言:Python

存储: sqlite (rqlite)

整体流程:

  • rqlite 介绍
  • rqlite CLI 客户端介绍
  • rqlite Basic Auth
  • pyrqlite 介绍
  • sqlalchemy-rqlite 介绍

1. rqlite 使用介绍

rqlite 项目地址

作者博客

rqlite : 基于 SQLite 构建的轻量级、分布式关系数据库, 使用Go 编程实现,使用 Raft 算法来确保所有 SQLite 数据库实例的一致性。

  • 下载地址和方式

Download

以 Linux版本为例, 解压之后:存在: rqlite 和 rqlited 两个文件

  • 启动服务
./rqlited /pathdir/rqlitedata


# 在 /pathdir/rqlitedata 目录下存放数据文件和其他一些配置文件

peers.json  raft.db  snapshots
  • 启动多个节点
rqlited -http-addr localhost:4003 -raft-addr localhost:4004 -join http://localhost:4001 /pathdir/rqlitedata1
rqlited -http-addr localhost:4005 -raft-addr localhost:4006 -join http://localhost:4001 /pathdir/rqlitedata2

rqlite 支持Securing 操作

  1. File system security
  2. Network security
  3. HTTPS API
  4. Node-to-node encryption
  5. Basic Auth

2. rqlite CLI 命令行使用介绍

启动服务后可以使用命令行工具进行数据的增删改查:

./rqlite
127.0.0.1:4001>

# sqlite 的语法的增删改查都支持
演示示例:
$ ./rqlite
127.0.0.1:4001> CREATE TABLE foo (id INTEGER NOT NULL PRIMARY KEY, name TEXT)
0 row affected (0.000362 sec)
127.0.0.1:4001> .tables
+------+
| name |
+------+
| foo  |
+------+
127.0.0.1:4001> .schema
+---------------------------------------------------------------+
| sql                                                           |
+---------------------------------------------------------------+
| CREATE TABLE foo (id INTEGER NOT NULL PRIMARY KEY, name TEXT) |
+---------------------------------------------------------------+
127.0.0.1:4001> INSERT INTO foo(name) VALUES("fiona")
1 row affected (0.000117 sec)
127.0.0.1:4001> SELECT * FROM foo
+----+-------+
| id | name  |
+----+-------+
| 1  | fiona |
+----+-------+
127.0.0.1:4001> quit
bye~

命令行工具的参数说明

./rqlite -h
 
Options:
 
  -h, --help
      display help information
 
  -s, --scheme[=http]
      protocol scheme (http or https)
 
  -H, --host[=127.0.0.1]
      rqlited host address
 
  -p, --port[=4001]
      rqlited host port
 
  -P, --prefix[=/]
      rqlited HTTP URL prefix
 
  -i, --insecure[=false]
      do not verify rqlited HTTPS certificate

除命令行之外,rqlite 支持 HTTP API

通过 HTTP API 完成对数据库的增删改查。

演示示例:

# 创建数据库
 
curl -X POST 'localhost:4001/db/execute?pretty&timings' -H "Content-Type: application/json" -d '[
    "CREATE TABLE foo (id integer not null primary key, name text)"
]'
 
# 返回是个 json 格式的数据
{
    "results": [
        {
            "last_insert_id": 1,
            "rows_affected": 1,
            "time": 0.00886
        }
    ],
    "time": 0.0152
}
 
# 查询数据
 
curl -G 'localhost:4001/db/query?pretty&timings' --data-urlencode 'q=SELECT * FROM foo'
 
# 返回结果
 
{
    "results": [
        {
            "columns": [
                "id",
                "name"
            ],
            "types": [
                "integer",
                "text"
            ],
            "values": [
                [
                    1,
                    "fiona"
                ]
            ],
            "time": 0.0150043
        }
    ],
    "time": 0.0220043
}
 
# 也有很好的错误处理机制,比如查询一个不存在的数据库,或者语法错误,都能很好的捕获
 
curl -XPOST 'localhost:4001/db/execute?pretty&timings' -H "Content-Type: application/json" -d "[
    \"INSERT INTO nonsense\"
]"
 
{
    "results": [
        {
            "error": "near \"nonsense\": syntax error"
        }
    ],
    "time": 2.478862
}
 
# 还可显示响应信息
 
curl -v -G 'localhost:4003/db/query?pretty&timings' --data-urlencode 'q=SELECT * FROM foo'
 
# 响应信息
* About to connect() to localhost port 4001 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 4001 (#0)
* Server auth using Basic with user 'bob'
> GET /db/query?pretty&timings&q=SELECT%20%2A%20FROM%20foo HTTP/1.1
> Authorization: Basic Ym9iOnNlY3JldDE=
> User-Agent: curl/7.29.0
> Host: localhost:4001
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< X-Rqlite-Version: v4.0.0
< Date: Tue, 14 Nov 2017 08:07:27 GMT
< Content-Length: 276
<
{
    "results": [
        {
            "columns": [
                "id",
                "name"
            ],
            "types": [
                "integer",
                "text"
            ],
            "time": 0.000116084
        }
    ],
    "time": 0.000741562
* Connection #0 to host localhost left intact

3. rqlite Basic Auth

其他安全策略暂时不研究,研究认证方式。

具体做法是:

  • 配置文件: config.json 规定相应用户的操作权限
  • 启动服务传入配置文件
  • 命令行操作 -H 传入参数
  • HTTP API 则也需要传入用户名和密码

演示:config.json

1. 用户名、密码和操作权限设置

[
  {
    "username": "bob",
    "password": "secret1",
    "perms": ["all"]
  },
  {
    "username": "mary",
    "password": "secret2",
    "perms": ["query", "status"]
  }
]


# 配置了两个用户名和密码,两个用户的操作权限不一致,mary 用户只要query , status 权限

注: 用户权限包括:

  • all: user can perform all operations on a node.
  • execute: user may access the execute endpoint.
  • query: user may access the query endpoint.
  • load: user may load an SQLite dump file into a node.
  • backup: user may perform backups.
  • status: user can retrieve status information from the node.
  • join: user can join a cluster. In practice only a node joins a cluster.
  • remove: user can remove a node from a cluster.

2. 传入认证参数启动节点服务

./rqlited -auth=/root/config.json -http-addr localhost:4001 -raft-addr localhost:4002 /root/data/rqlite

3. 若使用命令界面访问认证的数据库

bob,secret1 为配置文件中的用户名和密码

./rqlite -H bob:secret1@localhost
bob:secret1@localhost:4001>
 
# 正常使用 SQL 实现增删改查,不添加-H 参数,报错,无法读取数据库数据

4. 若使用HTTP API 的方式访问认证的数据库

访问 API 有所差异

curl -G 'https://bob:secret1@localhost:4001/db/query?pretty&timings' \
--data-urlencode 'q=SELECT * FROM foo'
 
# API 中带入了用户名和密码

4. pyrqlite 使用介绍

假设启动了节点服务,那如何实现编程实现对数据库的增删改查?

pyrqlite 和绝大多数数据库API 的使用方法一致:

安装

  • 下载源码
  • python setup.py install

基本使用

import pyrqlite.dbapi2 as dbapi2
 
# Connect to the database
connection = dbapi2.connect(
    host='localhost',
    port=4001,
)
 
try:
    with connection.cursor() as cursor:
        cursor.execute('CREATE TABLE foo (id integer not null primary key, name text)')
        cursor.executemany('INSERT INTO foo(name) VALUES(?)', seq_of_parameters=(('a',), ('b',)))
 
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `name` FROM `foo` WHERE `name`=?"
        cursor.execute(sql, ('a',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()
 
# 结果
OrderedDict([('id', 1), ('name', 'a')])

若启动了一个配置认证信息的节点如何操作pyrqlite

最新版本,已经实现创建数据库连接时配置 user 和 paasword

connection = dbapi2.connect(
    host='localhost',
    port=4001,
    user='bob',
    password='secret1'
)

5. sqlalchemy-rqlite 使用介绍

如果对直接编写SQL 语句容易出错,作者还提供了ORM 方式。

安装

  • 下载源码
  • python setup.py install

基本使用

from sqlalchemy import create_engine
engine = create_engine('rqlite+pyrqlite://localhost:4001/', echo=True)

如果对已经配置认证信息的节点进行连接

from sqlalchemy import create_engine
engine = create_engine('rqlite+pyrqlite://localhost:4001/?user=bob&password=secret1', echo=True)

(全文完)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.11.14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. rqlite 使用介绍
  • 2. rqlite CLI 命令行使用介绍
  • 3. rqlite Basic Auth
  • 4. pyrqlite 使用介绍
  • 5. sqlalchemy-rqlite 使用介绍
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档