%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /usr/lib/python2.7/site-packages/salt/returners/
Upload File :
Create Path :
Current File : //usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyc

�
���^c@@s�dZddlmZmZmZddlmZddlZddlZddl	Z	ddl
ZddlZddl
ZddlmZy"ddlZddlZeZWnek
r�eZnXe	je�ZdZdad�Zdd	�Zeded
��Zd�Zd�Z dd
�Z!dd�Z"d�Z#d�Z$d�Z%d�Z&d�Z'edd�Z(d�Z)d�Z*d�Z+dS(u�
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type

:maintainer:    Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity:      Stable
:depends:       python-psycopg2
:platform:      all

.. note::
    There are three PostgreSQL returners.  Any can function as an external
    :ref:`master job cache <external-job-cache>`. but each has different
    features.  SaltStack recommends
    :mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
    a version of PostgreSQL that has the appropriate native binary JSON types.
    Otherwise, review
    :mod:`returners.postgres <salt.returners.postgres>` and
    :mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
    to see which module best suits your particular needs.

To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:

.. code-block:: yaml

    returner.pgjsonb.host: 'salt'
    returner.pgjsonb.user: 'salt'
    returner.pgjsonb.pass: 'salt'
    returner.pgjsonb.db: 'salt'
    returner.pgjsonb.port: 5432

SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.

.. code-block:: yaml

    returner.pgjsonb.sslmode: None
    returner.pgjsonb.sslcert: None
    returner.pgjsonb.sslkey: None
    returner.pgjsonb.sslrootcert: None
    returner.pgjsonb.sslcrl: None

.. versionadded:: 2017.5.0

Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:

.. code-block:: yaml

    alternative.pgjsonb.host: 'salt'
    alternative.pgjsonb.user: 'salt'
    alternative.pgjsonb.pass: 'salt'
    alternative.pgjsonb.db: 'salt'
    alternative.pgjsonb.port: 5432
    alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
    alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
    alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'

Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.

Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True.  Salt will create 3 archive tables;

- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``

and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.

.. versionadded:: 2019.2.0

Use the following Pg database schema:

.. code-block:: sql

    CREATE DATABASE  salt
      WITH ENCODING 'utf-8';

    --
    -- Table structure for table `jids`
    --
    DROP TABLE IF EXISTS jids;
    CREATE TABLE jids (
       jid varchar(255) NOT NULL primary key,
       load jsonb NOT NULL
    );
    CREATE INDEX idx_jids_jsonb on jids
           USING gin (load)
           WITH (fastupdate=on);

    --
    -- Table structure for table `salt_returns`
    --

    DROP TABLE IF EXISTS salt_returns;
    CREATE TABLE salt_returns (
      fun varchar(50) NOT NULL,
      jid varchar(255) NOT NULL,
      return jsonb NOT NULL,
      id varchar(255) NOT NULL,
      success varchar(10) NOT NULL,
      full_ret jsonb NOT NULL,
      alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());

    CREATE INDEX idx_salt_returns_id ON salt_returns (id);
    CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
    CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
    CREATE INDEX idx_salt_returns_return ON salt_returns
        USING gin (return) with (fastupdate=on);
    CREATE INDEX idx_salt_returns_full_ret ON salt_returns
        USING gin (full_ret) with (fastupdate=on);

    --
    -- Table structure for table `salt_events`
    --

    DROP TABLE IF EXISTS salt_events;
    DROP SEQUENCE IF EXISTS seq_salt_events_id;
    CREATE SEQUENCE seq_salt_events_id;
    CREATE TABLE salt_events (
        id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
        tag varchar(255) NOT NULL,
        data jsonb NOT NULL,
        alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
        master_id varchar(255) NOT NULL);

    CREATE INDEX idx_salt_events_tag on
        salt_events (tag);
    CREATE INDEX idx_salt_events_data ON salt_events
        USING gin (data) with (fastupdate=on);

Required python modules: Psycopg2

To use this returner, append '--return pgjsonb' to the salt command.

.. code-block:: bash

    salt '*' test.ping --return pgjsonb

To use the alternative configuration, append '--return_config alternative' to the salt command.

.. versionadded:: 2015.5.0

.. code-block:: bash

    salt '*' test.ping --return pgjsonb --return_config alternative

To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.

.. versionadded:: 2016.3.0

.. code-block:: bash

    salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'

i(tabsolute_importtprint_functiontunicode_literals(tcontextmanagerN(tsixupgjsonbu7INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)cC@ststdfStS(NuDCould not import pgjsonb returner; python-psycopg2 is not installed.(tHAS_PGtFalsetTrue(((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyt__virtual__�s
c
C@s�idd6dd6dd6dd6dd6}i
dd6dd6dd6dd6dd6d	d	6d
d
6dd6dd6d
d
6}tjjdjt�||dtdtd|�}d|kr�t|d�|d<n|S(u8
    Returns options used for the MySQL connection.
    u	localhostuhostusaltuuserupassudbi8uportusslmodeusslcertusslkeyusslrootcertusslcrlureturner.{0}t__salt__t__opts__tdefaults(tsaltt	returnerstget_returner_optionstformatt__virtualname__R	R
tint(tretRtattrst_options((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyt_get_options�s4

	c	c@s}t|�}ywd�tj|�D�}tjd|jd�d|jd�d|jd�d|jd	�d
|jd�|�}Wn4tjk
r�}tjj	dj
d
|���nX|jdk	r�|jdkr�da
n|j�}z~y	|VWnKtjk
rF}|j}tjjtj|��|jd�|�n$X|r]|jd�n
|jd�Wd|j�XdS(u
    Return a Pg cursor
    cS@s+i|]!\}}|dkr||�qS(usslmodeusslcertusslkeyusslrootcertusslcrl(usslmodeusslcertusslkeyusslrootcertusslcrl((t.0tktv((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pys
<dictcomp>�s		thostuhosttportuporttdbnameudbtuseruusertpasswordupassu5pgjsonb returner could not connect to database: {exc}texci�au�INSERT INTO jids
                              (jid, load)
                              VALUES (%(jid)s, %(load)s)
                              ON CONFLICT (jid) DO UPDATE
                              SET load=%(load)suROLLBACKuCOMMITN(RRt	iteritemstpsycopg2tconnecttgettOperationalErrorRt
exceptionstSaltMasterErrorRtserver_versiontNonetPG_SAVE_LOAD_SQLtcursort
DatabaseErrortargstsyststderrtwritet	text_typetexecutetclose(	RtcommitRtssl_optionstconnRR)terrterror((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyt	_get_serv�s6	
"			

c
C@s�y�t|dt��l}d}|j||d|dtjj|d�|d|jdt�tjj|�tj�f�WdQXWn$t	j
jk
r�tj
d	�nXdS(
u$
    Return data to a Pg server
    R2u�INSERT INTO salt_returns
                    (fun, jid, return, id, success, full_ret, alter_time)
                    VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))ufunujidureturnuidusuccessNuLCould not store return with pgjsonb returner. PostgreSQL server unavailable.(R7RR0R textrastJsonR"RttimeRR$R%tlogtcritical(Rtcurtsql((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytreturner scC@s�t|dt��t}xj|D]b}|jdd�}|jdd�}d}|j||tjj|�tdtj�f�qWWdQXdS(u
    Return event to Pg server

    Requires that configuration be enabled via 'event_return'
    option in master config.
    R2utaguudatauuINSERT INTO salt_events (tag, data, master_id, alter_time)
                     VALUES (%s, %s, %s, to_timestamp(%s))uidN(	R7RR"R0R R8R9R
R:(teventsR=teventttagtdataR>((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytevent_return4s
c	C@satdt��L}y.|jti|d6tjj|�d6�Wntjk
rVnXWdQXdS(u/
    Save the load to the specified jid id
    R2ujiduloadN(R7RR0R(R R8R9tIntegrityError(tjidtloadtminionsR=((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyt	save_loadEs	%cC@sdS(u&
    Included for API consistency
    N((RFRHt	syndic_id((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytsave_minionsTscC@sYtdddt��>}d}|j||f�|j�}|rK|dSiSWdQXdS(u9
    Return the load data that marks a specified jid
    RR2u%SELECT load FROM jids WHERE jid = %s;iN(R7R'RR0tfetchone(RFR=R>RC((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytget_load[scC@s{tdddt��`}d}|j||f�|j�}i}|rmx!|D]\}}|||<qPWn|SWdQXdS(uP
    Return the information returned when the specified job id was executed
    RR2uDSELECT id, full_ret FROM salt_returns
                WHERE jid = %sN(R7R'RR0tfetchall(RFR=R>RCRtminiontfull_ret((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytget_jidiscC@s~tdddt��c}d}|j||f�|j�}i}|rpx$|D]\}}}|||<qPWn|SWdQXdS(uC
    Return a dict of the last function called for all minions
    RR2uSELECT s.id,s.jid, s.full_ret
                FROM salt_returns s
                JOIN ( SELECT MAX(`jid`) as jid
                    from salt_returns GROUP BY fun, id) max
                ON s.jid = max.jid
                WHERE s.fun = %s
                N(R7R'RR0RN(tfunR=R>RCRROt_RP((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytget_fun{scC@s~tdddt��c}d}|j|�|j�}i}x0|D](\}}tjjj||�||<qDW|SWdQXdS(u&
    Return a list of all job ids
    RR2u*SELECT jid, load
                FROM jidsN(	R7R'RR0RNRtutilsRFtformat_jid_instance(R=R>RCRRFRG((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytget_jids�s
 cC@smtdddt��R}d}|j|�|j�}g}x|D]}|j|d�qDW|SWdQXdS(u"
    Return a list of minions
    RR2u4SELECT DISTINCT id
                FROM salt_returnsiN(R7R'RR0RNtappend(R=R>RCRRO((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytget_minions�s

cC@s#|dk	r|Stjjjt�S(uO
    Do any work necessary to prepare a JID, including sending a custom id
    N(R'RRURFtgen_jidR
(tnocachet
passed_jid((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytprep_jid�sc	C@s~t��o}y*d}|j||f�|jd�WnKtjk
r�}|j}tjjtj	|��|jd�|�nXy*d}|j||f�|jd�WnKtjk
r�}|j}tjjtj	|��|jd�|�nXy*d}|j||f�|jd�WnKtjk
rs}|j}tjjtj	|��|jd�|�nXWdQXt
S(uy
    Purge records from the returner tables.
    :param job_age_in_seconds:  Purge jobs older than this
    :return:
    u[delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)uCOMMITuROLLBACKu.delete from salt_returns where alter_time < %su-delete from salt_events where alter_time < %sN(R7R0R R*R+R,R-R.RR/R(t	timestampR)R>R5R6((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyt_purge_jobs�s:	

	

	
c

C@s�dddg}t��j}i}x�|D]�}yD|d}dj||�}|j|�|jd�|||<Wq(tjk
r�}|j}tjjt	j
|��|jd�|�q(Xq(Wy:dj|dd�}|j||f�|jd�Wnmtjk
rK}|j}tjjt	j
|��|jd�|�n#tk
rm}	tj
|	��nXy:d	j|dd�}|j||f�|jd�WnKtjk
r�}|j}tjjt	j
|��|jd�|�nXy:d	j|dd�}|j||f�|jd�WnKtjk
r}}|j}tjjt	j
|��|jd�|�nXWd
QXt|�S(u�
    Copy rows to a set of backup tables, then purge rows.
    :param timestamp: Archive rows older than this timestamp
    :return:
    ujidsusalt_returnsusalt_eventsu_archiveu)create table IF NOT exists {0} (LIKE {1})uCOMMITuROLLBACKulinsert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)u7insert into {0} select * from {1} where alter_time < %sN(R7RR0R R*R+R,R-R.RR/t	ExceptionR;R6R_(
R^t
source_tablesR)t
target_tablest
table_namettmp_table_nameR>R5R6te((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyt
_archive_jobs�s`	



	
	
	
	

	
cC@s�tjdt�r�ttjdd��dkr�yyt��A}djtd�}|j|�|j�}|dd}WdQXtjdt�r�t|�n
t	|�Wq�t
k
r�}tj|�q�XndS(u�
    Called in the master's event loop every loop_interval.  Archives and/or
    deletes the events and job details from the database.
    :return:
    u	keep_jobsiu/select (NOW() -  interval '{0}' hour) as stamp;Nuarchive_jobs(
R
R"RRR7RR0RNRfR_R`R;R6(R=R>trowststampRe((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pytclean_old_jobs!s0

(,t__doc__t
__future__RRRt
contextlibRR,R:tloggingtsalt.returnersRtsalt.utils.jidtsalt.exceptionstsalt.extRR tpsycopg2.extrasRRtImportErrorRt	getLoggert__name__R;RR(RR'RR7R?RDRIRKRMRQRTRWRYR]R_RfRi(((s:/usr/lib/python2.7/site-packages/salt/returners/pgjsonb.pyt<module>�sF


	%1								(	=

Zerion Mini Shell 1.0