要记录某一时段机器CPU、内存、硬盘的信息,展示的时间粒度为分钟,但是为了精确,输入数据源的时间粒度为6s。这个统计过程可以在应用层做好,每分钟插入一次,也可以在数据库层写个存储过程来完成,根据传入数据的时间来判断是更新数据库旧数据还是插入新数据。
同时,这些数据只需要保留一周,更老的数据需要被删除。删除动作可以每天定时执行一次,也可以写在存储过程中每次检查一下。
考虑到性能在此时没什么太大约束,而后面存储过程的接口方式更漂亮些,不用应用层去关心数据到底组织成什么样,因此实现了一个如下:
Postgresql V8.3
CREATE OR REPLACE FUNCTION insert_host_status(_log_date timestamp without time zone, _host inet, _cpu integer, _mem integer, _disk integer)
RETURNS void AS
$BODY$
DECLARE
new_start timestamp without time zone;
current_start timestamp without time zone;
c_id integer;
c_log_date timestamp without time zone;
c_cpu integer;
c_mem integer;
c_disk integer;
c_count integer;
date_span interval;
BEGIN
-- insert or update
SELECT id, log_date, cpu, mem, disk, count INTO c_id, c_log_date, c_cpu, c_mem, c_disk, c_count FROM host_statu