Один ΠΈΠ· ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΎΠ² получСния истории Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΎΠΊ Π² PostgreSQL

ΠŸΡ€ΠΎΠ΄ΠΎΠ»ΠΆΠ΅Π½ΠΈΠ΅ ΡΡ‚Π°Ρ‚ΡŒΠΈ «ΠŸΠΎΠΏΡ‹Ρ‚ΠΊΠ° ΡΠΎΠ·Π΄Π°Ρ‚ΡŒ Π°Π½Π°Π»ΠΎΠ³ ASH для PostgreSQL «.

Π’ ΡΡ‚Π°Ρ‚ΡŒΠ΅ Π±ΡƒΠ΄Π΅Ρ‚ рассмотрСно ΠΈ ΠΏΠΎΠΊΠ°Π·Π°Π½ΠΎ Π½Π° ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½Ρ‹Ρ… запросах ΠΈ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°Ρ… β€” ΠΊΠ°ΠΊΡƒΡŽ ΠΆΠ΅ ΠΏΠΎΠ»Π΅Π·Π½ΡƒΡŽ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΌΠΎΠΆΠ½ΠΎ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΡ‚ΡŒ с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ истории прСдставлСния pg_locks.

ΠŸΡ€Π΅Π΄ΡƒΠΏΡ€Π΅ΠΆΠ΄Π΅Π½ΠΈΠ΅.
Π’ связи с Π½ΠΎΠ²ΠΈΠ·Π½ΠΎΠΉ Ρ‚Π΅ΠΌΡ‹ ΠΈ Π½Π΅Π·Π°Π²Π΅Ρ€ΡˆΠ΅Π½ΠΈΠ΅ΠΌ ΠΏΠ΅Ρ€ΠΈΠΎΠ΄Π° тСстирования, ΡΡ‚Π°Ρ‚ΡŒΡ ΠΌΠΎΠΆΠ΅Ρ‚ ΡΠΎΠ΄Π΅Ρ€ΠΆΠ°Ρ‚ΡŒ ошибки. ΠšΡ€ΠΈΡ‚ΠΈΠΊΠ° ΠΈ замСчания всячСски ΠΏΡ€ΠΈΠ²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‚ΡΡ ΠΈ ΠΎΠΆΠΈΠ΄Π°ΡŽΡ‚ΡΡ.

Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅

Π˜ΡΡ‚ΠΎΡ€ΠΈΡ прСдставлСния pg_locks

archive_locking

CREATE TABLE archive_locking 
(       timepoint timestamp without time zone ,
	locktype text ,
	relation oid ,
	mode text ,
	tid xid ,
	vtid text ,
	pid integer ,
	blocking_pids integer[] ,
	granted boolean ,
        queryid bigint 
);

По сути, Ρ‚Π°Π±Π»ΠΈΡ†Π° Π°Π½Π°Π»ΠΎΠ³ΠΈΡ‡Π½Π° Ρ‚Π°Π±Π»ΠΈΡ†Π΅ archive_pg_stat_activity, Π±ΠΎΠ»Π΅Π΅ ΠΏΠΎΠ΄Ρ€ΠΎΠ±Π½ΠΎ описанной здСсь β€” pg_stat_statements + pg_stat_activity + loq_query = pg_ash? ΠΈ здСсь β€” ΠŸΠΎΠΏΡ‹Ρ‚ΠΊΠ° ΡΠΎΠ·Π΄Π°Ρ‚ΡŒ Π°Π½Π°Π»ΠΎΠ³ ASH для PostgreSQL.

Для заполнСния столбца queryid ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅Ρ‚ΡΡ функция

update_history_locking_by_queryid

--update_history_locking_by_queryid.sql
CREATE OR REPLACE FUNCTION update_history_locking_by_queryid() RETURNS boolean AS $$
DECLARE
  result boolean ;
  current_minute double precision ; 
  
  start_minute integer ;
  finish_minute integer ;
  
  start_period timestamp without time zone ;
  finish_period timestamp without time zone ;
  
  lock_rec record ; 
  endpoint_rec record ; 
  
  current_hour_diff double precision ;
BEGIN
  RAISE NOTICE '***update_history_locking_by_queryid';
  
  result = TRUE ;
  
  current_minute = extract ( minute from now() );

  SELECT * FROM endpoint WHERE is_need_monitoring
  INTO endpoint_rec ;
  
  current_hour_diff = endpoint_rec.hour_diff ;
  
  IF current_minute < 5 
  THEN
	RAISE NOTICE 'Current time is less than 5 minute.';
	
	start_period = date_trunc('hour',now()) + (current_hour_diff * interval '1 hour');
    finish_period = start_period - interval '5 minute' ;
  ELSE 
    finish_minute =  extract ( minute from now() ) / 5 ;
    start_minute =  finish_minute - 1 ;
  
    start_period = date_trunc('hour',now()) + interval '1 minute'*start_minute*5+(current_hour_diff * interval '1 hour');
    finish_period = date_trunc('hour',now()) + interval '1 minute'*finish_minute*5+(current_hour_diff * interval '1 hour') ;
    
  END IF ;  
  
  RAISE NOTICE 'start_period = %', start_period;
  RAISE NOTICE 'finish_period = %', finish_period;

	FOR lock_rec IN   
	WITH act_queryid AS
	 (
		SELECT 
				pid , 
				timepoint ,
				query_start AS started ,			
				MAX(timepoint) OVER (PARTITION BY pid ,	query_start   ) AS finished ,			
				queryid 
		FROM 
				activity_hist.history_pg_stat_activity 			
		WHERE 			
				timepoint BETWEEN start_period and 
								  finish_period
		GROUP BY 
				pid , 
				timepoint ,  
				query_start ,
				queryid 
	 ),
	 lock_pids AS
		(
			SELECT
				hl.pid , 
				hl.locktype  ,
				hl.mode ,
				hl.timepoint , 
				MIN ( timepoint ) OVER (PARTITION BY pid , locktype  ,mode ) as started 
			FROM 
				activity_hist.history_locking hl
			WHERE 
				hl.timepoint between start_period and 
								     finish_period
			GROUP BY 
				hl.pid , 
				hl.locktype  ,
				hl.mode ,
				hl.timepoint 
		)
	SELECT 
		lp.pid , 
		lp.locktype  ,
		lp.mode ,
		lp.timepoint ,     
		aq.queryid 
	FROM lock_pids 	lp LEFT OUTER JOIN act_queryid aq ON ( lp.pid = aq.pid AND lp.started BETWEEN aq.started AND aq.finished )
	WHERE aq.queryid IS NOT NULL 
	GROUP BY  
		lp.pid , 
		lp.locktype  ,
		lp.mode ,
		lp.timepoint , 
		aq.queryid
	LOOP
		UPDATE activity_hist.history_locking SET queryid = lock_rec.queryid 
		WHERE pid = lock_rec.pid AND locktype = lock_rec.locktype AND mode = lock_rec.mode AND timepoint = lock_rec.timepoint ;	
	END LOOP;    
  
  RETURN result ;
END
$$ LANGUAGE plpgsql;

ПояснСниС: Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ столбца queryid обновляСтся Π² Ρ‚Π°Π±Π»ΠΈΡ†Π΅ history_locking, ΠΈ Π·Π°Ρ‚Π΅ΠΌ ΠΏΡ€ΠΈ создании Π½ΠΎΠ²ΠΎΠΉ сСкции для Ρ‚Π°Π±Π»ΠΈΡ†Ρ‹ archive_locking, Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ Π±ΡƒΠ΄Π΅Ρ‚ сохранСно Π² историчСских значСниях.

Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅

ΠžΠ±Ρ‰Π°Ρ информация, ΠΏΠΎ процСссам Π² Ρ†Π΅Π»ΠΎΠΌ.

WAITING FOR LOCKS BY LOCKTYPES

Запрос

WITH
t AS
(
	SELECT 
		locktype  ,
		mode ,
		count(*) as total 
	FROM 
		activity_hist.archive_locking
	WHERE 
		timepoint between pg_stat_history_begin+(current_hour_diff * interval '1 hour') AND pg_stat_history_end+(current_hour_diff * interval '1 hour') AND 
		NOT granted
	GROUP BY 
		locktype  ,
		mode  
)
SELECT 
	locktype  ,
	mode ,
	total * interval '1 second' as duration			
FROM t 		
ORDER BY 3 DESC 

ΠŸΡ€ΠΈΠΌΠ΅Ρ€

| WAITING FOR LOCKS BY LOCKTYPES
+--------------------+------------------------------+--------------------
|            locktype|                          mode|            duration
+--------------------+------------------------------+--------------------
|       transactionid|                     ShareLock|            19:39:26
|               tuple|           AccessExclusiveLock|            00:03:35
+--------------------+------------------------------+--------------------

TAKINGS OF LOCKS BY LOCKTYPES

Запрос

WITH
t AS
(
	SELECT 
		locktype  ,
		mode ,
		count(*) as total 
	FROM 
		activity_hist.archive_locking
	WHERE 
		timepoint between pg_stat_history_begin+(current_hour_diff * interval '1 hour') AND pg_stat_history_end+(current_hour_diff * interval '1 hour') AND 
		granted
	GROUP BY 
		locktype  ,
		mode  
)
SELECT 
	locktype  ,
	mode ,
	total * interval '1 second' as duration			
FROM t 		
ORDER BY 3 DESC 

ΠŸΡ€ΠΈΠΌΠ΅Ρ€

| TAKINGS OF  LOCKS BY LOCKTYPES
+--------------------+------------------------------+--------------------
|            locktype|                          mode|            duration
+--------------------+------------------------------+--------------------
|            relation|              RowExclusiveLock|            51:11:10
|          virtualxid|                 ExclusiveLock|            48:10:43
|       transactionid|                 ExclusiveLock|            44:24:53
|            relation|               AccessShareLock|            20:06:13
|               tuple|           AccessExclusiveLock|            17:58:47
|               tuple|                 ExclusiveLock|            01:40:41
|            relation|      ShareUpdateExclusiveLock|            00:26:41
|              object|              RowExclusiveLock|            00:00:01
|       transactionid|                     ShareLock|            00:00:01
|              extend|                 ExclusiveLock|            00:00:01
+--------------------+------------------------------+--------------------

Π”Π΅Ρ‚Π°Π»ΡŒΠ½Π°Ρ информация, ΠΏΠΎ ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½Ρ‹ΠΌ queryid запросов

WAITING FOR LOCKS BY LOCKTYPES BY QUERYID

Запрос

WITH
lt AS
(
	SELECT
		pid , 
		locktype  ,
		mode ,
		timepoint , 
		queryid , 
		blocking_pids ,
                MIN ( timepoint ) OVER (PARTITION BY pid , locktype  ,mode ) as started  
	FROM 
		activity_hist.archive_locking
	WHERE 
		timepoint between pg_stat_history_begin+(current_hour_diff * interval '1 hour') AND 
			                  pg_stat_history_end+(current_hour_diff * interval '1 hour') AND 
		NOT granted AND
	       queryid IS NOT NULL 
	GROUP BY 
	        pid , 
		locktype  ,
		mode ,
		timepoint ,
		queryid ,
		blocking_pids 
)
SELECT 
        lt.pid , 
	lt.locktype  ,
	lt.mode ,			
        lt.started ,
	lt.queryid  ,
	lt.blocking_pids ,
	COUNT(*)  * interval '1 second'	 as duration		
FROM lt 	
GROUP BY 
	lt.pid , 
        lt.locktype  ,
	lt.mode ,			
        lt.started ,
        lt.queryid ,
	lt.blocking_pids 
ORDER BY 4

ΠŸΡ€ΠΈΠΌΠ΅Ρ€

| WAITING FOR LOCKS BY LOCKTYPES BY QUERYID
+----------+-------------------------+--------------------+------------------------------+--------------------+--------------------+--------------------
|       pid|                 locktype|                mode|                       started|             queryid|       blocking_pids|            duration
+----------+-------------------------+--------------------+------------------------------+--------------------+--------------------+--------------------
|     11288|            transactionid|           ShareLock|    2019-09-17 10:00:00.302936|  389015618226997618|             {11092}|            00:03:34
|     11626|            transactionid|           ShareLock|    2019-09-17 10:00:21.380921|  389015618226997618|             {12380}|            00:00:29
|     11626|            transactionid|           ShareLock|    2019-09-17 10:00:21.380921|  389015618226997618|             {11092}|            00:03:25
|     11626|            transactionid|           ShareLock|    2019-09-17 10:00:21.380921|  389015618226997618|             {12213}|            00:01:55
|     11626|            transactionid|           ShareLock|    2019-09-17 10:00:21.380921|  389015618226997618|             {12751}|            00:00:01
|     11629|            transactionid|           ShareLock|    2019-09-17 10:00:24.331935|  389015618226997618|             {11092}|            00:03:22
|     11629|            transactionid|           ShareLock|    2019-09-17 10:00:24.331935|  389015618226997618|             {12007}|            00:00:01
|     12007|            transactionid|           ShareLock|    2019-09-17 10:05:03.327933|  389015618226997618|             {11629}|            00:00:13
|     12007|            transactionid|           ShareLock|    2019-09-17 10:05:03.327933|  389015618226997618|             {11092}|            00:01:10
|     12007|            transactionid|           ShareLock|    2019-09-17 10:05:03.327933|  389015618226997618|             {11288}|            00:00:05
|     12213|            transactionid|           ShareLock|    2019-09-17 10:06:07.328019|  389015618226997618|             {12007}|            00:00:10

TAKING LOCKS BY LOCKTYPES BY QUERYID

Запрос

WITH
lt AS
(
	SELECT
		pid , 
		locktype  ,
		mode ,
		timepoint , 
		queryid , 
		blocking_pids ,
                MIN ( timepoint ) OVER (PARTITION BY pid , locktype  ,mode ) as started  
	FROM 
		activity_hist.archive_locking
	WHERE 
		timepoint between pg_stat_history_begin+(current_hour_diff * interval '1 hour') AND 
			                  pg_stat_history_end+(current_hour_diff * interval '1 hour') AND 
		granted AND
		queryid IS NOT NULL 
	GROUP BY 
	        pid , 
		locktype  ,
		mode ,
		timepoint ,
		queryid ,
		blocking_pids 
)
SELECT 
        lt.pid , 
	lt.locktype  ,
	lt.mode ,			
        lt.started ,
	lt.queryid  ,
	lt.blocking_pids ,
	COUNT(*)  * interval '1 second'	 as duration			
FROM lt 	
GROUP BY 
	lt.pid , 
	lt.locktype  ,
	lt.mode ,			
        lt.started ,
	lt.queryid ,
	lt.blocking_pids 
ORDER BY 4

ΠŸΡ€ΠΈΠΌΠ΅Ρ€

| TAKING LOCKS BY LOCKTYPES BY QUERYID
+----------+-------------------------+--------------------+------------------------------+--------------------+--------------------+--------------------
|       pid|                 locktype|                mode|                       started|             queryid|       blocking_pids|            duration
+----------+-------------------------+--------------------+------------------------------+--------------------+--------------------+--------------------
|     11288|                 relation|    RowExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|             {11092}|            00:03:34
|     11092|            transactionid|       ExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|                  {}|            00:03:34
|     11288|                 relation|    RowExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|                  {}|            00:00:10
|     11092|                 relation|    RowExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|                  {}|            00:03:34
|     11092|               virtualxid|       ExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|                  {}|            00:03:34
|     11288|               virtualxid|       ExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|             {11092}|            00:03:34
|     11288|            transactionid|       ExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|             {11092}|            00:03:34
|     11288|                    tuple| AccessExclusiveLock|    2019-09-17 10:00:00.302936|  389015618226997618|             {11092}|            00:03:34

ИспользованиС истории Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΎΠΊ ΠΏΡ€ΠΈ Π°Π½Π°Π»ΠΈΠ·Π΅ ΠΈΠ½Ρ†ΠΈΠ΄Π΅Π½Ρ‚ΠΎΠ² ΠΏΡ€ΠΎΠΈΠ·Π²ΠΎΠ΄ΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎΡΡ‚ΠΈ.

  1. Запрос с queryid=389015618226997618 выполняСмый процСссом с pid=11288 ΠΎΠΆΠΈΠ΄Π°Π» Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΊΠΈ начиная с 2019-09-17 10:00:00 Π² Ρ‚Π΅Ρ‡Π΅Π½ΠΈΠΈ 3-Ρ… ΠΌΠΈΠ½ΡƒΡ‚.
  2. Π‘Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΊΡƒ ΡƒΠ΄Π΅Ρ€ΠΆΠΈΠ²Π°Π» процСсс с pid=11092
  3. ΠŸΡ€ΠΎΡ†Π΅ΡΡ с pid=11092 выполняя запрос с queryid=389015618226997618 начиная с 2019-09-17 10:00:00 ΡƒΠ΄Π΅Ρ€ΠΆΠΈΠ²Π°Π» Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΊΡƒ Π² Ρ‚Π΅Ρ‡Π΅Π½ΠΈΠΈ 3-Ρ… ΠΌΠΈΠ½ΡƒΡ‚.

Π˜Ρ‚ΠΎΠ³

Π’Π΅ΠΏΠ΅Ρ€ΡŒ, надСюсь, начинСтся самоС интСрСсноС ΠΈ ΠΏΠΎΠ»Π΅Π·Π½ΠΎΠ΅- сбор статистики ΠΈ Π°Π½Π°Π»ΠΈΠ· кСйсов ΠΏΠΎ истории ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΠΉ ΠΈ Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΎΠΊ.

Π’ пСрспСктивС, хочСтся Π²Π΅Ρ€ΠΈΡ‚ΡŒ, получится Π½Π°Π±ΠΎΡ€ Π½Π΅ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… ΠΊΠ°ΠΊ Π±Ρ‹ note(ΠΏΠΎ Π°Π½Π°Π»ΠΎΠ³Ρƒ с ΠΌΠ΅Ρ‚Π°Π»ΠΈΠ½ΠΊΠΎΠΌ ΠžΡ€Π°ΠΊΠ»Π°).

Π’ ΠΎΠ±Ρ‰Π΅ΠΌ-Ρ‚ΠΎ, ΠΈΠΌΠ΅Π½Π½ΠΎ ΠΏΠΎ этой ΠΏΡ€ΠΈΡ‡ΠΈΠ½Π΅ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅ΠΌΠ°Ρ ΠΌΠ΅Ρ‚ΠΎΠ΄ΠΈΠΊΠ°, максимально быстро выводится для всСобщСго ознакомлСния.

Π’ самоС блиТайшСС врСмя ΠΏΠΎΡΡ‚Π°Ρ€Π°ΡŽΡΡŒ Π²Ρ‹Π»ΠΎΠΆΠΈΡ‚ΡŒ ΠΏΡ€ΠΎΠ΅ΠΊΡ‚ Π½Π° github.

Π˜ΡΡ‚ΠΎΡ‡Π½ΠΈΠΊ: habr.com