【VMware vCenter】连接和使用vCenter Server嵌入式vPostgres数据库。
vCenter Server 早期支持内嵌(embedded)和外部(external)数据库,内嵌数据库就是vPostgres,基于VMware Postgres数据库(PostgreSQL数据库),外部数据库用的多的是Oracle数据库和SQL Server数据库。因为早期使用内嵌的PostgreSQL数据库只能用于小型环境,比如仅支持几十台主机以及几百个虚拟机,所以一般大型的环境都使用外部数据库进行部署,这跟早期基于Platform Services Controller(PSC)内嵌和分离部署方式类似,而现在VMware只使用内嵌vPostgres数据库了,因为越往后面更新的版本功能性能越来越强,这与使用外部数据库的差距就不大了,后来PSC也仅支持内嵌部署,在简化产品构成的复杂性的同时也与产品本身更紧密集成了。
注意:进行数据库操作之前,说明已知晓风险并承担可能带来的后果。此操作不受VMware支持,请对vCenter Server做好备份和快照。
要连接到vPostgres数据库,需要先连接到vCenter Server的Shell命令行界面,所以需要先为vCenter启用SSH连接并使用root用户登录。其中,连接数据库需要用到psql命令,psql是vPostgres数据库自带的交互式命令行管理工具,该工具位于vCenter的以下目录中。
/opt/vmware/vpostgres/current/bin/psql
需要注意的是,在操作vPostgres数据库时,应该使用位于/opt/vmware/vpostgres/current/bin/中的psql二进制文件,而不是直接使用操作系统的psql二进制文件,因为这两者的版本存在一定区别。
/opt/vmware/vpostgres/current/bin/psql --version
psql --version
在连接使用vPostgres数据库之前,先来看一下psql命令工具的使用帮助。
root@vcenter [ ~ ]# /opt/vmware/vpostgres/current/bin/psql --help
psql is the PostgreSQL interactive terminal.
Usage:
psql [OPTION]... [DBNAME [USERNAME]]
General options:
-c, --command=COMMAND run only single command (SQL or internal) and exit
-d, --dbname=DBNAME database name to connect to (default: "root")
-f, --file=FILENAME execute commands from file, then exit
-l, --list list available databases, then exit
-v, --set=, --variable=NAME=VALUE
set psql variable NAME to VALUE
(e.g., -v ON_ERROR_STOP=1)
-V, --version output version information, then exit
-X, --no-psqlrc do not read startup file (~/.psqlrc)
-1 ("one"), --single-transaction
execute as a single transaction (if non-interactive)
-?, --help[=options] show this help, then exit
--help=commands list backslash commands, then exit
--help=variables list special variables, then exit
Input and output options:
-a, --echo-all echo all input from script
-b, --echo-errors echo failed commands
-e, --echo-queries echo commands sent to server
-E, --echo-hidden display queries that internal commands generate
-L, --log-file=FILENAME send session log to file
-n, --no-readline disable enhanced command line editing (readline)
-o, --output=FILENAME send query results to file (or |pipe)
-q, --quiet run quietly (no messages, only query output)
-s, --single-step single-step mode (confirm each query)
-S, --single-line single-line mode (end of line terminates SQL command)
Output format options:
-A, --no-align unaligned table output mode
--csv CSV (Comma-Separated Values) table output mode
-F, --field-separator=STRING
field separator for unaligned output (default: "|")
-H, --html HTML table output mode
-P, --pset=VAR[=ARG] set printing option VAR to ARG (see \pset command)
-R, --record-separator=STRING
record separator for unaligned output (default: newline)
-t, --tuples-only print rows only
-T, --table-attr=TEXT set HTML table tag attributes (e.g., width, border)
-x, --expanded turn on expanded table output
-z, --field-separator-zero
set field separator for unaligned output to zero byte
-0, --record-separator-zero
set record separator for unaligned output to zero byte
Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "/var/run/vpostgres")
-p, --port=PORT database server port (default: "5432")
-U, --username=USERNAME database user name (default: "root")
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)
For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within psql, or consult the psql section in the PostgreSQL
documentation.
Report bugs to <[email protected]>.
PostgreSQL home page: <https://www.postgresql.org/>
psql命令后面可以跟多个选项,比如连接选项中,-h或--host指定连接的数据库主机,-p或--port指定连接数据库的端口号(默认5432),-U或--username指定连接数据库的用户名,-W或--password指定连接数据库的密码,在通用选项中,-d或--dbname指定连接的数据库名称。通过上述选项可以连接到某个数据库中并进入交互式命令行界面,如果不想进入交互式界面,可以使用-c或者--command直接在Shell中运行数据库指令,使用-l或--list选项列出所有可用的数据库名称,-f或--file选择可以执行本地目录中的一个脚本文件。还可以设定输入input和输出output选项以及输出output的格式,比如-b选项指定命令错误了输出,-q选项静默执行,-t选项仅输出结果等等。更多详细解释请看psql说明。
/opt/vmware/vpostgres/current/bin/psql -U postgres -l
默认情况下,vCenter Server内嵌式vPostgres数据库的用户名是 postgres,这是一个superuser具有超级管理员权限,通过本地登录无需要密码皆可连接,如果想通过外面其他客户端进行登录则还需要进行其他设置,后面会说。早期的vCenter Server版本还有一个用户 vc 也具有管理员权限,不过最新的版本中该用户依然存在不过无法进行数据库创建等操作。连接数据库后,我们可以使用\du或\du+或\dg或\dg+的psql基本命令查看数据库中的所有用户及其分配的角色。
/opt/vmware/vpostgres/current/bin/psql -U postgres -d VCDB
下图是vCenter Server 6.7版本中嵌入式vPostgres数据库中所有的用户。
下图是vCenter Server 8.0版本中嵌入式vPostgres数据库中所有的用户。
查看vPostgres数据库的配置文件,vCenter Server默认的数据库实例是VCDB,数据库的存放位置是/storage/db/vpostgres。JDBC地址以及PGUSER_PASSWORD密码后面通过外部客户端连接的时候会用到。
cat /etc/vmware-vpx/embedded_db.cfg
cat /etc/vmware-vpx/vcdb.properties
使用psql工具连接到vPostgres数据库以后,进入交互式命令行界面,可以使用help查看帮助。
/opt/vmware/vpostgres/current/bin/psql -U postgres -d VCDB
使用\?可以查看 psql 基本命令。
VCDB=# \?
General
\copyright show PostgreSQL usage and distribution terms
\crosstabview [COLUMNS] execute query and display results in crosstab
\errverbose show most recent error message at maximum verbosity
\g [(OPTIONS)] [FILE] execute query (and send results to file or |pipe);
\g with no arguments is equivalent to a semicolon
\gdesc describe result of query, without executing it
\gexec execute query, then execute each value in its result
\gset [PREFIX] execute query and store results in psql variables
\gx [(OPTIONS)] [FILE] as \g, but forces expanded output mode
\q quit psql
\watch [SEC] execute query every SEC seconds
Help
\? [commands] show help on backslash commands
\? options show help on psql command-line options
\? variables show help on special variables
\h [NAME] help on syntax of SQL commands, * for all commands
Query Buffer
\e [FILE] [LINE] edit the query buffer (or file) with external editor
\ef [FUNCNAME [LINE]] edit function definition with external editor
\ev [VIEWNAME [LINE]] edit view definition with external editor
\p show the contents of the query buffer
\r reset (clear) the query buffer
\s [FILE] display history or save it to file
\w FILE write query buffer to file
Input/Output
\copy ... perform SQL COPY with data stream to the client host
\echo [-n] [STRING] write string to standard output (-n for no newline)
\i FILE execute commands from file
\ir FILE as \i, but relative to location of current script
\o [FILE] send all query results to file or |pipe
\qecho [-n] [STRING] write string to \o output stream (-n for no newline)
\warn [-n] [STRING] write string to standard error (-n for no newline)
Conditional
\if EXPR begin conditional block
\elif EXPR alternative within current conditional block
\else final alternative within current conditional block
\endif end conditional block
Informational
(options: S = show system objects, + = additional detail)
\d[S+] list tables, views, and sequences
\d[S+] NAME describe table, view, sequence, or index
\da[S] [PATTERN] list aggregates
\dA[+] [PATTERN] list access methods
\dAc[+] [AMPTRN [TYPEPTRN]] list operator classes
\dAf[+] [AMPTRN [TYPEPTRN]] list operator families
\dAo[+] [AMPTRN [OPFPTRN]] list operators of operator families
\dAp[+] [AMPTRN [OPFPTRN]] list support functions of operator families
\db[+] [PATTERN] list tablespaces
\dc[S+] [PATTERN] list conversions
\dC[+] [PATTERN] list casts
\dd[S] [PATTERN] show object descriptions not displayed elsewhere
\dD[S+] [PATTERN] list domains
\ddp [PATTERN] list default privileges
\dE[S+] [PATTERN] list foreign tables
\des[+] [PATTERN] list foreign servers
\det[+] [PATTERN] list foreign tables
\deu[+] [PATTERN] list user mappings
\dew[+] [PATTERN] list foreign-data wrappers
\df[anptw][S+] [FUNCPTRN [TYPEPTRN ...]]
list [only agg/normal/procedure/trigger/window] functions
\dF[+] [PATTERN] list text search configurations
\dFd[+] [PATTERN] list text search dictionaries
\dFp[+] [PATTERN] list text search parsers
\dFt[+] [PATTERN] list text search templates
\dg[S+] [PATTERN] list roles
\di[S+] [PATTERN] list indexes
\dl list large objects, same as \lo_list
\dL[S+] [PATTERN] list procedural languages
\dm[S+] [PATTERN] list materialized views
\dn[S+] [PATTERN] list schemas
\do[S+] [OPPTRN [TYPEPTRN [TYPEPTRN]]]
list operators
\dO[S+] [PATTERN] list collations
\dp [PATTERN] list table, view, and sequence access privileges
\dP[itn+] [PATTERN] list [only index/table] partitioned relations [n=nested]
\drds [ROLEPTRN [DBPTRN]] list per-database role settings
\dRp[+] [PATTERN] list replication publications
\dRs[+] [PATTERN] list replication subscriptions
\ds[S+] [PATTERN] list sequences
\dt[S+] [PATTERN] list tables
\dT[S+] [PATTERN] list data types
\du[S+] [PATTERN] list roles
\dv[S+] [PATTERN] list views
\dx[+] [PATTERN] list extensions
\dX [PATTERN] list extended statistics
\dy[+] [PATTERN] list event triggers
\l[+] [PATTERN] list databases
\sf[+] FUNCNAME show a function's definition
\sv[+] VIEWNAME show a view's definition
\z [PATTERN] same as \dp
Formatting
\a toggle between unaligned and aligned output mode
\C [STRING] set table title, or unset if none
\f [STRING] show or set field separator for unaligned query output
\H toggle HTML output mode (currently off)
\pset [NAME [VALUE]] set table output option
(border|columns|csv_fieldsep|expanded|fieldsep|
fieldsep_zero|footer|format|linestyle|null|
numericlocale|pager|pager_min_lines|recordsep|
recordsep_zero|tableattr|title|tuples_only|
unicode_border_linestyle|unicode_column_linestyle|
unicode_header_linestyle)
\t [on|off] show only rows (currently off)
\T [STRING] set HTML <table> tag attributes, or unset if none
\x [on|off|auto] toggle expanded output (currently off)
Connection
\c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo}
connect to new database (currently "VCDB")
\conninfo display information about current connection
\encoding [ENCODING] show or set client encoding
\password [USERNAME] securely change the password for a user
Operating System
\cd [DIR] change the current working directory
\setenv NAME [VALUE] set or unset environment variable
\timing [on|off] toggle timing of commands (currently off)
\! [COMMAND] execute command in shell or start interactive shell
Variables
\prompt [TEXT] NAME prompt user to set internal variable
\set [NAME [VALUE]] set internal variable, or list all if no parameters
\unset NAME unset (delete) internal variable
Large Objects
\lo_export LOBOID FILE
\lo_import FILE [COMMENT]
\lo_list
\lo_unlink LOBOID large object operations
VCDB=#
使用\h可以查看支持的标准 SQL 命令。
VCDB=# \h
Available help:
ABORT CHECKPOINT CREATE USER DROP TRIGGER
ALTER AGGREGATE CLOSE CREATE USER MAPPING DROP TYPE
ALTER COLLATION CLUSTER CREATE VIEW DROP USER
ALTER CONVERSION COMMENT DEALLOCATE DROP USER MAPPING
ALTER DATABASE COMMIT DECLARE DROP VIEW
ALTER DEFAULT PRIVILEGES COMMIT PREPARED DELETE END
ALTER DOMAIN COPY DISCARD EXECUTE
ALTER EVENT TRIGGER CREATE ACCESS METHOD DO EXPLAIN
ALTER EXTENSION CREATE AGGREGATE DROP ACCESS METHOD FETCH
ALTER FOREIGN DATA WRAPPER CREATE CAST DROP AGGREGATE GRANT
ALTER FOREIGN TABLE CREATE COLLATION DROP CAST IMPORT FOREIGN SCHEMA
ALTER FUNCTION CREATE CONVERSION DROP COLLATION INSERT
ALTER GROUP CREATE DATABASE DROP CONVERSION LISTEN
ALTER INDEX CREATE DOMAIN DROP DATABASE LOAD
ALTER LANGUAGE CREATE EVENT TRIGGER DROP DOMAIN LOCK
ALTER LARGE OBJECT CREATE EXTENSION DROP EVENT TRIGGER MOVE
ALTER MATERIALIZED VIEW CREATE FOREIGN DATA WRAPPER DROP EXTENSION NOTIFY
ALTER OPERATOR CREATE FOREIGN TABLE DROP FOREIGN DATA WRAPPER PREPARE
ALTER OPERATOR CLASS CREATE FUNCTION DROP FOREIGN TABLE PREPARE TRANSACTION
ALTER OPERATOR FAMILY CREATE GROUP DROP FUNCTION REASSIGN OWNED
ALTER POLICY CREATE INDEX DROP GROUP REFRESH MATERIALIZED VIEW
ALTER PROCEDURE CREATE LANGUAGE DROP INDEX REINDEX
ALTER PUBLICATION CREATE MATERIALIZED VIEW DROP LANGUAGE RELEASE SAVEPOINT
ALTER ROLE CREATE OPERATOR DROP MATERIALIZED VIEW RESET
ALTER ROUTINE CREATE OPERATOR CLASS DROP OPERATOR REVOKE
ALTER RULE CREATE OPERATOR FAMILY DROP OPERATOR CLASS ROLLBACK
ALTER SCHEMA CREATE POLICY DROP OPERATOR FAMILY ROLLBACK PREPARED
ALTER SEQUENCE CREATE PROCEDURE DROP OWNED ROLLBACK TO SAVEPOINT
ALTER SERVER CREATE PUBLICATION DROP POLICY SAVEPOINT
ALTER STATISTICS CREATE ROLE DROP PROCEDURE SECURITY LABEL
ALTER SUBSCRIPTION CREATE RULE DROP PUBLICATION SELECT
ALTER SYSTEM CREATE SCHEMA DROP ROLE SELECT INTO
ALTER TABLE CREATE SEQUENCE DROP ROUTINE SET
ALTER TABLESPACE CREATE SERVER DROP RULE SET CONSTRAINTS
ALTER TEXT SEARCH CONFIGURATION CREATE STATISTICS DROP SCHEMA SET ROLE
ALTER TEXT SEARCH DICTIONARY CREATE SUBSCRIPTION DROP SEQUENCE SET SESSION AUTHORIZATION
ALTER TEXT SEARCH PARSER CREATE TABLE DROP SERVER SET TRANSACTION
ALTER TEXT SEARCH TEMPLATE CREATE TABLE AS DROP STATISTICS SHOW
ALTER TRIGGER CREATE TABLESPACE DROP SUBSCRIPTION START TRANSACTION
ALTER TYPE CREATE TEXT SEARCH CONFIGURATION DROP TABLE TABLE
ALTER USER CREATE TEXT SEARCH DICTIONARY DROP TABLESPACE TRUNCATE
ALTER USER MAPPING CREATE TEXT SEARCH PARSER DROP TEXT SEARCH CONFIGURATION UNLISTEN
ALTER VIEW CREATE TEXT SEARCH TEMPLATE DROP TEXT SEARCH DICTIONARY UPDATE
ANALYZE CREATE TRANSFORM DROP TEXT SEARCH PARSER VACUUM
BEGIN CREATE TRIGGER DROP TEXT SEARCH TEMPLATE VALUES
CALL CREATE TYPE DROP TRANSFORM WITH
VCDB=#
通常情况下,psql基本命令和标准的sql命令可以配合使用。使用\q可以退出 psql 交互式命令行界面,下面看一下常用的psql基本命令。更多详细解释请看psql说明。
\conninfo 查看当前连接信息。
\c postgres 连接到其他数据库。
\encoding 查看当前连接编码。
\l或\l+ 查看所有数据库。
\du或\du+ 查看所有用户及分配的角色(上面说过)。
\drds 查看角色的设置。
\dn+ 查看所有schema模式。
\d+ 查看所有对象信息,包含table、view、sequence等。\dt+ 查看table,\dv+ 查看view,\ds+ 查看sequence。
\db+ 查看表空间。
\dA+ 查看访问的方法。
\a 开启或关闭输出对齐模式。上面所有的默认输出都是对齐模式,unaligned后,以 \l 为例,如下所示。
重新aligned以后,再查看数据库,所有列都对齐了。
有的时候,当查询一个比较大的表时,显示的内容展示不太友好,比如\l+查看数据库,有些内容超出第二行了。
\x 开启expanded显示后,这样就方便我们进行查看了,若要关闭再次执行\x即可。
\t 仅显示输出的结果,不显示标题。
关于PostgreSQL标准的SQL命令语法这里就不展开说明了,详细可以查看PostgreSQL教程,下面举几个例子。
查看vCenter数据库版本,表名可以tab补全。
SELECT * FROM vpx_version;
查看表空间占用最大的前十个。
SELECT nspname || '.' || relname AS "table",pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size" FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) WHERE nspname NOT IN ('pg_catalog', 'information_schema') AND C.relkind <> 'i' AND nspname !~ '^pg_toast' ORDER BY pg_total_relation_size(C.oid) DESC LIMIT 10;
查看用户登录事件。vCenter 所有事件列表。
SELECT event_type,create_time,username,vm_name FROM vc.vpxv_events where event_type like '%UserLoginSessionEvent%';
在/opt/vmware/vpostgres/current/bin/目录下除了psql二进制文件以外,还有其他二进制文件工具,关于这些工具的使用和说明可以在这里查看。关于vCenter Server vPostgres数据库的备份和还原,可以参考KB 2091961知识库文章中的方法。
上述方式连接和使用vPostgres数据库都是基于psql命令行,其实也支持使用图形化客户端工具进行管理。可以使用 pgAdmin 或者 DBeaver 客户端图形工具来管理vPostgres数据库。下面就以DBeaver社区版客户端为例,了解如何连接和使用vPostgres数据库。
默认情况下,vCenter Server数据库只能进行本地连接,不过如果要从外部进行连接也是可以的。
需要在vCenter Server上将vPostgres数据库的访问端口(5432)从iptables防火墙上放开(accept)。
iptables -I INPUT 1 -p tcp --dport 5432 -j ACCEPT
配置vPostgres数据库允许来自所有远程主机的连接并要求postgres用户的密码,配置文件位于/storage/db/vpostgres/pg_hba.conf。
echo "host all postgres 0.0.0.0/0 md5" >> /storage/db/vpostgres/pg_hba.conf
重新加载vPostgres配置以应用对pg_hba.conf的更改。
/opt/vmware/vpostgres/current/bin/psql -U postgres -c "SELECT pg_reload_conf();"
查看postgres用户的密码。
cat /etc/vmware-vpx/embedded_db.cfg
安装好DBeaver工具后,下面配置连接vPostgres数据库。
先配置用于连接PostgreSQL数据库的驱动,展开导航栏中的“数据库”,点击“驱动管理器”,找到PostgreSQL数据库并编辑。
在设置的最下面有一行网址,点击下载PostgreSQL标准驱动,保存至客户端所在的本地文件夹中。
点击“库”,将下面存在驱动全部删除,点击“添加文件”将刚刚下载的驱动加入到库中。点击确定完成驱动的添加。
展开导航栏中的“数据库”,点击“新建数据库连接”,找到PostgreSQL数据库并点击下一步。
设置PostgreSQL数据库连接,配置主机(vCenter)和数据库(VCDB),还有用户名(postgres)和密码,点击测试连接。
展开VCDB数据库,查看所有的schema模式。
在vc schema模式下,vpx_alarm表中查看vCenter所有告警列表。
vpx_datastore表中查看vCenter所有数据存储。
vpx_dvs表中查看vCenter所有分布式交换机。
vpx_network表中查看vCenter所有标准交换机。
vpx_vm表中查看vCenter所有虚拟机。
参考: