15.7. Замечания по отдельным платформам

В этом разделе приведены дополнительные замечания по отдельным платформам, связанные с установкой и подготовкой к работе PostgreSQL. Обязательно изучите ещё инструкции по установке, и в частности Раздел 15.2. Также обратитесь к Главе 30, где рассказывается, как прочитать результаты регрессионных тестов.

Если какие-то платформы здесь не упоминаются, значит каких-либо известных особенностей установки в них нет.

15.7.1. AIX

PostgreSQL работает в AIX, но установить его правильно может быть непростой задачей. Поддерживаемыми считаются версии AIX с 4.3.3 до 6.1. Для сборки вы можете применить GCC или собственный компилятор IBM xlc. Вообще говоря, полезно использовать последние версии AIX и PostgreSQL. Получить актуальную информацию о версиях AIX, работа в которых проверена на данный момент, можно на сайте фермы сборки.

Минимальные рекомендуемые уровни исправлений для поддерживаемых версий AIX:

AIX 4.3.3

Эксплуатационный уровень (ML) 11 + пакет исправлений после ML11

AIX 5.1

Эксплуатационный уровень (ML) 9 + пакет исправлений после ML9

AIX 5.2

Технологический уровень (TL) 10, Пакет обновлений (SP) 3

AIX 5.3

Технологический уровень (TL) 7

AIX 6.1

Базовый уровень

Чтобы проверить ваш текущий уровень исправлений, выполните oslevel -r в AIX версии с 4.3.3 по 5.2 ML 7, либо oslevel -s в более поздних версиях.

Если Readline или libz у вас установлены не в /usr/local, передайте configure следующие ключи в дополнение к вашим: --with-includes=/usr/local/include --with-libraries=/usr/local/lib.

15.7.1.1. Особенности использования GCC

В AIX 5.3 наблюдались проблемы с компиляцией и запуском PostgreSQL с использованием GCC.

Для успешной сборки вам потребуется GCC версии новее 3.3.2, особенно, если вы используете версию из системного пакета. Мы добивались успеха с 4.0.1. Проблемы с предыдущими версиями, судя по всему, были связаны больше с тем, как IBM упаковала GCC, а не собственно с GCC, поэтому если вы скомпилируете GCC самостоятельно, положительный исход возможен и с ранней версией GCC.

15.7.1.2. Неработающие доменные сокеты Unix

В AIX 5.3 была проблема с размером структуры sockaddr_storage. В версии 5.3 IBM увеличила размер sockaddr_un, структуры адреса для доменных сокетов Unix, но не увеличила соответственно размер sockaddr_storage. В итоге при попытке PostgreSQL использовать доменные сокеты Unix происходило переполнение этой структуры в libpq. Подключение через TCP/IP устанавливается корректно, а через доменные сокеты Unix — нет, и в результате регрессионные тесты не проходят.

Об этой проблеме было сообщено IBM, она зафиксирована в отчёте об ошибке PMR29657. Если вы обновите систему до эксплуатационного уровня 5300-03 или новее, она получит соответствующее исправление. В качестве временного решения можно присвоить _SS_MAXSIZE значение 1025 в /usr/include/sys/socket.h. В любом случае, после исправления этого заголовочного файла перекомпилируйте PostgreSQL.

15.7.1.3. Проблемы с сетевыми адресами

PostgreSQL пользуется системной функцией getaddrinfo для разбора IP-адресов, указанных в параметре listen_addresses, файле pg_hba.conf и т. д. В старых версиях AIX эта функция работала некорректно. Если вы столкнулись с проблемами в этой области, обновление до уровня исправлений AIX, обозначенного выше, должно решить их.

Один пользователь сообщает:

Используя PostgreSQL версии 8.1 в AIX 5.3, мы периодически сталкивались с тем, что сборщик статистики "загадочным образом" не запускается. Кажется, это результат незапланированного поведения реализации IPv6. Похоже, что PostgreSQL и IPv6 не дружат в AIX 5.3.

Для "решения" проблемы можно выполнить одно из следующих действий.

  • Удалите адрес IPv6 для localhost:

    (от имени root)
    # ifconfig lo0 inet6 ::1/0 delete

  • Удалите IPv6 из сетевых сервисов. Файл /etc/netsvc.conf в AIX примерно соответствует файлу /etc/nsswitch.conf в Solaris/Linux. По умолчанию в AIX он выглядит так:

    hosts=local,bind

    Чтобы отключить поиск адресов IPv6, замените его содержимое следующим:

    hosts=local4,bind4

Внимание

К этим временным решениям приходилось прибегать из-за проблем, связанных с сырой реализацией IPv6, которая заметно улучшилась в последующих выпусках AIX 5.3. Эти решения работали в AIX версии 5.3, но они конечно далеки от идеальных. Кроме того, сообщалось, что они не только не требуются, но и приводят к другим проблемам в AIX 6.1, где поддержка IPv6 стала более зрелой.

15.7.1.4. Управление памятью

Иногда управление памятью в AIX может работать несколько странно. В системе может быть свободно несколько гигабайт ОЗУ, но при запуске приложений всё равно возможны ошибки, связанные с адресным пространством или нехваткой памяти. Например, необычную ошибку может выдать команда createlang. При запуске от имени владельца инсталляции PostgreSQL:

-bash-3.00$ createlang plperl template1
createlang: language installation failed: ERROR:  could not load library "/opt/dbs/pgsql748/lib/plperl.so": A memory address is not in the address space for the process.

(createlang: установить язык не удалось: ОШИБКА: не удалось загрузить библиотеку "/opt/dbs/pgsql748/lib/plperl.so": Адрес памяти находится не в адресном пространстве процесса.) При запуске от имени не владельца, а члена группы-владельца инсталляции PostgreSQL:

-bash-3.00$ createlang plperl template1
createlang: language installation failed: ERROR:  could not load library "/opt/dbs/pgsql748/lib/plperl.so": Bad address

(createlang: установить язык не удалось: ОШИБКА: не удалось загрузить библиотеку "/opt/dbs/pgsql748/lib/plperl.so": Неверный адрес) Также сообщения о нехватке памяти могут появляться в журнале PostgreSQL при попытке выделить блок памяти размером около 256 МиБ или больше.

Общая причина всех этих проблем связана с битностью и моделью памяти серверного процесса. По умолчанию все исполняемые файлы для AIX собираются как 32-битные, вне зависимости от того, какой тип оборудования или ядра используется. Такие 32-битные процессы ограничиваются общим пространством в 4 ГиБ, разделённым на сегменты по 256 МиБ, по одной из нескольких моделей. По умолчанию в куче можно выделить меньше 256 МиБ, так как она разделяет один сегмент со стеком.

В ситуации с показанным выше примером createlang, проверьте umask и разрешения, назначенные для двоичных файлов в вашей инсталляции PostgreSQL. Задействованные в данном примере двоичные файлы были 32-битными и установились с режимом 750 вместо 755. Из-за таких разрешений только владелец или член группы-владельца могли загрузить требуемую библиотеку. Так как она недоступна для чтения всеми, загрузчик помещал этот объект в область кучи процесса, а не в сегменты разделяемых библиотек, где он должен находиться.

В "идеале" эту проблему можно решить, если использовать 64-битную сборку PostgreSQL, но это не всегда практично, так как с 32-битным процессором нельзя будет запустить 64-битный код (можно только собрать).

При желании использовать 32-битную версию сервера установите в LDR_CNTRL значение MAXDATA=0xn0000000, где 1 <= n <= 8, до запуска PostgreSQL, и попробуйте подобрать подходящее значение и параметры postgresql.conf. Переменная окружения LDR_CNTRL говорит AIX, что вы хотите, чтобы сервер получил MAXDATA байт для области кучи, в сегментах по 256 МиБ. Подобрав рабочее значение, можно воспользоваться ldedit и модифицировать двоичные файлы, чтобы они использовали такой размер кучи по умолчанию. Тот же эффект можно получить, пересобрав PostgreSQL с указанием configure LDFLAGS="-Wl,-bmaxdata:0xn0000000".

Для 64-битной сборки определите переменную OBJECT_MODE со значением 64 и передайте configure указания CC="gcc -maix64" и LDFLAGS="-Wl,-bbigtoc". (Для xlc параметры могут быть другими.) Если нужное значение OBJECT_MODE не будет экспортировано, при сборке могут произойти ошибки на стадии компоновки. Когда переменная OBJECT_MODE установлена, она говорит сборочным утилитам AIX, таким как ar, as и ld, какие типы объектов обрабатывать по умолчанию.

По умолчанию система может чрезмерно выделять память в пространстве подкачки. Хотя нам не приходилось с этим сталкиваться, AIX уничтожает процессы при попытке обращения к чрезмерно выделенной памяти, когда её фактически не хватает. Наиболее близкое, что мы наблюдали, была ошибка порождения процесса из-за того, что система решала, что для него не хватает памяти. Как и многие другие компоненты AIX, механизмы распределения пространства подкачки и уничтожения процессов при нехватке памяти можно настроить на уровне системы или процесса, если возникают подобные проблемы.

Ссылки и ресурсы

" Large Program Support ", Документация AIX: Общие концепции программирования: Написание и отладка программ.

" Program Address Space Overview ", Документация AIX: Общие концепции программирования: Написание и отладка программ.

" Performance Overview of the Virtual Memory Manager (VMM) ", Документация AIX: Руководство по управлению производительностью.

" Page Space Allocation ", Документация AIX: Руководство по управлению производительностью.

" Paging-space thresholds tuning ", Документация AIX: Руководство по управлению производительностью.

15.7.2. Cygwin

PostgreSQL можно собрать с применением Cygwin, Linux-подобной среды для Windows, но сейчас этому методу предпочитается обычная сборка в Windows (см. Главу 16), и запускать сервер в среде Cygwin более не рекомендуется.

Выполняя сборку, следуйте обычной процедуре установки (т. е., ./configure; make; и т. д.), с учётом следующих особенностей Cygwin:

  • Настройте путь поиска так, чтобы каталог bin в Cygwin стоял перед каталогами утилит Windows. Это поможет избавиться от проблем при компиляции.

  • Команда adduser не поддерживается; воспользуйтесь соответствующим средством управления пользователями для Windows NT, 2000 или XP. Либо просто пропустите этот шаг.

  • Команда su не поддерживается; для эмуляции su в Windows NT, 2000 или XP воспользуйтесь ssh. Либо пропустите этот шаг.

  • OpenSSL не поддерживается.

  • Запустите cygserver для поддержки разделяемой памяти. Для этого введите команду /usr/sbin/cygserver &. Эта программа должна работать всегда при запуске сервера PostgreSQL или инициализации кластера баз данных (initdb). Возможно, вам придётся настроить конфигурацию cygserver (например, увеличить SEMMNS), чтобы PostgreSQL мог получить требуемые системные ресурсы.

  • Сборка может завершиться ошибкой в некоторых системах, где используется локаль, отличная от C. Чтобы исправить это, выберите локаль C, выполнив export LANG=C.utf8 до сборки, а затем восстановите предыдущее значение после установки PostgreSQL.

  • Параллельные регрессионные тесты (make check) могут выдавать ложные ошибки тестирования при переполнении очереди listen(), из-за чего подключения могут не устанавливаться или зависать. Вы можете ограничить число подключений, определив переменную make MAX_CONNECTIONS так:

    make MAX_CONNECTIONS=5 check

    (В некоторых системах поддерживается до 10 одновременных подключений).

Сервер PostgreSQL и cygserver можно запустить в виде служб Windows NT. Как это сделать, рассказывается в описании README, включённом в двоичный пакет PostgreSQL для Cygwin. Оно устанавливается в каталог /usr/share/doc/Cygwin.

15.7.3. HP-UX

PostgreSQL 7.3+ должен работать на машинах Series 700/800 PA-RISC под управлением HP-UX 10.X или 11.X, с подходящими уровнями системных исправлений и средствами сборки. Как минимум один разработчик регулярно тестирует сборку в HP-UX 10.20, и мы получали сообщения об успешных установках в HP-UX 11.00 и 11.11.

Помимо пакета исходного кода PostgreSQL, вам потребуется GNU make (HP make не подойдёт) и GCC или полный компилятор ANSI C от HP. Если вы намерены выполнить сборку не из дистрибутивного пакета исходного кода, а из Git, вам также потребуется Flex (GNU lex) и Bison (GNU yacc). Мы также рекомендуем убедиться, что у вас установлены довольно свежие исправления HP. Для сборки 64-битного кода в HP-UX 11.11 вам потребуется PHSS_30966 (11.11) или более новое исправление, без него initdb может зависать:

PHSS_30966  s700_800 Накопительное исправление ld(1) и утилит компоновки. Как правило, для сборки нужно иметь текущие исправления libc и ld/dld, а также компилятора (если вы используете компилятор HP). Получить эти исправления можно на сайтах поддержки HP http://itrc.hp.com и ftp://us-ffs.external.hp.com/.

Если вы проводите сборку на машине PA-RISC 2.0 и хотите получить 64-битный исполняемый код, вы должны использовать 64-битную версию GCC. Скомпилированный GCC для HP-UX PA-RISC и Itanium доступен по адресу http://www.hp.com/go/gcc. Не забудьте также загрузить и установить binutils.

Если вы проводите сборку на машине PA-RISC 2.0 и хотите, чтобы скомпилированный код запускался на машинах PA-RISC 1.1, также потребуется указать +DAportable в CFLAGS.

Если вы проводите сборку на машине HP-UX Itanium, вам потребуется последний компилятор ANSI C от HP с соответствующим исправлением или более новыми:

PHSS_30848  s700_800 Компилятор HP С (A.05.57)
PHSS_30849  s700_800 Исправление библиотеки u2comp/be/plugin

Если вы используете компилятор HP C и GCC, может потребоваться явно выбрать предпочитаемый компилятор при запуске configure:

./configure CC=cc

для использования компилятора C от HP, либо

./configure CC=gcc

для выбора GCC. При отсутствии явного указания configure выберет gcc, если есть такая возможность.

По умолчанию целевой каталог установки — /usr/local/pgsql, но вы, возможно, захотите его изменить на другой, внутри /opt. В этом случае передайте его configure с ключом --prefix.

В регрессионных тестах возможны отклонения при геометрических проверках, в наименее значащих цифрах, в зависимости от применяемого компилятора и математической библиотеки. Любые другие ошибки заслуживают внимания.

15.7.4. MinGW/Собственная сборка Windows

PostgreSQL для Windows можно собрать с использованием MinGW, Unix-подобной среды сборки для операционных систем Microsoft, либо используя набор средств разработки Microsoft Visual C++. При использовании MinGW применяется обычная система сборки, описанная в этой главе; сборка Visual C++ выполняется по-другому, как описано в Главе 16. Это полностью естественная сборка для Windows, для которой не требуется дополнительное ПО вроде MinGW. Готовый инсталлятор для Windows можно найти на сайте PostgreSQL.

PostgreSQL, портированный в Windows, будет работать в 32- или 64-битной версии Windows 2000 или новее. В предыдущих операционных системах нет достаточной инфраструктуры (но там можно использовать Cygwin). MinGW, Unix-подобные средства сборки, и MSYS, набор утилит Unix, требуемых для исполнения скриптов типа configure, можно загрузить с сайта http://www.mingw.org/. Эти дополнительные программы нужны только для сборки, для запуска полученных исполняемых файлов они не требуются.

Чтобы собрать 64-битную версию с использованием MinGW, установите набор 64-битных утилит с http://mingw-w64.sourceforge.net/, добавьте путь к его каталогу bin в PATH и запустите configure с параметром --host=x86_64-w64-mingw.

Когда вы всё установите, запускать psql предлагается из CMD.EXE, так как в консоли MSYS есть проблемы с буферизацией.

15.7.4.1. Сбор аварийных дампов в Windows

В случае аварии PostgreSQL в Windows он может сгенерировать минидамп памяти, который помогает выяснить причину аварии, подобно дампам памяти в Unix. Проанализировать эти дампы можно, используя Windows Debugger Tools (Средства отладки Windows) или Visual Studio. Чтобы в Windows получить дамп в случае аварии, создайте подкаталог crashdumps в каталоге данных кластера. Дампы будут записываться в этот каталог с уникальным именем, составленным из идентификатора процесса, давшего сбой, и времени сбоя.

15.7.5. SCO OpenServer и SCO UnixWare

PostgreSQL можно собрать в SCO UnixWare 7 и SCO OpenServer 5. В OpenServer для сборки можно использовать либо Инструменты разработки OpenServer (OpenServer Development Kit), либо Универсальные средства разработки (Universal Development Kit). Возможно, при этом потребуется выполнить дополнительные действия, как описано ниже.

15.7.5.1. Skunkware

Вы должны найти свою копию SCO Skunkware CD. Skunkware CD поставлялся с UnixWare 7 и текущими версиями OpenServer 5. В набор Skunkware входят готовые к установке версии многих популярных программ, доступных в Интернете. В частности, в него входят gzip, gunzip, GNU Make, Flex и Bison. Для UnixWare 7.1 этот CD называется "Open License Software Supplement" (Дополнительное ПО с открытыми лицензиями). Если у вас нет такого CD, это ПО можно найти на сайте http://www.sco.com/skunkware/.

Версии Skunkware для UnixWare и OpenServer различаются. Убедитесь, что вы устанавливаете правильную версию для вашей ОС, но учтите следующие замечания.

В UnixWare 7.1.3 и новее компилятор GCC поставляется на UDK CD, вместе с GNU Make.

15.7.5.2. GNU Make

Вам потребуется программа GNU Make, которая находится на Skunkware CD. По умолчанию она устанавливается в /usr/local/bin/make.

В UnixWare 7.1.3 и новее программа GNU Make включена в раздел OSTK диска UDK и устанавливается в /usr/gnu/bin/gmake.

15.7.5.3. Readline

Библиотека Readline поставляется на Skunkware CD, но она не включена в Skunkware CD для UnixWare 7.1. Если у вас есть Skunkware CD для UnixWare 7.0.0 или 7.0.1, вы можете установить её с этого диска. В противном случае, обратитесь к http://www.sco.com/skunkware/.

По умолчанию Readline устанавливается в /usr/local/lib и /usr/local/include. Однако configure для PostgreSQL не сможет найти её там без дополнительной помощи. Поэтому, если вы установили Readline, передайте configure следующие параметры:

./configure --with-libraries=/usr/local/lib --with-includes=/usr/local/include

15.7.5.4. Использование UDK в OpenServer

Если вы используете новый компилятор из Универсальных средств разработки (UDK, Universal Development Kit) в OpenServer, вам потребуется задать размещение библиотек UDK:

./configure --with-libraries=/udk/usr/lib --with-includes=/udk/usr/include

Совместите эти параметры с заданными выше для Readline:

./configure --with-libraries="/udk/usr/lib /usr/local/lib" --with-includes="/udk/usr/include /usr/local/include"

15.7.5.5. Получение справки man по PostgreSQL

По умолчанию страницы man для PostgreSQL устанавливаются в /usr/local/pgsql/man. Но UnixWare по умолчанию не ищет там эти страницы. Чтобы вы могли обращаться к ним, потребуется изменить переменную MANPATH в /etc/default/man, например так:

MANPATH=/usr/lib/scohelp/%L/man:/usr/dt/man:/usr/man:/usr/share/man:scohelp:/usr/local/man:/usr/local/pgsql/man

В OpenServer необходимо провести дополнительные исследования, чтобы справкой man можно было пользоваться, потому что в этой системе man работает немного не так, как в других. В настоящее время PostgreSQL просто не устанавливает справочные страницы в ней.

15.7.5.6. Проблемы C99 с функциональным дополнением 7.1.1b

Для компиляторов, более ранних, чем выпущенный с OpenUNIX 8.0.0 (UnixWare 7.1.2), в том числе с функциональным дополнением 7.1.1b, может потребоваться указать -Xb в переменной окружения CC или CFLAGS. Признаком этой проблемы будет ошибка при компиляции tuplesort.c в коде, ссылающемся на встроенные функции. Судя по всему, соответствующее исправление включено в компилятор версии 7.1.2(8.0.0) и новее.

15.7.5.7. Многопоточность в UnixWare

Для использования многопоточности вы должны добавлять указание -Kpthread при компиляции всех программ на базе libpq. Библиотека libpq вызывает функции pthread_*, которые доступны только при компиляции с флагом -Kpthread/-Kthread.

15.7.6. Solaris

PostgreSQL хорошо поддерживается в Solaris. Чем новее операционная система, тем меньше затруднений будет; подробнее об этом ниже.

15.7.6.1. Требуемые инструменты

Вы можете выполнить сборку с GCC или с набором компиляторов Sun. Для лучшей оптимизации кода на архитектуре SPARC настоятельно рекомендуется использовать компилятор Sun. Мы слышали о проблемах с GCC 2.95.1, поэтому рекомендуется использовать GCC 2.95.3 или новее. Если вы решили применить компилятор Sun, не выберите по ошибке /usr/ucb/cc; правильный путь — /opt/SUNWspro/bin/cc.

Sun Studio вы можете загрузить с сайта http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/. Средства GNU по большей части интегрированы в Solaris 10, либо представлены на сопутствующем CD. Если вам нужны пакеты для старых версий Solaris, вы можете найти их на сайте http://www.sunfreeware.com. Если вы предпочитаете исходный код, обратитесь к http://www.gnu.org/order/ftp.html.

15.7.6.2. Проблемы с OpenSSL

Собирая PostgreSQL с поддержкой OpenSSL, вы можете получить ошибки компиляции в следующих файлах:

  • src/backend/libpq/crypt.c

  • src/backend/libpq/password.c

  • src/interfaces/libpq/fe-auth.c

  • src/interfaces/libpq/fe-connect.c

Это вызвано конфликтом имён между стандартным /usr/include/crypt.h и заголовочными файлами в составе OpenSSL.

Эту проблему можно решить, обновив инсталляцию OpenSSL до версии 0.9.6a. Solaris 9 и новее уже включает обновлённую версию OpenSSL.

15.7.6.3. Процедура configure сообщает о сбое тестовой программы

Если configure сообщает о сбое тестовой программы, это может быть вызвано тем, что при связывании во время выполнения не удаётся найти некоторую библиотеку, вероятно, libz, libreadline или какую-то другую нестандартную, например, libssl. Чтобы указать правильное размещение библиотеки, задайте переменную окружения LDFLAGS в командной строке configure, например так:

configure ... LDFLAGS="-R /usr/sfw/lib:/opt/sfw/lib:/usr/local/lib"

За дополнительными сведениями обратитесь к странице man ld.

15.7.6.4. Периодические сбои 64-битной сборки

В Solaris 7 и старее 64-битная версия libc содержала бракованную функцию vsnprintf, которая могла вызывать непредсказуемые сбои PostgreSQL. Самое простое известное решение — сделать, чтобы PostgreSQL использовал собственную версию vsnprintf вместо библиотечной версии. Для этого, выполнив configure, отредактируйте полученный в результате configure файл. В src/Makefile.global поменяйте строку

LIBOBJS =

на такую

LIBOBJS = snprintf.o

(В этой переменной уже также могут быть перечислены и другие файлы.) Затем продолжите сборку как обычно.

15.7.6.5. Компиляция для максимальной производительности

Для архитектуры SPARC настоятельно рекомендуется проводить компиляцию с использованием Sun Studio. Добавив флаг -xO5, вы можете получить исполняемый код, который будет работать значительно быстрее. Но не добавляйте никакие флаги, влияющие на вычисления с плавающей точкой или обработку errno (например, -fast). С такими флагами PostgreSQL может вести себя нестандартно, например, выполняя операции с датами/временем.

Если у вас нет причины использовать 64-битные программы в архитектуре SPARC, собирайте 32-битную версию, так как 64-битные операции, а значит и 64-битные программы, выполняются медленнее 32-битных. С другой стороны, 32-битный код для процессоров семейства AMD64 не является «родным», поэтому на таких процессорах значительно медленнее работает 32-битный код.

15.7.6.6. Применение DTrace для трассировки PostgreSQL

Да, вы можете использовать DTrace. За дополнительными сведениями обратитесь к Разделу 27.4. Другую полезную информацию можно найти в этой статье: https://blogs.oracle.com/robertlor/entry/user_level_dtrace_probes_in.

Если компоновка исполняемого файла postgres прерывается с таким сообщением об ошибке:

Undefined                       first referenced
 symbol                             in file
AbortTransaction                    utils/probes.o
CommitTransaction                   utils/probes.o
ld: fatal: Symbol referencing errors. No output written to postgres
collect2: ld returned 1 exit status
make: *** [postgres] Error 1

Это означает, что ваша инсталляция DTrace слишком стара и неспособна работать с пробами в статических функциях. В этом случае вам нужна версия Solaris 10u4 или новее.

15.7. Platform-specific Notes

This section documents additional platform-specific issues regarding the installation and setup of PostgreSQL. Be sure to read the installation instructions, and in particular Section 15.2 as well. Also, check Chapter 30 regarding the interpretation of regression test results.

Platforms that are not covered here have no known platform-specific installation issues.

15.7.1. AIX

PostgreSQL works on AIX, but getting it installed properly can be challenging. AIX versions from 4.3.3 to 6.1 are considered supported. You can use GCC or the native IBM compiler xlc. In general, using recent versions of AIX and PostgreSQL helps. Check the build farm for up to date information about which versions of AIX are known to work.

The minimum recommended fix levels for supported AIX versions are:

AIX 4.3.3

Maintenance Level 11 + post ML11 bundle

AIX 5.1

Maintenance Level 9 + post ML9 bundle

AIX 5.2

Technology Level 10 Service Pack 3

AIX 5.3

Technology Level 7

AIX 6.1

Base Level

To check your current fix level, use oslevel -r in AIX 4.3.3 to AIX 5.2 ML 7, or oslevel -s in later versions.

Use the following configure flags in addition to your own if you have installed Readline or libz in /usr/local: --with-includes=/usr/local/include --with-libraries=/usr/local/lib.

15.7.1.1. GCC Issues

On AIX 5.3, there have been some problems getting PostgreSQL to compile and run using GCC.

You will want to use a version of GCC subsequent to 3.3.2, particularly if you use a prepackaged version. We had good success with 4.0.1. Problems with earlier versions seem to have more to do with the way IBM packaged GCC than with actual issues with GCC, so that if you compile GCC yourself, you might well have success with an earlier version of GCC.

15.7.1.2. Unix-Domain Sockets Broken

AIX 5.3 has a problem where sockaddr_storage is not defined to be large enough. In version 5.3, IBM increased the size of sockaddr_un, the address structure for Unix-domain sockets, but did not correspondingly increase the size of sockaddr_storage. The result of this is that attempts to use Unix-domain sockets with PostgreSQL lead to libpq overflowing the data structure. TCP/IP connections work OK, but not Unix-domain sockets, which prevents the regression tests from working.

The problem was reported to IBM, and is recorded as bug report PMR29657. If you upgrade to maintenance level 5300-03 or later, that will include this fix. A quick workaround is to alter _SS_MAXSIZE to 1025 in /usr/include/sys/socket.h. In either case, recompile PostgreSQL once you have the corrected header file.

15.7.1.3. Internet Address Issues

PostgreSQL relies on the system's getaddrinfo function to parse IP addresses in listen_addresses, pg_hba.conf, etc. Older versions of AIX have assorted bugs in this function. If you have problems related to these settings, updating to the appropriate AIX fix level shown above should take care of it.

One user reports:

When implementing PostgreSQL version 8.1 on AIX 5.3, we periodically ran into problems where the statistics collector would "mysteriously" not come up successfully. This appears to be the result of unexpected behavior in the IPv6 implementation. It looks like PostgreSQL and IPv6 do not play very well together on AIX 5.3.

Any of the following actions "fix" the problem.

  • Delete the IPv6 address for localhost:

    (as root)
    # ifconfig lo0 inet6 ::1/0 delete

  • Remove IPv6 from net services. The file /etc/netsvc.conf on AIX is roughly equivalent to /etc/nsswitch.conf on Solaris/Linux. The default, on AIX, is thus:

    hosts=local,bind

    Replace this with:

    hosts=local4,bind4

    to deactivate searching for IPv6 addresses.

Warning

This is really a workaround for problems relating to immaturity of IPv6 support, which improved visibly during the course of AIX 5.3 releases. It has worked with AIX version 5.3, but does not represent an elegant solution to the problem. It has been reported that this workaround is not only unnecessary, but causes problems on AIX 6.1, where IPv6 support has become more mature.

15.7.1.4. Memory Management

AIX can be somewhat peculiar with regards to the way it does memory management. You can have a server with many multiples of gigabytes of RAM free, but still get out of memory or address space errors when running applications. One example is createlang failing with unusual errors. For example, running as the owner of the PostgreSQL installation:

-bash-3.00$ createlang plperl template1
createlang: language installation failed: ERROR:  could not load library "/opt/dbs/pgsql748/lib/plperl.so": A memory address is not in the address space for the process.

Running as a non-owner in the group possessing the PostgreSQL installation:

-bash-3.00$ createlang plperl template1
createlang: language installation failed: ERROR:  could not load library "/opt/dbs/pgsql748/lib/plperl.so": Bad address

Another example is out of memory errors in the PostgreSQL server logs, with every memory allocation near or greater than 256 MB failing.

The overall cause of all these problems is the default bittedness and memory model used by the server process. By default, all binaries built on AIX are 32-bit. This does not depend upon hardware type or kernel in use. These 32-bit processes are limited to 4 GB of memory laid out in 256 MB segments using one of a few models. The default allows for less than 256 MB in the heap as it shares a single segment with the stack.

In the case of the createlang example, above, check your umask and the permissions of the binaries in your PostgreSQL installation. The binaries involved in that example were 32-bit and installed as mode 750 instead of 755. Due to the permissions being set in this fashion, only the owner or a member of the possessing group can load the library. Since it isn't world-readable, the loader places the object into the process' heap instead of the shared library segments where it would otherwise be placed.

The "ideal" solution for this is to use a 64-bit build of PostgreSQL, but that is not always practical, because systems with 32-bit processors can build, but not run, 64-bit binaries.

If a 32-bit binary is desired, set LDR_CNTRL to MAXDATA=0xn0000000, where 1 <= n <= 8, before starting the PostgreSQL server, and try different values and postgresql.conf settings to find a configuration that works satisfactorily. This use of LDR_CNTRL tells AIX that you want the server to have MAXDATA bytes set aside for the heap, allocated in 256 MB segments. When you find a workable configuration, ldedit can be used to modify the binaries so that they default to using the desired heap size. PostgreSQL can also be rebuilt, passing configure LDFLAGS="-Wl,-bmaxdata:0xn0000000" to achieve the same effect.

For a 64-bit build, set OBJECT_MODE to 64 and pass CC="gcc -maix64" and LDFLAGS="-Wl,-bbigtoc" to configure. (Options for xlc might differ.) If you omit the export of OBJECT_MODE, your build may fail with linker errors. When OBJECT_MODE is set, it tells AIX's build utilities such as ar, as, and ld what type of objects to default to handling.

By default, overcommit of paging space can happen. While we have not seen this occur, AIX will kill processes when it runs out of memory and the overcommit is accessed. The closest to this that we have seen is fork failing because the system decided that there was not enough memory for another process. Like many other parts of AIX, the paging space allocation method and out-of-memory kill is configurable on a system- or process-wide basis if this becomes a problem.

References and Resources

"Large Program Support", AIX Documentation: General Programming Concepts: Writing and Debugging Programs.

"Program Address Space Overview", AIX Documentation: General Programming Concepts: Writing and Debugging Programs.

"Performance Overview of the Virtual Memory Manager (VMM)", AIX Documentation: Performance Management Guide.

"Page Space Allocation", AIX Documentation: Performance Management Guide.

"Paging-space thresholds tuning", AIX Documentation: Performance Management Guide.

15.7.2. Cygwin

PostgreSQL can be built using Cygwin, a Linux-like environment for Windows, but that method is inferior to the native Windows build (see Chapter 16) and running a server under Cygwin is no longer recommended.

When building from source, proceed according to the normal installation procedure (i.e., ./configure; make; etc.), noting the following-Cygwin specific differences:

  • Set your path to use the Cygwin bin directory before the Windows utilities. This will help prevent problems with compilation.

  • The adduser command is not supported; use the appropriate user management application on Windows NT, 2000, or XP. Otherwise, skip this step.

  • The su command is not supported; use ssh to simulate su on Windows NT, 2000, or XP. Otherwise, skip this step.

  • OpenSSL is not supported.

  • Start cygserver for shared memory support. To do this, enter the command /usr/sbin/cygserver &. This program needs to be running anytime you start the PostgreSQL server or initialize a database cluster (initdb). The default cygserver configuration may need to be changed (e.g., increase SEMMNS) to prevent PostgreSQL from failing due to a lack of system resources.

  • Building might fail on some systems where a locale other than C is in use. To fix this, set the locale to C by doing export LANG=C.utf8 before building, and then setting it back to the previous setting, after you have installed PostgreSQL.

  • The parallel regression tests (make check) can generate spurious regression test failures due to overflowing the listen() backlog queue which causes connection refused errors or hangs. You can limit the number of connections using the make variable MAX_CONNECTIONS thus:

    make MAX_CONNECTIONS=5 check

    (On some systems you can have up to about 10 simultaneous connections).

It is possible to install cygserver and the PostgreSQL server as Windows NT services. For information on how to do this, please refer to the README document included with the PostgreSQL binary package on Cygwin. It is installed in the directory /usr/share/doc/Cygwin.

15.7.3. HP-UX

PostgreSQL 7.3+ should work on Series 700/800 PA-RISC machines running HP-UX 10.X or 11.X, given appropriate system patch levels and build tools. At least one developer routinely tests on HP-UX 10.20, and we have reports of successful installations on HP-UX 11.00 and 11.11.

Aside from the PostgreSQL source distribution, you will need GNU make (HP's make will not do), and either GCC or HP's full ANSI C compiler. If you intend to build from Git sources rather than a distribution tarball, you will also need Flex (GNU lex) and Bison (GNU yacc). We also recommend making sure you are fairly up-to-date on HP patches. At a minimum, if you are building 64 bit binaries on HP-UX 11.11 you may need PHSS_30966 (11.11) or a successor patch otherwise initdb may hang:

PHSS_30966  s700_800 ld(1) and linker tools cumulative patch On general principles you should be current on libc and ld/dld patches, as well as compiler patches if you are using HP's C compiler. See HP's support sites such as http://itrc.hp.com and ftp://us-ffs.external.hp.com/ for free copies of their latest patches.

If you are building on a PA-RISC 2.0 machine and want to have 64-bit binaries using GCC, you must use GCC 64-bit version. GCC binaries for HP-UX PA-RISC and Itanium are available from http://www.hp.com/go/gcc. Don't forget to get and install binutils at the same time.

If you are building on a PA-RISC 2.0 machine and want the compiled binaries to run on PA-RISC 1.1 machines you will need to specify +DAportable in CFLAGS.

If you are building on a HP-UX Itanium machine, you will need the latest HP ANSI C compiler with its dependent patch or successor patches:

PHSS_30848  s700_800 HP C Compiler (A.05.57)
PHSS_30849  s700_800 u2comp/be/plugin library Patch

If you have both HP's C compiler and GCC's, then you might want to explicitly select the compiler to use when you run configure:

./configure CC=cc

for HP's C compiler, or

./configure CC=gcc

for GCC. If you omit this setting, then configure will pick gcc if it has a choice.

The default install target location is /usr/local/pgsql, which you might want to change to something under /opt. If so, use the --prefix switch to configure.

In the regression tests, there might be some low-order-digit differences in the geometry tests, which vary depending on which compiler and math library versions you use. Any other error is cause for suspicion.

15.7.4. MinGW/Native Windows

PostgreSQL for Windows can be built using MinGW, a Unix-like build environment for Microsoft operating systems, or using Microsoft's Visual C++ compiler suite. The MinGW build variant uses the normal build system described in this chapter; the Visual C++ build works completely differently and is described in Chapter 16. It is a fully native build and uses no additional software like MinGW. A ready-made installer is available on the main PostgreSQL web site.

The native Windows port requires a 32 or 64-bit version of Windows 2000 or later. Earlier operating systems do not have sufficient infrastructure (but Cygwin may be used on those). MinGW, the Unix-like build tools, and MSYS, a collection of Unix tools required to run shell scripts like configure, can be downloaded from http://www.mingw.org/. Neither is required to run the resulting binaries; they are needed only for creating the binaries.

To build 64 bit binaries using MinGW, install the 64 bit tool set from http://mingw-w64.sourceforge.net/, put its bin directory in the PATH, and run configure with the --host=x86_64-w64-mingw option.

After you have everything installed, it is suggested that you run psql under CMD.EXE, as the MSYS console has buffering issues.

15.7.4.1. Collecting Crash Dumps on Windows

If PostgreSQL on Windows crashes, it has the ability to generate minidumps that can be used to track down the cause for the crash, similar to core dumps on Unix. These dumps can be read using the Windows Debugger Tools or using Visual Studio. To enable the generation of dumps on Windows, create a subdirectory named crashdumps inside the cluster data directory. The dumps will then be written into this directory with a unique name based on the identifier of the crashing process and the current time of the crash.

15.7.5. SCO OpenServer and SCO UnixWare

PostgreSQL can be built on SCO UnixWare 7 and SCO OpenServer 5. On OpenServer, you can use either the OpenServer Development Kit or the Universal Development Kit. However, some tweaking may be needed, as described below.

15.7.5.1. Skunkware

You should locate your copy of the SCO Skunkware CD. The Skunkware CD is included with UnixWare 7 and current versions of OpenServer 5. Skunkware includes ready-to-install versions of many popular programs that are available on the Internet. For example, gzip, gunzip, GNU Make, Flex, and Bison are all included. For UnixWare 7.1, this CD is now labeled "Open License Software Supplement". If you do not have this CD, the software on it is available from http://www.sco.com/skunkware/.

Skunkware has different versions for UnixWare and OpenServer. Make sure you install the correct version for your operating system, except as noted below.

On UnixWare 7.1.3 and beyond, the GCC compiler is included on the UDK CD as is GNU Make.

15.7.5.2. GNU Make

You need to use the GNU Make program, which is on the Skunkware CD. By default, it installs as /usr/local/bin/make.

As of UnixWare 7.1.3 and above, the GNU Make program is the OSTK portion of the UDK CD, and is in /usr/gnu/bin/gmake.

15.7.5.3. Readline

The Readline library is on the Skunkware CD. But it is not included on the UnixWare 7.1 Skunkware CD. If you have the UnixWare 7.0.0 or 7.0.1 Skunkware CDs, you can install it from there. Otherwise, try http://www.sco.com/skunkware/.

By default, Readline installs into /usr/local/lib and /usr/local/include. However, the PostgreSQL configure program will not find it there without help. If you installed Readline, then use the following options to configure:

./configure --with-libraries=/usr/local/lib --with-includes=/usr/local/include

15.7.5.4. Using the UDK on OpenServer

If you are using the new Universal Development Kit (UDK) compiler on OpenServer, you need to specify the locations of the UDK libraries:

./configure --with-libraries=/udk/usr/lib --with-includes=/udk/usr/include

Putting these together with the Readline options from above:

./configure --with-libraries="/udk/usr/lib /usr/local/lib" --with-includes="/udk/usr/include /usr/local/include"

15.7.5.5. Reading the PostgreSQL Man Pages

By default, the PostgreSQL man pages are installed into /usr/local/pgsql/man. By default, UnixWare does not look there for man pages. To be able to read them you need to modify the MANPATH variable in /etc/default/man, for example:

MANPATH=/usr/lib/scohelp/%L/man:/usr/dt/man:/usr/man:/usr/share/man:scohelp:/usr/local/man:/usr/local/pgsql/man

On OpenServer, some extra research needs to be invested to make the man pages usable, because the man system is a bit different from other platforms. Currently, PostgreSQL will not install them at all.

15.7.5.6. C99 Issues with the 7.1.1b Feature Supplement

For compilers earlier than the one released with OpenUNIX 8.0.0 (UnixWare 7.1.2), including the 7.1.1b Feature Supplement, you may need to specify -Xb in CFLAGS or the CC environment variable. The indication of this is an error in compiling tuplesort.c referencing inline functions. Apparently there was a change in the 7.1.2(8.0.0) compiler and beyond.

15.7.5.7. Threading on UnixWare

For threading, youmust use -Kpthread on all libpq-using programs. libpq uses pthread_* calls, which are only available with the -Kpthread/-Kthread flag.

15.7.6. Solaris

PostgreSQL is well-supported on Solaris. The more up to date your operating system, the fewer issues you will experience; details below.

15.7.6.1. Required Tools

You can build with either GCC or Sun's compiler suite. For better code optimization, Sun's compiler is strongly recommended on the SPARC architecture. We have heard reports of problems when using GCC 2.95.1; GCC 2.95.3 or later is recommended. If you are using Sun's compiler, be careful not to select /usr/ucb/cc; use /opt/SUNWspro/bin/cc.

You can download Sun Studio from http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/. Many of GNU tools are integrated into Solaris 10, or they are present on the Solaris companion CD. If you like packages for older version of Solaris, you can find these tools at http://www.sunfreeware.com. If you prefer sources, look at http://www.gnu.org/order/ftp.html.

15.7.6.2. Problems with OpenSSL

When you build PostgreSQL with OpenSSL support you might get compilation errors in the following files:

  • src/backend/libpq/crypt.c

  • src/backend/libpq/password.c

  • src/interfaces/libpq/fe-auth.c

  • src/interfaces/libpq/fe-connect.c

This is because of a namespace conflict between the standard /usr/include/crypt.h header and the header files provided by OpenSSL.

Upgrading your OpenSSL installation to version 0.9.6a fixes this problem. Solaris 9 and above has a newer version of OpenSSL.

15.7.6.3. configure Complains About a Failed Test Program

If configure complains about a failed test program, this is probably a case of the run-time linker being unable to find some library, probably libz, libreadline or some other non-standard library such as libssl. To point it to the right location, set the LDFLAGS environment variable on the configure command line, e.g.,

configure ... LDFLAGS="-R /usr/sfw/lib:/opt/sfw/lib:/usr/local/lib"

See the ld man page for more information.

15.7.6.4. 64-bit Build Sometimes Crashes

On Solaris 7 and older, the 64-bit version of libc has a buggy vsnprintf routine, which leads to erratic core dumps in PostgreSQL. The simplest known workaround is to force PostgreSQL to use its own version of vsnprintf rather than the library copy. To do this, after you run configure edit a file produced by configure: In src/Makefile.global, change the line

LIBOBJS =

to read

LIBOBJS = snprintf.o

(There might be other files already listed in this variable. Order does not matter.) Then build as usual.

15.7.6.5. Compiling for Optimal Performance

On the SPARC architecture, Sun Studio is strongly recommended for compilation. Try using the -xO5 optimization flag to generate significantly faster binaries. Do not use any flags that modify behavior of floating-point operations and errno processing (e.g., -fast). These flags could raise some nonstandard PostgreSQL behavior for example in the date/time computing.

If you do not have a reason to use 64-bit binaries on SPARC, prefer the 32-bit version. The 64-bit operations are slower and 64-bit binaries are slower than the 32-bit variants. And on other hand, 32-bit code on the AMD64 CPU family is not native, and that is why 32-bit code is significant slower on this CPU family.

15.7.6.6. Using DTrace for Tracing PostgreSQL

Yes, using DTrace is possible. See Section 27.4 for further information. You can also find more information in this article: https://blogs.oracle.com/robertlor/entry/user_level_dtrace_probes_in.

If you see the linking of the postgres executable abort with an error message like:

Undefined                       first referenced
 symbol                             in file
AbortTransaction                    utils/probes.o
CommitTransaction                   utils/probes.o
ld: fatal: Symbol referencing errors. No output written to postgres
collect2: ld returned 1 exit status
make: *** [postgres] Error 1

your DTrace installation is too old to handle probes in static functions. You need Solaris 10u4 or newer.

FAQ