---
title: "pg启动过程中的那些事三：加载GUC参数"
author: "BeiGang"
date: "2011-12-09T20:14:49Z"
tags: []
categories: ["数据库"]
slug: "pg-guc"
draft: false
lastmod: "2011-12-09T20:21:59Z"
id: 1300203
url: "https://beigang.iteye.com/blog/1300203"
---

**1 先上个图，看一下函数调用过程梗概，中间细节有略**

 

![](http://dl.iteye.com/upload/attachment/603558/b8e16874-8260-3b8a-a22f-51cccd5b8b71.png)

      GUC 参数初始化分两步，第一步先读取 buildin/ compiled-in 的 GUC 参数默认值，这里包括全部的 GUC 参数，建立 GUC 参数相关结构变量，第二步读取 postgresql.conf 配置文件中的参数设置之。从上图中能看出来，这个读取并设置 postgresql.conf 中参数的过程还是挺复杂的。

**2** **初始化** **GUC** **相关数据结构并取** **hardcode/buildin** **的参数值。**

       pg 里的GUC 参数按设置的值分五种类型，分别是bool 、int 、real 、string 、enum ，根据这五种类型，定义了五种结构类型，再根据这五种结构，每个类型建一个对应的静态数组，用于存储这些相应类型的GUC 参数。这五种类型是config\_bool 、config\_int 、config\_real 、config\_string 、config\_enum ，对应的静态数组是ConfigureNamesBool 、ConfigureNamesInt 、ConfigureNamesReal 、ConfigureNamesString 、ConfigureNamesEnum 。具体结构和数组定义见下面。

 

五个结构定义：

struct config\_bool

{

    struct config\_generic gen;

    /* these fields must be set correctly in initial value: \*/

    /* (all but reset\_val are constants) \*/

    bool        \*variable;

    bool         boot\_val;

    GucIntCheckHook check\_hook;

    GucBoolAssignHook assign\_hook;

    GucShowHook show\_hook;

    /* variable fields, initialized at runtime: \*/

    bool         reset\_val;

    void         * reset\_extra

};

 

struct config\_int

{

    struct config\_generic gen;

/* constant fields, must be set correctly in initial value: \*/

    int         \*variable;

    int          boot\_val;

    int          min;

    int          max;

    GucIntCheckHook check\_hook;

    GucIntAssignHook assign\_hook;

    GucShowHook show\_hook;

    /* variable fields, initialized at runtime: \*/

    int          reset\_val;

    void         * reset\_extra

};

 

struct config\_real

{

    struct config\_generic gen;

/* constant fields, must be set correctly in initial value: \*/

    double      \*variable;

    double       boot\_val;

    double       min;

    double       max;

    GucIntCheckHook check\_hook;

    GucRealAssignHook assign\_hook;

    GucShowHook show\_hook;

    /* variable fields, initialized at runtime: \*/

    double       reset\_val;

    void         * reset\_extra

};

 

struct config\_string

{

    struct config\_generic gen;

/* constant fields, must be set correctly in initial value: \*/

    char       \*\*variable;

    const char \*boot\_val;

    GucIntCheckHook check\_hook;

    GucStringAssignHook assign\_hook;

    GucShowHook show\_hook;

    /* variable fields, initialized at runtime: \*/

    char        \*reset\_val;

void         * reset\_extra

};

struct config\_enum

{

    struct config\_generic gen;

/* constant fields, must be set correctly in initial value: \*/

    int   \*variable;

    int     boot\_val;

    GucIntCheckHook check\_hook;

    GucStringAssignHook assign\_hook;

    GucShowHook show\_hook;

    /* variable fields, initialized at runtime: \*/

    int    reset\_val;

void         * reset\_extra

};

 

和结构类型对应的五个静态数组：

static struct config\_bool ConfigureNamesBool\[] =

{

       {

              {"enable\_seqscan", PGC\_USERSET, QUERY\_TUNING\_METHOD,

                     gettext\_noop("Enables the planner's use of sequential-scan plans."),

                     NULL

              },

              &enable\_seqscan,

              true,

              NULL, NULL, NULL

       },

……

       /* End-of-list marker \*/

       {

              {NULL, 0, 0, NULL, NULL}, NULL, false, NULL, NULL, NULL

       }

};

 

static struct config\_int ConfigureNamesInt\[] =

{

       {

              {"archive\_timeout", PGC\_SIGHUP, WAL\_ARCHIVING,

                     gettext\_noop("Forces a switch to the next xlog file if a "

                                            "new file has not been started within N seconds."),

                     NULL,

                     GUC\_UNIT\_S

              },

              &XLogArchiveTimeout,

              0, 0, INT\_MAX,

              NULL, NULL, NULL

       },

……

       /* End-of-list marker \*/

       {

              {NULL, 0, 0, NULL, NULL}, NULL, 0, 0, 0, NULL, NULL, NULL

       }

};

 

 

static struct config\_real ConfigureNamesReal\[] =

{

       {

              {"seq\_page\_cost", PGC\_USERSET, QUERY\_TUNING\_COST,

                     gettext\_noop("Sets the planner's estimate of the cost of a "

                                            "sequentially fetched disk page."),

                     NULL

              },

              &seq\_page\_cost,

              DEFAULT\_SEQ\_PAGE\_COST, 0, DBL\_MAX,

              NULL, NULL, NULL

       },

       /* End-of-list marker \*/

       {

              {NULL, 0, 0, NULL, NULL}, NULL, 0.0, 0.0, 0.0, NULL, NULL, NULL

       }

};

 

 

static struct config\_string ConfigureNamesString\[] =

{

       {

              {"archive\_command", PGC\_SIGHUP, WAL\_ARCHIVING,

                     gettext\_noop("Sets the shell command that will be called to archive a WAL file."),

                     NULL

              },

              &XLogArchiveCommand,

              "",

              NULL, NULL, show\_archive\_command

       },

……

       /* End-of-list marker \*/

       {

              {NULL, 0, 0, NULL, NULL}, NULL, NULL, NULL, NULL, NULL

       }

};

 

 

static struct config\_enum ConfigureNamesEnum\[] =

{

       {

              {"backslash\_quote", PGC\_USERSET, COMPAT\_OPTIONS\_PREVIOUS,

                     gettext\_noop("Sets whether \\"\\\\'\\" is allowed in string literals."),

                     NULL

              },

              &backslash\_quote,

              BACKSLASH\_QUOTE\_SAFE\_ENCODING, backslash\_quote\_options,

              NULL, NULL, NULL

       },

……

       /* End-of-list marker \*/

       {

              {NULL, 0, 0, NULL, NULL}, NULL, 0, NULL, NULL, NULL, NULL

       }

};

 

上面五个结构定义中，每个结构的第一个成员变量都是一个 config\_generic 结构的 gen 成员，下面是 config\_generic 的结构定义：

struct config\_generic

{

       /* constant fields, must be set correctly in initial value: \*/

       const char \*name;                 /* name of variable - MUST BE FIRST \*/

       GucContext       context;              /* context required to set the variable \*/

       enum config\_group group;   /* to help organize variables by function \*/

       const char \*short\_desc;         /* short desc. of this variable's purpose \*/

       const char \*long\_desc;          /* long desc. of this variable's purpose \*/

       int                  flags;                   /* flag bits, see below \*/

       /* variable fields, initialized at runtime: \*/

       enum config\_type vartype;  /* type of variable (set only at startup) \*/

       int                  status;                 /* status bits, see below \*/

       GucSource  reset\_source;      /* source of the reset\_value \*/

       GucSource  source;                /* source of the current actual value \*/

       GucStack   \*stack;               /* stacked outside-of-transaction states \*/

       void           \*extra;                   /* "extra" pointer for current actual value \*/

       char          \*sourcefile;           /* file current setting is from (NULL if not

                                  * file) \*/

       int                  sourceline;          /* line in source file \*/

};

 

然后，定义一个 config\_generic \** 类型的 静态变量数组 guc\_variables ， 再计算参数总数，所有参数以 config\_generic * 类型计算所需内存空间，冗余 25% 内存后 malloc 分配内存空间。 把guc\_variables 每一个元素指向ConfigureNamesBool 、ConfigureNamesInt 、ConfigureNamesReal 、ConfigureNamesString 、ConfigureNamesEnum 这五个数组的config\_generic 类型成员gen 的地址，然后按照参数名称把所有元素做了快速排序。这个过程中还设置了一些GUC 参数的默认值。

static struct config\_generic \*\*guc\_variables;

    后面查询GUC 参数都是在guc\_variables 这个已排序的数组里找。这样GUC 参数的数据结构就搭建完成了，下面看看GUC 参数相关的数据结构图吧。

    先把涉及到的结构的图分别列出，再画个这些结构的组织关系示意图。

 

![](http://dl.iteye.com/upload/attachment/603560/cd8c4adb-f314-3dc3-86c7-abc11c4daec5.png)

![](http://dl.iteye.com/upload/attachment/603562/540bbddf-8f92-3ee8-ad5a-afc62800d197.png)

![](http://dl.iteye.com/upload/attachment/603564/d95ea20e-c9da-320f-8e46-d46bd0ccac55.png)

 

 

**3** **加载** **postgresql.conf** **参数配置文件里的参数设置**

       从 main-&gt;PostmasterMain-&gt;SelectConfigFiles-&gt;ProcessConfigFile 开始处理参数配置文件 postgresql.conf ， 读取 postgresql.conf 配置文件的调用过程是 ProcessConfigFile -&gt; ParseConfigFile -&gt; AllocateFile-&gt;fopen ，最后用fopen 打开文件，其中ProcessConfigFile 、ParseConfigFile 在文件src\\backend\\utils\\misc\\guc-file.l 中，AllocateFile 在文件src\\backend\\storage\\file\\fd.c 中。

    pg 使用 flex 去处理 conf 文件 。 在 ParseConfig File 中把配置文件中的配置项组织成一个链表，调用 set\_config\_option 检查这些值是否有效，若可以设置就调用 set\_config\_option 设置这些值。

 

这里以 "max\_connections" 做例子 ，从配置文件读取 "max\_connections" ，然后 从 guc\_variables 数组 中找元素 " max\_connections " ， 比较参数结构的 GucContext （枚举类参数能被设置的时机。定义见下面）枚举类型成员 context 和当前时间，看是否可以此刻修改。接着比较参数结构的 GucSource （枚举了当前 GUC 参数设置的来源。除非参数新值的来源等级不小于原参数的来源等级时，新设置才能生效。例如，修改配置文件不能覆盖 postmaster command line 的设置。定义见下面）枚举类型成员 source 和新参数值的来源，看是否可以修改。如果可以， 把 config\_generic 结构类型的元素 " max\_connections " 类型转换为 config\_int 类型，修改variable 成员为新值，修改该参数的来源source 为当前来源PGC\_S\_FILE ，如果 元素 " max\_connections " 的 reset\_source &lt;= source ，修改reset\_val 成员为新值，修改该参数的reset\_source 为当前来源PGC\_S\_FILE 。

 

typedef enum

{

    PGC\_INTERNAL,

    PGC\_POSTMASTER,

    PGC\_SIGHUP,

    PGC\_BACKEND,

    PGC\_SUSET,

    PGC\_USERSET

} GucContext;

 

typedef enum

{

    PGC\_S\_DEFAULT,              /* wired-in default \*/

    PGC\_S\_ENV\_VAR,              /* postmaster environment variable \*/

    PGC\_S\_FILE,                 /* postgresql.conf \*/

    PGC\_S\_ARGV,                 /* postmaster command line \*/

    PGC\_S\_DATABASE,             /* per-database setting \*/

    PGC\_S\_USER,                 /* per-user setting \*/

    PGC\_S\_CLIENT,               /* from client connection request \*/

    PGC\_S\_OVERRIDE,             /* special case to forcibly set default \*/

    PGC\_S\_INTERACTIVE,          /* dividing line for error reporting \*/

    PGC\_S\_TEST,                 /* test per-database or per-user setting \*/

    PGC\_S\_SESSION               /* SET command \*/

} GucSource