Files
MaxScale/server/core/gateway.c
Johan Wikman d115a54038 All changes 1.4.3...2.0.0
b709e29 Fix URL typo in release notes
01f203c Update release notes
c49810a Update COPYRIGHT
e327526 Add BSL version number to LICENSE.TXT
07e3a4e Remove superfluous COPURIGHT.md and LICENSE.md
54c3310 Replace Dynamic Data Routing Platform with Database Proxy
305d02f Remove *.cmake wildcard from .gitignore
b0b5208 Cleanup of spaces
aeca6d0 Extend maxscaled error messages
817d74c Document where the CDC users are stored
9a569db Update license
ff8697a MXS-716: Fix table level privilege detection
2071a8c Only check replies of slaves that are in use
f8dfa42 Fix possible hangs in CDC python scripts
fa1d99e Removed "filestem option" from example
009b549 Removed "filestem option" from example
8d515c2 Add example Kafka producer script for Python
64e976b Fix sporadic SSL authentication failures
5a655dc MXS-814: Check service/monitor permissions on all servers
2a7f596 Add note about galeramon priority to Galera tutorials
b90b5a6 Fixed SHOW SLAVE STATUS in binlog router
e22fe39 Changed couln size for SHOW SLAVE STATUS
ae97b18 Fix avrorouter build failure with older sqlite libraries
56ef8b7 Replace GPL license with BSL license in scripts and tests
552836f Initialize all fields when MySQL users are loaded from cache
bf42947 Update all licensing related files
b29db9d Remove optimize_wildcard parameter from use
5170844 Make readwritesplit diagnosting output more clear
262ffb1 Fix crash when a config parameter has no section
33ac9e6 Add note about LEAST_BEHIND_MASTER and server weights
e13e860 Fix a memory leak when backend authentication fails
75d00c2 MXS-801: Set the default value of strip_db_esc to true
bd5f2db MXS-800: Add a log message about the working directory
4b1dd8c Update MySQL Monitor documentation on detect_replication_lag
559bc99 Fix installation of license file
b057587 Change LICENSE to LICENSE.TXT
223fa43 Remove null characters from log messages
36fd05b Fix fatal signal handler log message
053dc8a Fix typos in documentation
371dc87 Fix Galera text in Master-Slave tutorial
30b6265 Disable adding of new objects at runtime
db92311 Update the documentation on configuration reloading
0923d40 Update Connector-C version
c4738b5 Add define for avro-conversion.ini
196e6ac Update license from GPL to BSL.
e612366 Correctly calculate the number of bytes read in dcb_read
93a2a03 Update rotate documentation in admin tutorial
c5eb854 MXS-585: Fix authentication handling regression
6330070 Fix schemarouter memory leak
aa5827e Fix CDC authentication memory leak
a5af4ad Fix avro memory leaks
627d73f Fix Avro scripts
0ff7556 Add build instructions to avrorouter documentation
734a1c8 Fix doxygen mainpage
e51ce09 Add licence text to avro scripts
4d27c14 Update Avro documentation and fix installation directories
a58a330 Fix readconnroute error message about router_options
22b138c MXS-772: Fix postinstall script
a9960b7 Fix function declaration in mysql_backend.c
cbe1704 Add missing newline
09d76ee Fix avro documentation default values
1d3f8f3 Added refresh users on START SLAVE
880db34 Make router configuration errors fatal
3bad5ca Update documentation and add logging to avrorouter
10f3384 Disable SSLv3
ca8d902 Fix rwsplit error reporting when master is lost
e816d65 Fix MaxScale Tutorial
deca3e1 Update MaxScale man page
f1735b7 Update release notes
9238714 qc: Change type of DEALLOCATE PREPARE
0b77c3b dbfwfilter: Do not require a trailing new line
1152ca9 Remove copyright message
a038a85 Remove debug assertion on ERANGE error in galeramon
12ab235 Fix comparison error for connections limit.
5de1a8f qc_sqlite: Correct string recognition
b63d754 Fix links in documentation contents
05d457e CDC protocol link fix
50676ef Fix monitor code formatting
218ba09 Remove MaxScale-and-SSL.md
0d6845b Add images to Avro documentation and tutorial
8dd2c9b Update MaxScale-2.0.0-Release-Notes.md
6d4b593 Change avrorouter default transaction grouping
4c629de Add notes about monitor changes to upgrading and release notes
267d0dc Update Binlogrouter.md
c624781 Update Replication-Proxy-Binlog-Router-Tutorial.md
f3261bc CDC users
1368797 Format authenticator and module headers
ab01749 Format filters
8b05d32 Format core and include files
f3974e5 Add GPL LICENSE to qc_mysqlembedded
bfec36a astyle rabbitmq_consumer/consumer.c
54b960a Check that the Avro directory is writable
3d4cd2e Fix cdc_users using the wrong path for service users cache
1e738dd Add CDC client program documentation
f6809fd Remove superfluous rabbitmw_consumer/LICENSE
6b5e667 Update license text in files
9bfcb46 Change CDC protocol documentation formatting
607f25c  REQUEST-DATA formatting
8175ab4 CDC protocol update
d5ca272 CDC protocol update
6c91764 Only check wsrep_local_index if node is joined
f12e2c2 Do not use SSL for monitors and services
6d2cd99 Fix TestAdminUsers
f4ae50d Apply astyle to server/core/test/*.c
7cc2824 Update build instructions
cf8e2b5 Update release notes
03c7a6c Remove wrong function prototypes
5a11eed Revert "Remove duplicate functions"
80ed488 Remove duplicate functions
bb0de8d Add info on SSL and throttling to release notes for 2.0.
0934aee Update MaxAdmin reference guide
2a3fe9b Update source URL in release notes
e575cf0 Merge branch 'MXS-177-develop' into develop
cc8c88d Change header for BSL
ecde266 Change header for BSL
890b208 Log a message when a script is executed
9c365df Added information on server side SSL to config guide.
aa3e002 Remove obsolete heading
79dd73a Make dprintAllSessions use dprintSession
1fc0db9 Align output of "show services"
1b9d301 Make monitorShowAll use monitorShow
983615e Adjust output of 'show modules'
436badd qc_sqlite: The module is now beta
a7cbbe5 Update Upgrade document
71ac13f Remove obsolete user/password from example
eb20ff8 Fix and clean up Avrorouter diagnostics code
31d4052 Change MaxScale to MariaDB MaxScale
e6e4858 Fix `source` parameter not working with `router_options`
d8de99a Update module version numbers
eb81add Merge remote-tracking branch 'origin/develop' into MXS-177-develop
daba563 Merge remote-tracking branch 'origin/MXS-651-develop-merge' into develop
678f417 Changes in response to reviews.
410fb81 Changes in response to reviews.
60135e5 Add initial release notes about Avrorouter
7400ecc qc_sqlite: Remove uninitialized read
536962c Update version number
018f044 Fix debug assertion in client command processing
51f0804 Prevent 'show monitor' from crashing with failed monitor
559347e Fix "Too many connections" message; add comments.
01d3929 Add printf format checking to dcb_printf
fbd49a6 dbfwfilter: Require complete parsing only when needed
1885863 Add information to release notes about readwritesplit changes
73b56a2 Update MaxScale section in release notes.
0a2f56f MaxAdmin: Remove debug information from 'show users'
3cf3279 MaxAdmin: Report SSL information as well
29c2b66 Always use SSL if server configured with SSL
7d6b335 dprintAllServers should use dprintServer
02a5246 qc_sqlite: Correctly detect parsing context
469419b compare: Add strict mode
8c5b3d3 compare: Allow the comparison of a single statement
4691514 Add Updgrade to 2.0 document
38b3ecb Expand the checks done before a monitor is stopped
8e2cfb9 Add backend name to authentication error message
9600a07 Fix MaxInfo crash
91c58b0 Removed log message for duplicate entry while adding an user
40392fe Fixed log message priority
0ec35b8 maxadmin: Allow the last user to be removed
5a0ebed maxadmin: Change name of user file
87aa8f1 maxadmin: Always allow root to connect
bf37751 Fix COM_QUIT packet detection
7c93ee4 Update avrorouter documentation and tutorial
95ce463 Fix wrong directory in avrorouter log message
cfe54c7 Update ChangeLog
d69562c Fix LOAD DATA LOCAL INFILE data size tracking
24e7cd6 MXS-584: added support for SET @@session.autocommit
d6f6f76 Fixes, correct too many connections message
efeb924 Update release notes for 2.0.0
8f71a87 qc_sqlite: Adjust error messages
b967d60 Remove copy of enum enum_server_command
822b7e3 Update package license
b58301a Update MaxScale License for overlooked files
c09ee47 Update MaxScale License
49f46fa Tidy up. Comment out config items not yet supported.
f5c3470 Updated and simplified the Building from Source document
98b98e2 Add note about master failure modes to documentation
e036f2c Update Limitations document
62219a5 Merge remote-tracking branch 'origin/drain-writeq' into develop
5caf667 Invoke DCB_REASON_DRAINED more frequently.
77b107b qc_sqlite: Add support for LOAD DATA INFILE
8e70f26 compare: Optionally print out the parse result
ad750e6 Merge remote-tracking branch 'origin/MXS-651-develop-merge' into develop
ef85779 Merge remote-tracking branch 'origin/develop' into MXS-651-develop-merge
ea9fdda MXS-477: Add LONGBLOB support for readconnroute
eae6d42 qc_sqlite: Remove superfluous columnname definition
8fe2b21 Add binlog source to avrorouter
b25cc37 qc_sqlite: Add missing destructors
8a749e7 qc_sqlite: Reduce number of keywords
5f4bb8b compare: Output query immediately
2456e52 dbfwfilter: Reject queries that cannot be parsed
5f1fbbd qc_sqlite: Extend SET grammar
b8d8418 dbfwfilter: Remove 'allow' from firewall filter rule
0bd2a44 MXS-741 When no events are read from binlog file, ...
a07c491 Remove duplicated function (merge error, probably)
b237008 Save conflict resolution, missed last time.
a0c0b40 Merge remote-tracking branch 'origin/develop' into MXS-651-develop
385d47d Change SSL logic, fix large read problem.
b93b5e0 Remove false debug assertion
b953b1f Turn off SSL read ahead.
e0d46a5 Fix error messages and remove commented code
49b4655 MXS-739: Fix invalid JSON in Maxinfo
0c30692 qc_sqlite: Handle GROUP_CONCAT arguments
54e48a1 qc_sqlite: Consider \ as an escape character in strings
713a5d6 qc_sqlite: Add test cases
20d1b51 qc_sqlite: Handle qualified names in CREATE VIEW
1019313 qc_sqlite: Make QUERY_TYPE_WRITE default for SHOW
059c14e qc_sqlite: Accept qualified function names in SELECT
db34989 qc_sqlite: Accept qualified function names
b93e2f1 qc_sqlite: Add limited support for GRAND and REVOKE
678672d qc_sqlite: Cleanup copying of database and table names
9b744b9 qc_sqlite: Update table and database names at the same time
db75e61 qc: Support getting the qualified table names
1f867f4 qc: Add join.test
9c7e02a qc_sqlite: Accept "...from NATURAL straight_join..."
93d1c31 qc_sqlite: Both " and ' can enclose a string literal
8055b21 qc_sqlite: Set more information based upon tokens
37e3663 qc_sqlite: Do not blindly add affected fields
50f1360 qc: Correctly collect affected fields
71c234e qc_sqlite: Recognize CREATE TABLE ... UNION
01803f1 qc_sqlite: Recognize {DEALLOCATE|DROP} PREPARE ...
6ecd4b3 qc_sqlite: Parse index hints
0bdab01 qc: Compare sets of tables
b908c8f Fix double freeing of internal DCBs
8903556 qc_sqlite: Recognize LEFT, INSERT and REPLACE
266e6c0 qc: Log all problems by default (compare program)
7b54cac qc_sqlite: Fix logging bug
9566e9f qc_sqlite: Plug a leak
b0a860d qc: Run compare a specified number of times
050d698 qc_sqlite: Simplified argument handling
97c56b8 qc: Allow arguments to be passed to the query classifier
09a46e0 qc_sqlite: Add argument log_unrecognized_statements
fd98153 qc: Allow arguments to be provided to the query classifier
313aa7e Fix Problems SSL assertion; non SSL connect to SSL
1d721e6 Fix DEB packaging errors
96bdc39 Fix RPM packaging failures on CentOS 7
6ba900d qc_sqlite: Recognize more SHOW commands
2869d0b qc_sqlite: Exclude support for sqlite's PRAGMA
0be68a3 qc_sqlite: Enhance SELECT syntax
28f3e1a Merge branch 'develop' into MXS-729
e18bd41 qc: Expose the result of the parsing
5896085 Add BUILD_AVRO to the CMake cache
daeb896 Remove changes to blr_master.c memory handling
d523821 Add comments
4eb9a66 Empty admin users file is now handled
52b46c6 qc: Update create.test
db09711 qc_sqlite: Ignore case when looking for test language keywords
f042a1d qc_sqlite: Extend CREATE TABLE syntax
177d2de qc_sqlite: Extend CREATE TABLE syntax
d3ca8e6 qc_sqlite: Add some support for HANDLER
86c6a96 qc_sqlite: Recognize RENAME TABLE
471594f qc_sqlite: Accept more table options at CREATE TABLE
3da6cde qc_sqlite: Remove unused keywords
bd89662 Fix crash on corrupted passwd file
b5d1764 MXS-733: Always print session states
043e2db Remove unused CMake variables
5604fe2 Restore missing line, fixes logic error.
66d15a5 Added log message warning for old users found
5be9fca Changes in response to review by Johan
899e0e2 Removed password parameter from admin_user_add and admin_remove_user
a2d9302 Merge branch 'develop' into MXS-729
bcaf82f Code review update
e61c716 Nagios plugin update with Maxadmin using UNIX socket only
d7150a2 qc_sqlite: Extend column syntax
3b78df0 qc_sqlite: Accept VALUE in addition to VALUES
85a705b qc_sqlite: Accept CHARSET in addition to CHARACTER SET
db9cec8 qc_sqlite: Accept qualified column  names in CREATE TABLE
a9cabb0 qc_sqlite: Extend SELECT syntax
f5e9878 qc_sqlite: Add set type
675cb93 qc_sqlite: Allow BINARY to turn into an identifier
b04a760 qc_sqlite: Accept DROP TABLES
1075d9c qc_sqlite: Allow qualified name with LIKE in CREATE
420ac56 qc_sqlite: Extend EXPLAIN grammar
727d626 Add missing error message to readwritesplit
f4fd09e Change templates and testing configurations to use sockets
1ef2e06 Add configurable default admin user
a723731 Remove wrong file
7c3b02b Maxadmin/maxscaled UNIX socket update
eed78d4 qc_sqlite: Pick out more information from select when CREATEing
267f091 qc_sqlite: Recognise DROP TEMPORARY TABLE
54fc29f qc_sqlite: Accept $ as a valid character in identifiers
afa2ec9 qc_sqlite: Allow keywords to be used in qualified name
db0427d MXS-729 code review update
a3b3000 Merge branch 'develop' into MXS-729
e73d66c qc_sqlite: Identify qualified identifiers
5bacade Trailing space fix
3bc9be3 MXS-729 socket=default support in maxscale.cnf
1a5c23c Code review update for MXS-729
d6665c7 qc_sqlite: Extend CREATE TABLE grammar
91725ce qc_sqlite: Dequote table and database names
cd7a022 qc: Add create test
1aa4e6b qc: Update test files
762b0c2 qc_mysqlembedded: Do not return "*" as table name
cd9968f qc_sqlite: Update delete.test
f16703d qc_sqlite: Add support for CALL
e3ca9b4 qc_mysqlembedded: Do not return an array of empty strings
5878a22 qc_sqlite: Support selects in DELETE
1cf0444 qc_sqlite: Fix bug in DELETE grammar
0bf39a1 qc_sqlite: Add support for CHECK TABLE
4a8feca qc_sqlite: Add helper for catenating SrcLists
ab299b3 qc_sqlite: Extend DELETE syntax
5778856 qc_sqlite: Extract database name as well
99901f1 qc_sqlite: Extend DELETE syntax
63396f8 qc_sqlite: Match "autocommit" caseinsensitively
e804dd3 qc_sqlite: Add support for LOCK/UNLOCK
c23e442 qc_sqlite: Extend DELETE syntax
5460e31 qc: Add delete test
ab392ad qc_sqlite: Free unused data
598c6f0 qc: Measure time of parsing
2fa3844 qc_sqlite: Put all changes being {%|#}ifdefs
1b43992 qc_sqlite: Modified update.test
1676ea4 qc_sqlite: LEFT|RIGHT are not required with JOIN
224ebd3 qc_sqlite: Extend UPDATE grammar
dbecca9 qc_sqlite: Extend UPDATE grammar
b6ca3b3 MaxAdmin security modification MXS-729
8fb47dd Remove copying of MariaDB embedded library files
22e1257 Normalize whitespace when canonicalizing queries
269cff2 MXS-697: Fix dbfwfilter logging for matched queries
6344f6f Ignore Apple .DS_Store files.
d606977 Improve comments in response to code review.
619aa13 Add configuration check flag to MaxScale
27c860b Drain write queue improvements.
33d4154 Read only one configuration file
d104c19 Format more core files
83fdead Format part of core source code
311d5de Format gateway.c and config.c with Astyle
8cbb48e Don't build maxavro library if BUILD_AVRO is not defined
32bb77a Merge branch 'MXS-483' into develop
db72c5d Format CDC/Avro related files
3c26e27 qc_sqlite: Use SrcList instead of Expr
f96ad6a Merge branch 'develop' into MXS-729
0728734 Fix query canonical form tests
e68262d Merge remote-tracking branch 'gpl-maxscale/master' into develop
65460dc Fix missing symbols from MySQLAuth
791c821 MaxAdmin listens on UNIX socket only and maxadmin can connect
89afed6 MXS-66: All configuration errors are fatal errors
d613053 Add more details to galeramon documentation
22f4f57 qc: Add support for multi UPDATE
0dba25a Added default port to blr_make_registration
9d8248c qc_sqlit: Plug leaks and access errors
057551a qc_sqlite: Fix to small an allocation
1f73820 qc_sqlite: Free memory allocated during parsing
93fefb9 qc: Enable compare to run the same test repeatedly
e52c578 qc_sqlite: Handle last_insert_id()
929e02a qc_sqlite: Extend UPDATE grammar
de3b9f7 qc_sqlite: Defines provided when running cmake and make
4d5c3b2 qc_sqlite: Add support for multiple-table DELETE FROM
36a4296 qc_mysqlembedded: Handle SQLCOM_DELETE_MULTI
41f613a Fix DCB and SESSION removal from free object pools
00f2ddd Move some common code used in only one protocol into protocol.
6fbd0b0 Format Go source with gofmt
abfbbcb Fix build failures and internal test suite
31de74a Merge branch 'develop' into MXS-483
20d461d Remove uniqueness constrain on oneshot tasks
6c09288 Add missing error message to converter task
0c2c389 Merge branch 'develop' into MXS-483
fa0accc Set freed memory to NULL after authentication failure
63f24e4 Install cdc_schema.go
5123c21 Fix ALTER TABLE parsing
004acc2 Merge branch 'develop' into MXS-483
f69a671 Remove array foreach macro use
a159cd9 qc_sqlite: Add support for SHOW DATABASES
31a2118 Make qc_mysqlembedded optional
27ef30e Changed the default query classifier
359010d Add -h flag as the alias for --host
bebc086 Fix minor bugs
c7ca253 qc_sqlite: Recognize START [TRANSACTION]
240f8bf qc_sqlite: Collect info from nested SELECTs
93ea393 qc_sqlite: Pass along the relative position of a token
cc960af qc_sqlite: Fix incorrect assigment
22a6fef Fix `gtid` avro index table
4c38bef qc_sqlite: STATUS is not a registered word
cace998 qc_sqlite: Include all fields of UPDATE
997b19c qc: Add update tests
7601b3f qc_sqlite: Parse "INSERT INTO t VALUES (), ();" correctly
ca426f1 qc_sqlite: Handle CREATE TRIGGER
f54f963 qc_sqlite: Allow INSERT without INTO
e4a1b6d Remove foreign keys from Avro index
e4501a2 Merge branch 'develop' into MXS-483
82b9585 Fix MMMon never assigning master status
a45a709 qc_mysqlembedded: Find the leaf name
2f3ca8f qc_mysqlembedded: Recognize SQLCOM_REPLACE
cc7ad83 qc_mysqlembedded: Pick up fields for INSERT SELECT as well
0e6b39e qc: Cleanup of select.test
9113f4f qc_sqlite: Pickup more fields from INSERT
4d58f98 Dummy query classifier
dfe824f Document `query_classifier` option
4aa329b MXS-718: Collect fields of INSERT
53818f2 Modify packet number for SSL backend connection
346f973 qc_sqlite: Accept qualified column names
8a83616 Fix in-memory SQLite table structure
6f2c884 Further backend SSL development
4444e92 qc_sqlite: Extend INSERT grammar
2aebcab qc_sqlite: Add support for TRUNCATE
1a6742e qc_sqlite: Accept DEFAULT as value in INSERT
07dec05 qc_sqlite: Crude classification made based on seen keywords
a90a579 Add missing function documentation
72bd0cf qc_sqlite: Change CREATE TABLE grammar
6e04bc8 qc: Add INSERT tests
3666bda qc_sqlite: Add SELECT test
d27e173 Add server/mysql-test/t/select.test to query_classifier
562d004 qc_sqlite: Cleanup error logging.
819cacb Merge branch 'develop' into MXS-483
0d3a789 Add warnings and comments to Avro row event processing
2fab570 Added support for SET autocommit=1
1aa83cf Code review fix
c999f0a Addition of SELECT USER()
8c723da Clean up avro_client.c and avro_file.c
eb21ee8 Clean up avro.c
946a284 Added Avro schema to table metadata processing
72f90be qc_sqlite: Add support for CREATE {FUNCTION|PROCEDURE} ...
4a4ab49 qc: Update line number also when skipping a block
ffddb2a qc_sqlite: Allow queries using INTERVAL
b8b03bd qc_sqlite: Add support for SELECT * FROM tbl2 = tbl1;
77a261a qc_sqlite: Add support for GROUP BY ... WITH ROLLUP
0ead41e cdc_schema now generates lowercase JSON
66e327a Classifier has to be specified explicitly
9074b91 Updated Avrorouter documentation
cf06c7a qc_sqlite: Some comments added.
f579eff Added simple Go based Avro schema generator
f448e90 MXS-419: Added ulimit calls to init scripts
b4ad257 Added FindAvro.cmake
56cc9b9 Added the last transaction script to installations
2d52da2 Added temporary avro-alpha package name
6ada071 Fixed cdc_users script
61f0206 Renaming and minor fixes to CDC Python scripts
9d77c32 Moved GTID table tracking to an in-memory database
8ae7cb0 MXS-704: Fixed `which` usage in post-install scripts
195e118 Readwritesplit sessions aren't created if master is down
2be91da Added affected tables to avro diagnostics
b185320 QUERY-LAST-TRANSACTION now returns proper table names
90860b5 Log stale master message only once
4859c60 Table name to GTID mapping
f77bd23 First steps to backend SSL, not yet working.
68b5bf0 qc_sqlite: Don't treat TRUE and FALSE as identifiers
fca8e59 qc_sqlite: Collect database names as well
6b0e04d qc_sqlite: Add support for SHOW CREATE VIEW
77f4b34 qc_mysqlembedded: Report more, rather than less
a73e033 qc_sqlite: Extend builtin functions
9d9650e qc_sqlite: SQL_BUFFER_RESULT must decay to an id
83fe99d qc_sqlite: Support INSERT IGNORE
9d1c9ca Added avrorouter limitations and tutorial
8dd094d qc_sqlite: Recognize builtin functions
2edc3d6 Moved write operations of the maxavro library to a different file
1364e54 Added more comments to the Avro RBR handling code
f711588 Added warnign about unsupported field types
df0d250 Added SQLite3 based indexing to avrorouter
0c55706 Added GTID event flag check in AVRO processing
bfe28dd qc_sqlite: Accept SET GLOBAL|SESSION ...
a8d2068 qc_mysqlembedded: Exlude code that won't compile on 5.5.42
16ea0b3 qc_sqlite: Add support for DROP FUNCTION
1c0f1fc qc: Report stats after comparison
02345b2 qc_sqlite: Recognize builtin readonly functions
c7a5e75 qc_sqlite: Recognize :=
0aa849d qc: Make compare undestand the delimiter command
fb0a877 qc_mysqlembedded: Examine Item::SUBSELECT_ITEMs
045cf8d qc: Add missing mtl commands
e5c6f45 qc_sqlite: Relax qc_get_type comparison
ac3b2df qc_sqlite: Add support for SHOW STATUS
73a34fb qc_sqlite: Add initial support for FLUSH
4ffbe79 qc_sqlite: Extend CREATE TABLE syntax
009af81 qc_sqlite: Add support for SHOW WARNINGS
001de97 qc: Ignore mysqltest constructs
128307d Merge branch 'release-1.4.3' into gpl-master
5e8a06a SET NAMES XXX added
3ca12ba MXS-685: MMMon clears server state before setting it
dc4d2b0 Further steps to connection limit, non-working.
ef70257 MXS-636: Master failures are no longer fatal errors
99f4c64 Updated QUERY-LAST-TRANSACTION format
d1ff157 Changed QUERY-LAST-TRANSACTION format to JSON
8b2f1ac Fixed formatting of the avrorouter
61543df Added QUERY-LAST-TRANSACTION command
c10d10b qc_sqlite: Add support for SHOW CREATE TABLE
106a38f qc_sqlite: Add support for DROP INDEX
2a85421 qc_sqlite: Extend what can be stated about a table
794cd1c qc_sqlite: Add support for MATCH ... AGAINST
dd7b747 qc_sqlite: Accept FULLTEXT and SPATIAL in CREATE TABLE
a13d6ce qc_sqlite: Add support for PREPARE and EXECUTE
0c5d29f qc_sqlite: Add support for ANALYZE
a6cd32b qc_sqlite: Extend SET syntax
5d47704 qc_sqlite: Pick out fields from UPDATE t SET i = ...
0e05735 qc: Understand --error in server test files
8535975 qc_sqlite: Extend CREATE VIEW syntax
b35e638 qc: Igore read type bit if write bit is on
818a814 qc_sqlite: Add support for SHOW VARIABLES
1aa877b qc_sqlite: Add initial support for DO
e92913a qc_sqlite: Add support for CREATE VIEW
d53a46d qc_sqlite: Recognize bit field literals b'1010'
1fb7977 Added GTID event timestmap into struct gtid_pos
8f95b10 Added new fields in AVRO diagnostics
cb4db54 Added tests with large SQL packets to modutil tests
e4dbd6b MXS-621: More fixes to log messages at startup
4f1e9ee qc: compare tester can now read server MySQL tests
cd8154b qc_sqlite: Allow CHARACTER SET to be specified for column
6f8d053 Added MariaDB 10.1 check for new flags in GTID event
71c471b qc_mysqlembedded: Fix type bits setting
26b00a7 qc_sqlite: Extend ALTER grammar
ea6057c qc_sqlite: Handle also pInto when dupping a struct select
2271559 qc_sqlite: Add support for SHOW TABLE STATUS
9caaf27 qc_sqlite: Add support for CREATE ... LIKE oldtable
cd19932 Merge tag '1.4.2' into master
9e9e4d8 Merge branch 'develop' of https://github.com/mariadb-corporation/maxscale-bsl into develop
267cb60 qc_mysqlembedded: Look into parenthesized comma expressions
77c6ca9 qc_sqlite: Recognize token "<=>"
5ca9a9f qc_sqlite: Allow comma expressions in where clause
b08e910 qc_sqlite: Add SELECT options
d11e581 qc_sqlite: Some recursion cleanup
d53d063 Add but don't invoke connection queue functionality.
6818104 Fix logic error in connections limiter
3c61605 qc_sqlite: Find more affected fields
9af8dfd Allow the classifiers to be specified on the command line
5d4a134 Activate call to protocol for max connections error message.
16638e7 Fix another mistake
234f9e6 Fix mistake
843a6fc Fix mistake.
2c6e9ad Fix errors in config.c; enable call to protocol on connection limit.
fd27849 Introduce configuration items for Maximum and Queued Service connections
60d198d Implement very simple connection limit.
84d8f0f Merge remote-tracking branch 'origin/develop' into MXS-177
8a58e63 Merge remote-tracking branch 'origin/develop' into develop
08487cd Add assertion to enforce number of free DCBs not being negative.
f73af2f Added MariaDB 10.1 check for new flags in GTID event
23898ec Fix wrong sprintf specifier, trailing white space.
ea6cfa3 readwritesplit: Cleaned up routeQuery
3858df0 Cleaned up select_connect_backend_servers
c38ee13 Added more buffer tests
48816df Added more modutils tests
537eac2 Added tests for modutil_get_complete_packets
22a6095 MXS-669: modutil_get_complete_packets no longer makes the buffer contiguous
51af97e qc_sqlite: Add support for CREATE INDEX
e50c573 qc_sqlite: Dig out fields for IN
f58c6df qc_sqlite: Dequote table name
319422b qc_sqlite: Accept ENUM as type for a column
5d6a45c qc_sqlite: Allow UNSIGNED to fallback to an id
16a5f20 qc_sqlite: Extend CREATE TABLE syntax
d6268da qc_sqlite: Accept RIGHT and FULL OUTER joins
2207415 qc_sqlite: Allow STRAIGHT_JOIN in SELECT
6fee546 qc_sqlite: Pick upp more table names
9de5f84 Remove trailing white space.
758f84d Improve comments and messages in dcb.c and session.c re recycle memory.
1c2de21 Merge remote-tracking branch 'origin/develop' into dcb-optimise
6614944 DCB code tidying. Fix missing spinlock release; remove redundant variables
ecd5e5c Remove extra code introduced by merge.
877127a Merge commit '3c0d3e5ab6ddde59da764ec904b517759074a31e' into develop
4275bbe Updated the Connector-C version to 2.2.3
c71042b Some tentative list management code; provide for counting service clients.
ad0c8a6 qc_sqlite: Allow empty insert statement
72e75e5 qc_sqlite: Add support for SELECT ... INTO
cc553fa qc_sqlite: MAXSCALE define can now be used everywhere
3305c6e qc_sqlite: Handle CASE in SELECT
702f62e qc_sqlite: Extend CREATE TABLE grammar
941c212 qc_sqlite: Add support for SHOW [INDEX|INDEXES|KEYS]
6a79136 qc_sqlite: Extend grammar for SHOW TABLES and SHOW COLUMNS
f175d2d qc_sqlite: Add SHOW COLUMNS support
6e47951 qc_sqlite: Add support for SHOW TABLES
bcfa0e7 qc_mysqlembedded: Return the actual name and not as-name
3e19f2e Fixed qlafilter build failure
810b24e MXS-675: Standardized qlafilter output
be92173 qc_sqlite: Exclude alias names from affected fields
9479280 qc_sqlite: Add support for explain EXTENDED
13b0e10 qc_sqlite: Add support for DELETE
a6ccfea qc_mysqlembedded: Look at all conditional items
b428041 qc_sqlite: Extend SELECT options
83f829f query_classifier: Correctly calculate the length of a GWBUF
2ddb24c query_classifier: Ensure that -- comments are handled
fa7a746 qc_sqlite: Allow STRAIGHT_JOIN in SELECTS
6f47819 FindLibUUID update
5ed897b Added FindLibUUID cmake file
16e02bb Added FindLibUUID cmake file
aff63e0 MXS-680: qc_mysqlembedded does not look into functions
8a0eeb4 query_classifier: Improve output of compare
6f08185 Query classifier can now convert enums to strings
124e2b9 MXS-679: Correctly collect fields of WHERE
353c97c transaction_safety default is off
896e37b qc_sqlite: Invert stop logic and be more verbose
7a44d4d qc_sqlite: Extend what is accepted in CREATE TABLE
4dbf499 qc_sqlite: Accept FIRST in ALTER TABLE
3f655c0 qc_sqlite: Update table and affected fields for INSERT
8e1e275 qc_sqlite: Make AS optional in CREATE statement
5f2084b qc_sqlite: Add support for ENGINE when creating a table
242f183 qc_sqlite: CREATE paramters handled in the correct place
8ed2e25 qc_sqlite: Trace only when needed
63d4531 qc_sqlite: Update affected fields also from functions
118cdc3 qc_sqlite: Allow multiple index names in USE|IGNORE INDEX
912da76 qc_sqlite: Add initial support for ...IGNORE INDEX...
0aa7de6 qc_sqlite: Log detailed message on error
3e3bf1a qc_sqlite: Extend create syntax.
c4a4572 qc_sqlite: Exclude quoted values
1621f49 Removed MYSQL_EMBEDDED_LIBRARIES
d3e324c UUID generation now comes from libuuid
e8fe678 qc_sqlite: Enable confitional compilation
a9522ba qc_sqlite: Handle X.Y selects
9bc9770 qc_sqlite: Use same stream when outputting padding
366257a qc_sqlite: Add support for UNSIGNED and ZEROFILL
d4d90ff qc_sqlite: Add support for DROP VIEW
d0519bd qc_sqlite: Extend DROP TABLE syntax
c1e4894 qc_sqlite: Add flag to compare for stopping at first error
9fd6344 MXS-674: Maxinfo generates invalid JSON
3c0d3e5 Fix stupid errors.
9d32b2d Include read queue in buffer provided by dcb_read; changes to match.
b690797 Fix double spinlock release in random_jkiss.
6a4328f Fix problems of memory not being freed in some error cases.
2112e56 Change DCB and Session handling to recycle memory; fix bug in random_jkiss.
3912f72 MXS-631, MXS-632: Cleaned up default value CMake files
383ccb8 Fixed build failure on MariaDB 5.5
a60bca5 Merge branch '1.2.1-binlog_router_trx' into develop
3c2a062 Fix to crashes in embedded library with MariaDB 10.0
d3fe938 MXS-662: Service protocol check no longer ignores bind address
c3da49b qc_sqlite: Update affected fields from everywhere
7a0fab8 qc_sqlite: Allow verbosity of compare test to be controlled
81d6822 qc_sqlite: Cleanup handling of select columns
13e5c59 qc_sqlite: Introduce custom allocation functions
026f27d qc_sqlite: Add support for "USE database"
99079df qc_sqlite: Ignore duplicates when comparing affected fields
ca45cd6 qc_sqlite: Add initial support for qc_get_database_names
75970b6 qc_sqlite: Add support for DROP TABLE.
b97e45d qc_sqlite: Move get_affected_fields() to other helpers
cb0fa96 qc_sqlite: Collect table names of INSERT
3a7c513 qc_mysqlembedded: Only look for created name if CREATE
308b0a4 qc_sqlite: Add support for gc_get_created_table_name.
0dc4af2 qc_sqlite: Add qc_has_clause() handling to update
e9f2d1d qc_sqlite: Update now also provides table names
c3192e4 qc_sqlite: Add initial support for get_table_names
c51eafd qc_sqlite: Add support for qc_has_clause
f318fb2 qc_mysqlembedded: Work around embedded lib bug
4ba2e11 qc_sqlite: Add initial support for qc_get_affected_fields
080dea5 qc_sqlite: Support is_read_query
3f94df1 Fixed compare.cc build failure
868a712 Updated freeing of buffer chains in readwritesplit
9bf7fca Formatted readwritesplit source code
de4da2b Add assertion to spinlock release to detect release of already released spinlock.
d30955a qc_sqlite: Handle the default case of affected fields.
5d02b3f qc_sqlite: Set operation when creating table
94a334d Add test for comparing qc-output
aa6f5d6 Allow a specific query classifier to be loaded explicitly
c799d37 Test both qc_mysqlembedded and qc_sqlite
f8d9aa1 qc_sqlite: Enable "set @user_var=@@system_var"
f190bdc qc_sqlite: Recognize /*!-comments
b694b55 Fixed binary Avro format streaming
c95fa86 qc_sqlite: Report correctly the type of set autocommit
9cb236c qc_sqlite: Add test case
77b4e62 Ensure classify test checks all types
962039e Change return type of qc_get_type
ae00df8 qc_sqlite: Add initial support for the SET statement.
88253c5 qc_sqlite: Rename functions
fa48043 Rework of MySQL backend protocol clean up to fix fault.
3851064 qc_sqlite: Correct recognition of system variables (@@xyz).
9d86f7f qc_sqlite: Detect user and system variables.
a683297 qc_sqlite: Recognize and accept system variables (@@xyz).
a4f64dd qc_sqlite: Add initial support for CREATE [TEMPORARY] TABLE
f834b4f MXS-661: Only COM_QUERY packets are parsed
30077c1 CMake policies set only for correct versions
a166f34 Suppress warning about unknown CMake target
1412730 Added more variables to launchable monitor scripts
358c194 MXS-656: Galera nodes with index 0 can be master again
842aec5 qc_sqlite: Add support for BEGIN, COMMIT, ROLLBACK
b9cad6d Add initial support for UPDATE.
95741cb Add initial support for insert.
3796158 Re-install sqlite whenever parse.y has changed
5bcd8cf Ensure that the query is the one passed
cf05533 Add support for obtaining the type of a query
400d8b4 Always log the outcome
45cf632 Fixed resource leaks and minor bugs
fa9e970 Printout the query when there is a mismatch.
263cb07 All classify to be used with any query classifier
ea381b9 Further cleanup of classify.c
23f6f30 Merge pull request #107 from godmodelabs/typo-dpkg
8c2a64e Fixed classify build failure
0c3070b Fixed binlog to Avro conversion bugs
b827ba9 MXS-653: Silence maxpasswd
30d981c MXS-654: Add test for checking maxpasswd
984039b Rearrange classify.c
837e46d Add log initialization
1cc7a6e Reformat query_classifier/test/classify.c
065a4e5 Merge branch 'develop' into develop-MXS-544-b-merge
ca27f13 Fixed binlog build failure
fb81be2 fixed typo dpgk <-> dpkg
1e88d5d Added python based CDC user creation script
040bbdd MXS-633: Monitor permission checks moved to modules
cde7595 Master-Slave clusters are now robust by default
158c776 Cleaned up core test suite
94c6e66 Fixed bugs resulting from merge
a491e11 Merge remote-tracking branch 'origin/MXS-544-b' into develop-MXS-544-b-merge
30f9f25 Cleaned up avro.c
6286f64 Merge branch 'release-1.4.1' into develop
00206ac MXS-194: Added support for more query types to dbfwfilter
267832b Fixed diagnostic output
a64b694 Fixed bugs in avrorouter
8faaba1 Fixed a bug in GTID seeking
a5fafb7 Fixed typos in avrorouter documentation
8080379 Added avrorouter documentation
fa07d8a Fixed dbfwfilter rule parser build failure
744ce0d Constraints are ignored in DDL statement processing
50808c6 Cleaned up avrorouter
47f6032 Merge branch '1.2.1-binlog_router_trx_lint' into develop
caa0956 Added missing dependencies to maxscale-core
92df61a Remove parallel make from travis coverity builds
fa2b2b4 Added more error logging to Avro record reading
9a98e8b Support for GTID requests and data bursts
c2a787b Small diagnostic fix
c4cee7e Added format output requested by client
50483c7 Cleaning up of Avro code
d485379 Added support for binary Avro protocol
c22cdbb Converted Avro GTID from string to integer representation
5795ca9 Added coverity notification email to .travis.yml
a06e44d Added coverity_scan to Travis
6b94384 Fixed memory leak in avro_schema.c
a11096c Support for db.table request for Avrorouter
4e5cbbf Fixed bugs in Avro record reading
a99e427 Fixed minor bugs in avrorouter
01db8ae Fixed errors with CREATE TABLE statements
f5f3d7a Diagnostic routine update
209324f Added missing include for log_manager.h
e62f764 Added sending of schemas and file rotation
8c8fcbb Added missing log_manager.h include
b13942d Changed printf calls in maxavro library to MXS_ERROR
1168962 More lint inspired changes, mainly in blr_master.c and blr_slave.c
ced8f2f Fixed directory checks in avrorouter
a8ae6be Minor fix to string processing
fbd2d95 Fixed typo in dbfwfilter's CMakeLists.txt
29c3cf4 Merge pull request #106 from mariadb-corporation/willfong-patch-1
854d4e9 Add password column name to example
2f956df Moved server state change logging to a common function
007121f Fixed truncated string values
782892b Fix lint errors and warnings for blr_file.c
4f99fc5 Added Avro testing script
2820980 Small fix to help clear lint problems in blr.c
3afeda4 Fixed errors and warnings located by lint
ecfff82 Fix most lint problems in blr.c
223689c Added ALTER TABLE support
80bc935 Fix final lint problems with mysql_common protocol functions.
e068310 Added preliminary alter table parsing
8c723f1 Lint monitor modules
fdb5620 Fix lint issues in authenticators.
84f0e04 Added function documentation and renamed files
365d9f5 Tidy up, mainly for lint
2ff3005 Added update rows event processing and event types to avro records
2ae0371 Fixed failing regex and improved data streaming
f19206a Renamed avrorouter header
aa7174b Moved relpacement and storage of ddl statements to a separate function
0c10be8 Improved client notification and added Avro block size managemet
91405a7 Cleaned up instance creation
dd97485 Removed useless vars
af64e9e Added CDC authentication with a db file
b73a118 Streamline and lint MySQL backend protocol.
65034ce Merge branch 'release-1.4.0' into develop
28f7e4e Added callback for AVRO client async data transmission
628c27a Added MAXAVRO_FILE struct to AVRO_CLIENT
32b3645 Fixed slavelag build failure
7b15542 Added default authentication method for CDC protocol
5f8e20f Renamed maxavro types and formatted files that use them
882cf84 Added more function documentation to maxavro library
9532f0b Fixed CDC protocol build failure
35a1d3a Added support for offsets in client requests
94577ac Fixed, formatted and refactored CDC protocol
da9bcad Use the maxavro library to read data from Avro files
3ececee Added low level error checking to maxavro library
01b0b8b Tidy and lint mysql_client.c
943f0a7 Added handling of Avro boolean data types to maxavro library
4c781f7 Cleaned up maxavro library and avrorouter
6b2e85d Renamed functions more consistently and cleaned up code
e07158a Moved query event handling to its own function
df7d4c0 Added avro_ prefix to rbr.c
fcbfceb Added seeking to a position in an Avro file
068243a CDC auth decoding
3584d54 Add checks to simplify downstream logic.
9b2c323 Removed useless fprintf
bd5cd52 Added missing authfunc setup
e4aff59 Added record value processing
5cc8615 Added value length functions
7921ecc Merge branch 'MXS-615' into MXS-483
4b09cca Added Travis status to readme.md
cca3a48 Simplify interface to max admin authentication.
4739838 Authenticator API update
233505f Maxavrocheck now accepts multiple files
3fdd137 Improved the Avro file handling
a6ba913 Merge from MXS-615
417d742 Added maxavrocheck
014f9cf Remove obsolete second parameter from authenticate function in authenticators.
ece7ece MaxAdmin authentication converted to a module. Fix quirk in SSL setup.
7c8b37e Moved contents of avro_schema.h into mxs_avro.h
d6660cf Improvements to type handling
71ed0cf Protocol API to have entry point for obtaining default authenticator name.
9d35de2 Fixed transaction tracking
5be02a2 Avrorouter internal state is now stored in the Avro file directory
9293464 Added new info to avro diagnostics
06e0e93 Protocol modules can still handle the authentication outside authenticator modules
6d7108b Added JSON output when Requesting an avro file
6188211 Added new CDC protocol state
c8af27f CDC authentication uses its own authenticator
6590f94 Factor out qc_get_qtype_str
b7880f1 Fix qc_sqlite CMakeLists.txt
bd4ff43 Fixed connector-c being updated and built after every make invokation
0d9e57b Fixed non-MariaDB connectors being used in builds
3d3b779 FIX BUG IN CLIENT DCB SHUTDOWN THAT CAN CAUSE CRASHES
e45ba33 Fixed Connector-C .cmake files
c130189 Fixed connector-c being updated and built after every make invokation
7f3cdf3 Fixed errors on binlog rotation
9d3c83a Remove qc_sqlite
15e8ba5 CDC protocol is now compliant with new protocol structure
4460869 Merge branch 'release-1.4.0' into MXS-483
ea40812 Cleaned up the binlog processing loop
cb646ca Add minimal select recognition to qc_sqlite
ac1a9c5 Fixed binlogrouter test
85dd227 Re-route sqlite's sqlite3Select.
7a2e6f3 Update CMakeLists.txt for qc_sqlite
7a751c3 Added timestamps to records and fixed minor bugs
f73bdde Avrorouter state storage to disk
fcf0488 Fixed Connector-C .cmake files
48b8e4e Merge branch 'MXS-615' into MXS-615-binlog-merge
7c8e19f Add missing dependencies for qc_sqlite
bb9b667 Improvements to type handling and binlog position tracking
dc66b74 Client UUID added
f12fce4 AVRO registration is now handled by avro router
575b809 Add skeleton sqlite-based query classifier.
d09d5fc Build sqlite
146d1f9 Fixed BLOB type handling and refined error messages
6e9e521 Added client user to diagnostics
4538bb8 Merge pull request #104 from rasmushoj/develop
7e18d95 Avro router diagnostics routine update
01e3f75 reverted changes in CMakeLists.txt
52f7c78 reverted changes in postinst.in
eaed577 Added sqlite 3110100
a58cdda Travis configuration for MaxScale. ...
38b452d MIGRATE FREE CLIENT DATA TO AUTH MODULE; BUG FIXES; TIDY UP
6e64506 Fixed minor bugs
aff2411 Enabled CDC protocol
f669100 Fixed NULL Avro value being assigned to a field which cannot be NULL
8f6b16a Added row event processing to avrorouter
2939fe0 Updated Avro schema management to use actual column names
9e3b0cb Removed use of RBR related functions in binlogrouter
d674903 Formatted avro files
fe028d1 DEVELOPMENT OF AUTHENTICATION AS MODULE - WILL NOT WORK YET
977aded Added authenticator modules to the build
a2b384f MOVE MYSQL AUTH CODE INTO AUTHENTICATOR MODULES DIRECTORY
a5d7484 PRELIMINARY CHANGES TO CREATE AUTHENTICATORS AS MODULES
66cf802 Merge remote-tracking branch 'origin/develop' into MXS-615
bca0a7d MINOR CHANGES TO SATISFY LINT
5a9e397 Added Avrorouter binlog file walking
fbc737f Fixed binlogrouter test
3c7c9d7 Added avrorouter main event handling loop
07ad81b Moved common binlogrouter code to a separate file
8c605ed Fixed avrorouter build failures
aa1ba05 Moved binlog definitions to a separate header and fixed build failures
eee7c55 Added create table statement detection
e52b27e Added AVRO_INSTANCE and AVRO_CLIENT
0830caa Change test for client DCB to use role being DCB_ROLE_CLIENT_HANDLER. ...
997bbca Change protocols to continue looping if an accept fails; ...
522e42d Make use of dcb_accept and dcb_listen in httpd and telnetd protocols.
4e692b0 Generalise dcb_listen to tailor log messages to different protocols. ...
52c431d Remove support for passing default port number when handling ...
afe5abc Fix bug in creation of SSL listener structure; fix bugs in ...
0bd6c77 Merge remote-tracking branch 'origin/MXS-544' into MXS-544-a ...
7598597 Add dcb_listen function to make a given DCB into a listener, ...
a275d89 Maxbinlogcheck avro version can detect proper end of file
9bb55a5 Moved row event and table map event handling to a separate file
b7d9e09 Add/improve comments, fix mistake with premature return.
c598770 First attempt at extracting general code into dcb_accept, ...
f20f28f Testing with maxbinlogcheck
b3c60b7 Added mysql_binlog files
0ff9971 Added MariaDB/MySQL binary data processing functions
124560c Merge branch '1.2.1-binlog_router_trx' into MXS-483
4deccff New router fro cdc client
2c11434 Fixed test compiler errors
c1f7d24 Obliged to merge remote-tracking branch 'origin/develop' ...
1775599 Merge remote-tracking branch 'origin/MXS-544' into Test-dev-544-merge
c5317da Small modifications in comments
11c0666 Code cleanup
64a5e9a Merge branch 'release-1.3.0' into MXS-483
2c11e89 First Implementation of CDC
2016-08-11 12:44:07 +03:00

2570 lines
72 KiB
C

/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl.
*
* Change Date: 2019-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
/**
* @file gateway.c - The gateway entry point.
*
* @verbatim
* Revision History
*
* Date Who Description
* 23-05-2013 Massimiliano Pinto epoll loop test
* 12-06-2013 Mark Riddoch Add the -p option to set the
* listening port
* and bind addr is 0.0.0.0
* 19/06/13 Mark Riddoch Extract the epoll functionality
* 21/06/13 Mark Riddoch Added initial config support
* 27/06/13
* 28/06/13 Vilho Raatikka Added necessary headers, example functions and
* calls to log manager and to query classifier.
* Put example code behind SS_DEBUG macros.
* 05/02/14 Mark Riddoch Addition of version string
* 29/06/14 Massimiliano Pinto Addition of pidfile
* 10/08/15 Markus Makela Added configurable directory locations
* 19/01/16 Markus Makela Set cwd to log directory
* @endverbatim
*/
#define _XOPEN_SOURCE 700
#define OPENSSL_THREAD_DEFINES
#include <my_config.h>
#include <openssl/opensslconf.h>
#if defined(OPENSSL_THREADS)
#define HAVE_OPENSSL_THREADS 1
#else
#define HAVE_OPENSSL_THREADS 0
#endif
#include <ftw.h>
#include <string.h>
#include <strings.h>
#include <gw.h>
#include <unistd.h>
#include <time.h>
#include <getopt.h>
#include <service.h>
#include <server.h>
#include <dcb.h>
#include <session.h>
#include <modules.h>
#include <maxconfig.h>
#include <maxscale/poll.h>
#include <housekeeper.h>
#include <service.h>
#include <memlog.h>
#include <stdlib.h>
#include <unistd.h>
#include <mysql.h>
#include <monitor.h>
#include <version.h>
#include <maxscale.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <skygw_utils.h>
#include <log_manager.h>
#include <query_classifier.h>
#include <execinfo.h>
#include <ini.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/file.h>
#include <statistics.h>
#define STRING_BUFFER_SIZE 1024
#define PIDFD_CLOSED -1
/** for procname */
#if !defined(_GNU_SOURCE)
# define _GNU_SOURCE
#endif
extern char *program_invocation_name;
extern char *program_invocation_short_name;
/* The data directory we created for this gateway instance */
static char datadir[PATH_MAX + 1] = "";
static bool datadir_defined = false; /*< If the datadir was already set */
/* The data directory we created for this gateway instance */
static char pidfile[PATH_MAX + 1] = "";
static int pidfd = PIDFD_CLOSED;
/**
* exit flag for log flusher.
*/
static bool do_exit = FALSE;
/**
* Flag to indicate whether MySQL is successfully initialized.
*/
static bool libmysql_initialized = FALSE;
/**
* If MaxScale is started to run in daemon process the value is true.
*/
static bool daemon_mode = true;
static const char* maxscale_commit = MAXSCALE_COMMIT;
const char *progname = NULL;
static struct option long_options[] =
{
{"config-check", no_argument, 0, 'c'},
{"config", required_argument, 0, 'f'},
{"nodaemon", no_argument, 0, 'd'},
{"log", required_argument, 0, 'l'},
{"logdir", required_argument, 0, 'L'},
{"datadir", required_argument, 0, 'D'},
{"configdir", required_argument, 0, 'C'},
{"piddir", required_argument, 0, 'P'},
{"libdir", required_argument, 0, 'B'},
{"cachedir", required_argument, 0, 'A'},
{"language", required_argument, 0, 'N'},
{"syslog", required_argument, 0, 's'},
{"maxlog", required_argument, 0, 'S'},
{"user", required_argument, 0, 'U'},
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, '?'},
{"version-full", no_argument, 0, 'V'},
{"log_augmentation", required_argument, 0, 'G'},
{0, 0, 0, 0}
};
static bool syslog_configured = false;
static bool maxlog_configured = false;
static bool log_to_shm_configured = false;
static int last_signal = 0;
static int cnf_preparser(void* data, const char* section, const char* name, const char* value);
static void log_flush_shutdown(void);
static void log_flush_cb(void* arg);
static int write_pid_file(); /* write MaxScale pidfile */
static void unlink_pidfile(void); /* remove pidfile */
static void unlock_pidfile();
static void libmysqld_done(void);
static bool file_write_header(FILE* outfile);
static bool file_write_footer(FILE* outfile);
static void write_footer(void);
static int ntfw_cb(const char*, const struct stat*, int, struct FTW*);
static bool file_is_readable(const char* absolute_pathname);
static bool file_is_writable(const char* absolute_pathname);
bool handle_path_arg(char** dest, char* path, char* arg, bool rd, bool wr);
static void set_log_augmentation(const char* value);
static void usage(void);
static char* get_expanded_pathname(
char** abs_path,
const char* input_path,
const char* fname);
static void print_log_n_stderr(
bool do_log,
bool do_stderr,
const char* logstr,
const char* fprstr,
int eno);
static bool resolve_maxscale_conf_fname(
char** cnf_full_path,
const char* home_dir,
char* cnf_file_arg);
static char* check_dir_access(char* dirname, bool, bool);
static int set_user(const char* user);
bool pid_file_exists();
void write_child_exit_code(int fd, int code);
static bool change_cwd();
void shutdown_server();
static void log_exit_status();
/** SSL multi-threading functions and structures */
static SPINLOCK* ssl_locks;
static void ssl_locking_function(int mode, int n, const char* file, int line)
{
if (mode & CRYPTO_LOCK)
{
spinlock_acquire(&ssl_locks[n]);
}
else
{
spinlock_release(&ssl_locks[n]);
}
}
/**
* OpenSSL requires this struct to be defined in order to use dynamic locks
*/
struct CRYPTO_dynlock_value
{
SPINLOCK lock;
};
/**
* Create a dynamic OpenSSL lock. The dynamic lock is just a wrapper structure
* around a SPINLOCK structure.
* @param file File name
* @param line Line number
* @return Pointer to new lock or NULL of an error occurred
*/
static struct CRYPTO_dynlock_value *ssl_create_dynlock(const char* file, int line)
{
struct CRYPTO_dynlock_value* lock = malloc(sizeof(struct CRYPTO_dynlock_value));
if (lock)
{
spinlock_init(&lock->lock);
}
return lock;
}
/**
* Lock a dynamic lock for OpenSSL.
* @param mode
* @param n pointer to lock
* @param file File name
* @param line Line number
*/
static void ssl_lock_dynlock(int mode, struct CRYPTO_dynlock_value * n, const char* file, int line)
{
if (mode & CRYPTO_LOCK)
{
spinlock_acquire(&n->lock);
}
else
{
spinlock_release(&n->lock);
}
}
/**
* Free a dynamic OpenSSL lock.
* @param n Lock to free
* @param file File name
* @param line Line number
*/
static void ssl_free_dynlock(struct CRYPTO_dynlock_value * n, const char* file, int line)
{
free(n);
}
#ifdef OPENSSL_1_0
/**
* The thread ID callback function for OpenSSL dynamic locks.
* @param id Id to modify
*/
static void maxscale_ssl_id(CRYPTO_THREADID* id)
{
CRYPTO_THREADID_set_numeric(id, pthread_self());
}
#endif
/**
* Handler for SIGHUP signal. Reload the configuration for the
* gateway.
*/
static void sighup_handler (int i)
{
MXS_NOTICE("Refreshing configuration following SIGHUP\n");
config_reload();
}
/**
* Handler for SIGUSR1 signal. A SIGUSR1 signal will cause
* maxscale to rotate all log files.
*/
static void sigusr1_handler (int i)
{
MXS_NOTICE("Log file flush following reception of SIGUSR1\n");
mxs_log_rotate();
}
static const char shutdown_msg[] = "\n\nShutting down MaxScale\n\n";
static void sigterm_handler(int i)
{
last_signal = i;
shutdown_server();
write(STDERR_FILENO, shutdown_msg, sizeof(shutdown_msg) - 1);
}
static void
sigint_handler(int i)
{
last_signal = i;
shutdown_server();
write(STDERR_FILENO, shutdown_msg, sizeof(shutdown_msg) - 1);
}
static void
sigchld_handler (int i)
{
int exit_status = 0;
pid_t child = -1;
if ((child = wait(&exit_status)) == -1)
{
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("Failed to wait child process: %d %s",
errno, strerror_r(errno, errbuf, sizeof(errbuf)));
}
else
{
if (WIFEXITED(exit_status))
{
if (WEXITSTATUS(exit_status) != 0)
{
MXS_ERROR("Child process %d exited with status %d",
child, WEXITSTATUS(exit_status));
}
else
{
MXS_INFO("Child process %d exited with status %d",
child, WEXITSTATUS(exit_status));
}
}
else if (WIFSIGNALED(exit_status))
{
MXS_ERROR("Child process %d was stopped by signal %d.",
child, WTERMSIG(exit_status));
}
else
{
MXS_ERROR("Child process %d did not exit normally. Exit status: %d",
child, exit_status);
}
}
}
int fatal_handling = 0;
static int signal_set(int sig, void (*handler)(int));
static void
sigfatal_handler(int i)
{
if (fatal_handling)
{
fprintf(stderr, "Fatal signal %d while backtracing\n", i);
_exit(1);
}
fatal_handling = 1;
GATEWAY_CONF* cnf = config_get_global_options();
fprintf(stderr, "\n\nMaxScale "MAXSCALE_VERSION" received fatal signal %d\n", i);
MXS_ERROR("Fatal: MaxScale "MAXSCALE_VERSION" received fatal signal %d. Attempting backtrace.", i);
MXS_ERROR("Commit ID: %s System name: %s "
"Release string: %s",
maxscale_commit, cnf->sysname, cnf->release_string);
{
void *addrs[128];
int n, count = backtrace(addrs, 128);
char** symbols = backtrace_symbols(addrs, count);
if (symbols)
{
for (n = 0; n < count; n++)
{
MXS_ERROR(" %s\n", symbols[n]);
}
free(symbols);
}
else
{
fprintf(stderr, "\nresolving symbols to error log failed, writing call trace to stderr:\n");
backtrace_symbols_fd(addrs, count, fileno(stderr));
}
}
mxs_log_flush_sync();
/* re-raise signal to enforce core dump */
fprintf(stderr, "\n\nWriting core dump\n");
signal_set(i, SIG_DFL);
raise(i);
}
/**
* @node Wraps sigaction calls
*
* Parameters:
* @param sig Signal to set
* @param void Handler function for signal *
*
* @return 0 in success, 1 otherwise
*
*
* @details (write detailed description here)
*
*/
static int signal_set(int sig, void (*handler)(int))
{
static struct sigaction sigact;
static int err;
int rc = 0;
memset(&sigact, 0, sizeof(struct sigaction));
sigact.sa_handler = handler;
GW_NOINTR_CALL(err = sigaction(sig, &sigact, NULL));
if (err < 0)
{
int eno = errno;
errno = 0;
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("Failed call sigaction() in %s due to %d, %s.",
program_invocation_short_name,
eno,
strerror_r(eno, errbuf, sizeof(errbuf)));
rc = 1;
}
return rc;
}
/**
* @brief Create the data directory for this process
*
* This will prevent conflicts when multiple MaxScale instances are run on the
* same machine.
* @param base Base datadir path
* @param datadir The result where the process specific datadir is stored
* @return True if creation was successful and false on error
*/
static bool create_datadir(const char* base, char* datadir)
{
bool created = false;
int len = 0;
if ((len = snprintf(datadir, PATH_MAX, "%s", base)) < PATH_MAX &&
(mkdir(datadir, 0777) == 0 || errno == EEXIST))
{
if ((len = snprintf(datadir, PATH_MAX, "%s/data%d", base, getpid())) < PATH_MAX)
{
if ((mkdir(datadir, 0777) == 0) || (errno == EEXIST))
{
created = true;
}
else
{
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("Cannot create data directory '%s': %d %s\n",
datadir, errno, strerror_r(errno, errbuf, sizeof(errbuf)));
}
}
}
else
{
if (len < PATH_MAX)
{
char errbuf[STRERROR_BUFLEN];
fprintf(stderr, "Error: Cannot create data directory '%s': %d %s\n",
datadir, errno, strerror_r(errno, errbuf, sizeof(errbuf)));
}
else
{
MXS_ERROR("Data directory pathname exceeds the maximum allowed pathname "
"length: %s/data%d.", base, getpid());
}
}
return created;
}
/**
* Cleanup the temporary data directory we created for the gateway
*/
int ntfw_cb(const char* filename,
const struct stat* filestat,
int fileflags,
struct FTW* pfwt)
{
int rc = remove(filename);
if (rc != 0)
{
int eno = errno;
errno = 0;
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("Failed to remove the data directory %s of MaxScale due to %d, %s.",
datadir, eno, strerror_r(eno, errbuf, sizeof(errbuf)));
}
return rc;
}
/**
* @brief Clean up the data directory
*
* This removes the process specific datadir which is currently only used by
* the embedded library. In the future this directory could contain other
* temporary files and relocating this to to, for example, /tmp/ could make sense.
*/
void cleanup_process_datadir()
{
int depth = 1;
int flags = FTW_CHDIR | FTW_DEPTH | FTW_MOUNT;
const char *proc_datadir = get_process_datadir();
if (strcmp(proc_datadir, get_datadir()) != 0 && access(proc_datadir, F_OK) == 0)
{
nftw(proc_datadir, ntfw_cb, depth, flags);
}
}
static void libmysqld_done(void)
{
if (libmysql_initialized)
{
mysql_library_end();
}
}
static void write_footer(void)
{
file_write_footer(stdout);
}
static bool file_write_footer(FILE* outfile)
{
bool succp = false;
size_t len1;
const char* header_buf1;
header_buf1 = "------------------------------------------------------"
"\n\n";
len1 = strlen(header_buf1);
fwrite((void*)header_buf1, len1, 1, outfile);
succp = true;
return succp;
}
// Documentation says 26 bytes is enough, but 32 is a nice round number.
#define ASCTIME_BUF_LEN 32
static bool file_write_header(FILE* outfile)
{
bool succp = false;
size_t len1;
size_t len2;
size_t len3;
const char* header_buf1;
char header_buf2[ASCTIME_BUF_LEN];
const char* header_buf3;
time_t t;
struct tm tm;
#if defined(LAPTOP_TEST)
struct timespec ts1;
ts1.tv_sec = 0;
ts1.tv_nsec = DISKWRITE_LATENCY * 1000000;
#endif
#if !defined(SS_DEBUG)
return true;
#endif
t = time(NULL);
localtime_r(&t, &tm);
header_buf1 = "\n\nMariaDB Corporation MaxScale " MAXSCALE_VERSION "\t";
asctime_r(&tm, header_buf2);
header_buf3 = "------------------------------------------------------\n";
len1 = strlen(header_buf1);
len2 = strlen(header_buf2);
len3 = strlen(header_buf3);
#if defined(LAPTOP_TEST)
nanosleep(&ts1, NULL);
#else
fwrite((void*)header_buf1, len1, 1, outfile);
fwrite((void*)header_buf2, len2, 1, outfile);
fwrite((void*)header_buf3, len3, 1, outfile);
#endif
succp = true;
return succp;
}
static bool resolve_maxscale_conf_fname(char** cnf_full_path,
const char* home_dir,
char* cnf_file_arg)
{
if (cnf_file_arg)
{
*cnf_full_path = (char *)malloc(PATH_MAX + 1);
if (!realpath(cnf_file_arg, *cnf_full_path))
{
const char* logstr = "Failed to open read access to configuration file.";
int eno = errno;
print_log_n_stderr(true, true, logstr, logstr, eno);
free(*cnf_full_path);
*cnf_full_path = NULL;
}
}
else /*< default config file name is used */
{
*cnf_full_path = get_expanded_pathname(NULL, home_dir, default_cnf_fname);
}
return *cnf_full_path && file_is_readable(*cnf_full_path);
}
/**
* Check read and write accessibility to a directory.
* @param dirname directory to be checked
*
* @return NULL if directory can be read and written, an error message if either
* read or write is not permitted.
*/
static char* check_dir_access(char* dirname, bool rd, bool wr)
{
char errbuf[PATH_MAX * 2];
char* errstr = NULL;
if (dirname == NULL)
{
errstr = strdup("Directory argument is NULL");
goto retblock;
}
if (access(dirname, F_OK) != 0)
{
snprintf(errbuf, PATH_MAX * 2 - 1, "Can't access '%s'.", dirname);
errbuf[PATH_MAX * 2 - 1] = '\0';
errstr = strdup(errbuf);
goto retblock;
}
if (rd && !file_is_readable(dirname))
{
snprintf(errbuf, PATH_MAX * 2 - 1, "MaxScale doesn't have read permission "
"to '%s'.", dirname);
errbuf[PATH_MAX * 2 - 1] = '\0';
errstr = strdup(errbuf);
goto retblock;
}
if (wr && !file_is_writable(dirname))
{
snprintf(errbuf, PATH_MAX * 2 - 1, "MaxScale doesn't have write permission "
"to '%s'.", dirname);
errbuf[PATH_MAX * 2 - 1] = '\0';
errstr = strdup(errbuf);
goto retblock;
}
retblock:
return errstr;
}
/**
* @node Provides error printing for non-formatted error strings.
*
* @param do_log Specifies whether printing to log is enabled
*
* @param do_stderr Specifies whether printing to stderr is enabled
*
* @param logstr String to be printed to log
*
* @param fprstr String to be printed to stderr
*
* @param eno Errno, if it is set, zero, otherwise
*/
static void print_log_n_stderr(
bool do_log, /*< is printing to log enabled */
bool do_stderr,/*< is printing to stderr enabled */
const char* logstr, /*< string to be printed to log */
const char* fprstr, /*< string to be printed to stderr */
int eno) /*< errno, if it is set, zero, otherwise */
{
char* log_err = "Error :";
char* fpr_err = "*\n* Error :";
char* fpr_end = "\n*\n";
if (do_log)
{
mxs_log_init(NULL, get_logdir(), MXS_LOG_TARGET_FS);
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("%s %s %s %s",
log_err,
logstr,
eno == 0 ? " " : "Error :",
eno == 0 ? " " : strerror_r(eno, errbuf, sizeof(errbuf)));
}
if (do_stderr)
{
char errbuf[STRERROR_BUFLEN];
fprintf(stderr,
"%s %s %s %s %s",
fpr_err,
fprstr,
eno == 0 ? " " : "Error :",
eno == 0 ? " " : strerror_r(eno, errbuf, sizeof(errbuf)),
fpr_end);
}
}
/**
* Check if the file or directory is readable
* @param absolute_pathname Path of the file or directory to check
* @return True if file is readable
*/
static bool file_is_readable(const char* absolute_pathname)
{
bool succp = true;
if (access(absolute_pathname, R_OK) != 0)
{
int eno = errno;
errno = 0;
char buff[PATH_MAX + 100];
snprintf(buff, sizeof(buff), "Opening file '%s' for reading failed.", absolute_pathname);
print_log_n_stderr(true, true, buff, buff, eno);
succp = false;
}
return succp;
}
/**
* Check if the file or directory is writable
* @param absolute_pathname Path of the file or directory to check
* @return True if file is writable
*/
static bool file_is_writable(const char* absolute_pathname)
{
bool succp = true;
if (access(absolute_pathname, W_OK) != 0)
{
int eno = errno;
errno = 0;
char buff[PATH_MAX + 100];
snprintf(buff, sizeof(buff), "Opening file '%s' for writing failed.", absolute_pathname);
print_log_n_stderr(true, true, buff, buff, eno);
succp = false;
}
return succp;
}
/**
* @node Expand path expression and if fname is provided, concatenate
* it to path to for an absolute pathname. If fname is provided
* its readability is tested.
*
* Parameters:
* @param output_path memory address where expanded path is stored,
* if output_path != NULL
*
* @param relative_path path to be expanded
*
* @param fname file name to be concatenated to the path, may be NULL
*
* @return expanded path and if fname was NULL, absolute pathname of it.
* Both return value and *output_path are NULL in case of failure.
*
*
*/
static char* get_expanded_pathname(char** output_path,
const char* relative_path,
const char* fname)
{
char* cnf_file_buf = NULL;
char* expanded_path;
if (relative_path == NULL)
{
goto return_cnf_file_buf;
}
expanded_path = (char*)malloc(PATH_MAX);
/*<
* Expand possible relative pathname to absolute path
*/
if (realpath(relative_path, expanded_path) == NULL)
{
int eno = errno;
errno = 0;
char buff[PATH_MAX + 100];
snprintf(buff, sizeof(buff), "Failed to read the directory '%s'.", relative_path);
print_log_n_stderr(true, true, buff, buff, eno);
free(expanded_path);
*output_path = NULL;
goto return_cnf_file_buf;
}
if (fname != NULL)
{
/*<
* Concatenate an absolute filename and test its existence and
* readability.
*/
size_t pathlen = strnlen(expanded_path, PATH_MAX) +
1 + strnlen(fname, PATH_MAX) + 1;
cnf_file_buf = (char*)malloc(pathlen);
if (cnf_file_buf == NULL)
{
ss_dassert(cnf_file_buf != NULL);
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("Memory allocation failed due to %s.",
strerror_r(errno, errbuf, sizeof(errbuf)));
free(expanded_path);
expanded_path = NULL;
goto return_cnf_file_buf;
}
snprintf(cnf_file_buf, pathlen, "%s/%s", expanded_path, fname);
if (!file_is_readable(cnf_file_buf))
{
free(expanded_path);
free(cnf_file_buf);
expanded_path = NULL;
cnf_file_buf = NULL;
goto return_cnf_file_buf;
}
}
else
{
/*<
* If only directory was provided, check that it is
* readable.
*/
if (!file_is_readable(expanded_path))
{
free(expanded_path);
expanded_path = NULL;
goto return_cnf_file_buf;
}
}
if (output_path == NULL)
{
free(expanded_path);
}
else
{
*output_path = expanded_path;
}
return_cnf_file_buf:
return cnf_file_buf;
}
static void usage(void)
{
fprintf(stderr,
"\nUsage : %s [OPTION]...\n\n"
" -c, --config-check Validate configuration file and exit\n"
" -d, --nodaemon enable running in terminal process (default:disabled)\n"
" -f, --config=FILE relative or absolute pathname of MaxScale configuration file\n"
" (default:/etc/maxscale.cnf)\n"
" -l, --log=[file|shm|stdout] log to file, shared memory or stdout (default: file)\n"
" -L, --logdir=PATH path to log file directory (default: /var/log/maxscale)\n"
" -A, --cachedir=PATH path to cache directory (default: /var/cache/maxscale)\n"
" -B, --libdir=PATH path to module directory (default: /usr/lib64/maxscale)\n"
" -C, --configdir=PATH path to configuration file directory (default: /etc/)\n"
" -D, --datadir=PATH path to data directory, stored embedded mysql tables\n"
" (default: /var/cache/maxscale)\n"
" -E, --execdir=PATH path to the maxscale and other executable files\n"
" (default: /usr/bin)\n"
" -N, --language=PATH path to errmsg.sys file (default: /var/lib/maxscale)\n"
" -P, --piddir=PATH path to PID file directory (default: /var/run/maxscale)\n"
" -U, --user=USER run MaxScale as another user.\n"
" The user ID and group ID of this user are used to run MaxScale.\n"
" -s, --syslog=[yes|no] log messages to syslog (default:yes)\n"
" -S, --maxlog=[yes|no] log messages to MaxScale log (default: yes)\n"
" -G, --log_augmentation=0|1 augment messages with the name of the function where\n"
" the message was logged (default: 0). Primarily for \n"
" development purposes.\n"
" -v, --version print version info and exit\n"
" -V, --version-full print full version info and exit\n"
" -?, --help show this help\n"
, progname);
}
/**
* The entry point of each worker thread.
*
* @param arg The thread argument.
*/
void worker_thread_main(void* arg)
{
if (qc_thread_init())
{
/** Init mysql thread context for use with a mysql handle and a parser */
if (mysql_thread_init() == 0)
{
poll_waitevents(arg);
/** Release mysql thread context */
mysql_thread_end();
}
else
{
MXS_ERROR("Could not perform thread initialization for MySQL. Exiting thread.");
}
qc_thread_end();
}
else
{
MXS_ERROR("Could not perform thread initialization for query classifier. Exiting thread.");
}
}
/**
* Deletes a particular signal from a provided signal set.
*
* @param sigset The signal set to be manipulated.
* @param signum The signal to be deleted.
* @param signame The name of the signal.
*
* @return True, if the signal could be deleted from the set, false otherwise.
*/
static bool delete_signal(sigset_t* sigset, int signum, const char* signame)
{
int rc = sigdelset(sigset, signum);
if (rc != 0)
{
int e = errno;
errno = 0;
static const char FORMAT[] = "Failed to delete signal %s from the signal set of MaxScale. Exiting.";
char message[sizeof(FORMAT) + 16]; // Enough for any "SIG..." string.
sprintf(message, FORMAT, signame);
print_log_n_stderr(true, true, message, message, e);
}
return rc == 0;
}
/**
* Disables all signals.
*
* @return True, if all signals could be disabled, false otherwise.
*/
bool disable_signals(void)
{
sigset_t sigset;
if (sigfillset(&sigset) != 0)
{
int e = errno;
errno = 0;
static const char message[] = "Failed to initialize set the signal set for MaxScale. Exiting.";
print_log_n_stderr(true, true, message, message, e);
return false;
}
if (!delete_signal(&sigset, SIGHUP, "SIGHUP"))
{
return false;
}
if (!delete_signal(&sigset, SIGUSR1, "SIGUSR1"))
{
return false;
}
if (!delete_signal(&sigset, SIGTERM, "SIGTERM"))
{
return false;
}
if (!delete_signal(&sigset, SIGSEGV, "SIGSEGV"))
{
return false;
}
if (!delete_signal(&sigset, SIGABRT, "SIGABRT"))
{
return false;
}
if (!delete_signal(&sigset, SIGILL, "SIGILL"))
{
return false;
}
if (!delete_signal(&sigset, SIGFPE, "SIGFPE"))
{
return false;
}
#ifdef SIGBUS
if (!delete_signal(&sigset, SIGBUS, "SIGBUS"))
{
return false;
}
#endif
if (sigprocmask(SIG_SETMASK, &sigset, NULL) != 0)
{
int e = errno;
errno = 0;
static const char message[] = "Failed to set the signal set for MaxScale. Exiting";
print_log_n_stderr(true, true, message, message, e);
return false;
}
return true;
}
/**
* Configures the handling of a particular signal.
*
* @param signum The signal number.
* @param signame The name of the signal.
* @param handler The handler function for the signal.
*
* @return True, if the signal could be configured, false otherwise.
*/
static bool configure_signal(int signum, const char* signame, void (*handler)(int))
{
int rc = signal_set(signum, handler);
if (rc != 0)
{
static const char FORMAT[] = "Failed to set signal handler for %s. Exiting.";
char message[sizeof(FORMAT) + 16]; // Enough for any "SIG..." string.
sprintf(message, FORMAT, signame);
print_log_n_stderr(true, true, message, message, 0);
}
return rc == 0;
}
/**
* Configures signal handling of MaxScale.
*
* @return True, if all signals could be configured, false otherwise.
*/
bool configure_signals(void)
{
if (!configure_signal(SIGHUP, "SIGHUP", sighup_handler))
{
return false;
}
if (!configure_signal(SIGUSR1, "SIGUSR1", sigusr1_handler))
{
return false;
}
if (!configure_signal(SIGTERM, "SIGTERM", sigterm_handler))
{
return false;
}
if (!configure_signal(SIGINT, "SIGINT", sigint_handler))
{
return false;
}
if (!configure_signal(SIGSEGV, "SIGSEGV", sigfatal_handler))
{
return false;
}
if (!configure_signal(SIGABRT, "SIGABRT", sigfatal_handler))
{
return false;
}
if (!configure_signal(SIGILL, "SIGILL", sigfatal_handler))
{
return false;
}
if (!configure_signal(SIGFPE, "SIGFPE", sigfatal_handler))
{
return false;
}
if (!configure_signal(SIGCHLD, "SIGCHLD", sigchld_handler))
{
return false;
}
#ifdef SIGBUS
if (!configure_signal(SIGBUS, "SIGBUS", sigfatal_handler))
{
return false;
}
#endif
return true;
}
/**
* @mainpage
* The main entry point into MaxScale
*
* Logging and error printing
* ---
* What is printed to the terminal is something that the user can understand,
* and/or something what the user can do for. For example, fix configuration.
* More detailed messages are printed to error log, and optionally to trace
* and debug log.
*
* As soon as process switches to daemon process, stderr printing is stopped -
* except when it comes to command-line argument processing.
* This is not an obvious solution because stderr is often directed to somewhere,
* but currently this is the case.
*
* The configuration file is by default /etc/maxscale.cnf
* The name of configuration file and its location can also be specified with a
* command-line argument.
*
* @param argc The argument count
* @param argv The array of arguments themselves
* @return 0 if process exited normally, otherwise a non-zero value is returned
*/
int main(int argc, char **argv)
{
int rc = MAXSCALE_SHUTDOWN;
int l;
int i;
int n;
int ini_rval;
intptr_t thread_id;
int n_threads; /*< number of epoll listener threads */
int n_services;
int eno = 0; /*< local variable for errno */
int opt;
int daemon_pipe[2] = { -1, -1};
bool parent_process;
int child_status;
THREAD* threads = NULL; /*< thread list */
char mysql_home[PATH_MAX + 1];
char* cnf_file_path = NULL; /*< conf file, to be freed */
char* cnf_file_arg = NULL; /*< conf filename from cmd-line arg */
THREAD log_flush_thr;
char* tmp_path;
char* tmp_var;
int option_index;
int *syslog_enabled = &config_get_global_options()->syslog; /** Log to syslog */
int *maxlog_enabled = &config_get_global_options()->maxlog; /** Log with MaxScale */
int *log_to_shm = &config_get_global_options()->log_to_shm; /** Log to shared memory */
ssize_t log_flush_timeout_ms = 0;
sigset_t sigpipe_mask;
sigset_t saved_mask;
bool config_check = false;
bool to_stdout = false;
void (*exitfunp[4])(void) = { mxs_log_finish, cleanup_process_datadir, write_footer, NULL };
*syslog_enabled = 1;
*maxlog_enabled = 1;
*log_to_shm = 0;
maxscale_reset_starttime();
sigemptyset(&sigpipe_mask);
sigaddset(&sigpipe_mask, SIGPIPE);
progname = *argv;
snprintf(datadir, PATH_MAX, "%s", default_datadir);
datadir[PATH_MAX] = '\0';
#if defined(FAKE_CODE)
memset(conn_open, 0, sizeof(bool) * 10240);
memset(dcb_fake_write_errno, 0, sizeof(unsigned char) * 10240);
memset(dcb_fake_write_ev, 0, sizeof(__int32_t) * 10240);
fail_next_backend_fd = false;
fail_next_client_fd = false;
fail_next_accept = 0;
fail_accept_errno = 0;
#endif /* FAKE_CODE */
file_write_header(stderr);
/*<
* Register functions which are called at exit except libmysqld-related,
* which must be registered later to avoid ordering issues.
*/
for (i = 0; exitfunp[i] != NULL; i++)
{
l = atexit(*exitfunp);
if (l != 0)
{
char* fprerr = "Failed to register exit functions for MaxScale";
print_log_n_stderr(false, true, NULL, fprerr, 0);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
}
while ((opt = getopt_long(argc, argv, "dcf:l:vVs:S:?L:D:C:B:U:A:P:G:N:E:",
long_options, &option_index)) != -1)
{
bool succp = true;
switch (opt)
{
case 'd':
/*< Debug mode, maxscale runs in this same process */
daemon_mode = false;
break;
case 'f':
/*<
* Simply copy the conf file argument. Expand or validate
* it when MaxScale home directory is resolved.
*/
if (optarg[0] != '-')
{
cnf_file_arg = strndup(optarg, PATH_MAX);
}
if (cnf_file_arg == NULL)
{
char* logerr = "Configuration file argument "
"identifier \'-f\' was specified but "
"the argument didn't specify\n a valid "
"configuration file or the argument "
"was missing.";
print_log_n_stderr(true, true, logerr, logerr, 0);
usage();
succp = false;
}
break;
case 'v':
rc = EXIT_SUCCESS;
printf("MaxScale %s\n", MAXSCALE_VERSION);
goto return_main;
case 'V':
rc = EXIT_SUCCESS;
printf("MaxScale %s - %s\n", MAXSCALE_VERSION, maxscale_commit);
goto return_main;
case 'l':
if (strncasecmp(optarg, "file", PATH_MAX) == 0)
{
*log_to_shm = false;
log_to_shm_configured = true;
}
else if (strncasecmp(optarg, "shm", PATH_MAX) == 0)
{
*log_to_shm = true;
log_to_shm_configured = true;
}
else if (strncasecmp(optarg, "stdout", PATH_MAX) == 0)
{
to_stdout = true;
*log_to_shm = false;
log_to_shm_configured = true;
}
else
{
char* logerr = "Configuration file argument "
"identifier \'-l\' was specified but "
"the argument didn't specify\n a valid "
"configuration file or the argument "
"was missing.";
print_log_n_stderr(true, true, logerr, logerr, 0);
usage();
succp = false;
}
break;
case 'L':
if (handle_path_arg(&tmp_path, optarg, NULL, true, false))
{
set_logdir(tmp_path);
}
else
{
succp = false;
}
break;
case 'N':
if (handle_path_arg(&tmp_path, optarg, NULL, true, false))
{
set_langdir(tmp_path);
}
else
{
succp = false;
}
break;
case 'P':
if (handle_path_arg(&tmp_path, optarg, NULL, true, true))
{
set_piddir(tmp_path);
}
else
{
succp = false;
}
break;
case 'D':
snprintf(datadir, PATH_MAX, "%s", optarg);
datadir[PATH_MAX] = '\0';
set_datadir(strdup(optarg));
datadir_defined = true;
break;
case 'C':
if (handle_path_arg(&tmp_path, optarg, NULL, true, false))
{
set_configdir(tmp_path);
}
else
{
succp = false;
}
break;
case 'B':
if (handle_path_arg(&tmp_path, optarg, NULL, true, false))
{
set_libdir(tmp_path);
}
else
{
succp = false;
}
break;
case 'A':
if (handle_path_arg(&tmp_path, optarg, NULL, true, true))
{
set_cachedir(tmp_path);
}
else
{
succp = false;
}
break;
case 'E':
if (handle_path_arg(&tmp_path, optarg, NULL, true, false))
{
set_execdir(tmp_path);
}
else
{
succp = false;
}
break;
case 'S':
{
char* tok = strstr(optarg, "=");
if (tok)
{
tok++;
if (tok)
{
*maxlog_enabled = config_truth_value(tok);
maxlog_configured = true;
}
}
else
{
*maxlog_enabled = config_truth_value(optarg);
maxlog_configured = true;
}
}
break;
case 's':
{
char* tok = strstr(optarg, "=");
if (tok)
{
tok++;
if (tok)
{
*syslog_enabled = config_truth_value(tok);
syslog_configured = true;
}
}
else
{
*syslog_enabled = config_truth_value(optarg);
syslog_configured = true;
}
}
break;
case 'U':
if (set_user(optarg) != 0)
{
succp = false;
}
break;
case 'G':
set_log_augmentation(optarg);
break;
case '?':
usage();
rc = EXIT_SUCCESS;
goto return_main;
case 'c':
config_check = true;
break;
default:
usage();
succp = false;
break;
}
if (!succp)
{
rc = MAXSCALE_BADARG;
goto return_main;
}
}
if (config_check)
{
daemon_mode = false;
to_stdout = true;
}
if (!daemon_mode)
{
fprintf(stderr,
"Info : MaxScale will be run in the terminal process.\n");
#if defined(SS_DEBUG)
fprintf(stderr,
"\tSee "
"the log from the following log files : \n\n");
#endif
}
else
{
if (pipe(daemon_pipe) == -1)
{
fprintf(stderr, "Error: Failed to create pipe for inter-process communication: %d %s",
errno, strerror(errno));
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
/*<
* Maxscale must be daemonized before opening files, initializing
* embedded MariaDB and in general, as early as possible.
*/
if (!disable_signals())
{
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
/** Daemonize the process and wait for the child process to notify
* the parent process of its exit status. */
parent_process = gw_daemonize();
if (parent_process)
{
close(daemon_pipe[1]);
int nread = read(daemon_pipe[0], (void*)&child_status, sizeof(int));
close(daemon_pipe[0]);
if (nread == -1)
{
char* logerr = "Failed to read data from child process pipe.";
print_log_n_stderr(true, true, logerr, logerr, errno);
exit(MAXSCALE_INTERNALERROR);
}
else if (nread == 0)
{
/** Child process has exited or closed write pipe */
char* logerr = "No data read from child process pipe.";
print_log_n_stderr(true, true, logerr, logerr, 0);
exit(MAXSCALE_INTERNALERROR);
}
exit(child_status);
}
/** This is the child process and we can close the read end of
* the pipe. */
close(daemon_pipe[0]);
}
/*<
* Set signal handlers for SIGHUP, SIGTERM, SIGINT and critical signals like SIGSEGV.
*/
if (!configure_signals())
{
static const char* logerr = "Failed to configure signal handlers. Exiting.";
print_log_n_stderr(true, true, logerr, logerr, 0);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
eno = pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask);
if (eno != 0)
{
char* logerr = "Failed to initialise signal mask for MaxScale. "
"Exiting.";
print_log_n_stderr(true, true, logerr, logerr, eno);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
if (!utils_init())
{
char* logerr = "Failed to initialise utility library.";
print_log_n_stderr(true, true, logerr, logerr, eno);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
/** OpenSSL initialization */
if (!HAVE_OPENSSL_THREADS)
{
char* logerr = "OpenSSL library does not support multi-threading";
print_log_n_stderr(true, true, logerr, logerr, eno);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
SSL_library_init();
SSL_load_error_strings();
OPENSSL_add_all_algorithms_noconf();
int numlocks = CRYPTO_num_locks();
if ((ssl_locks = malloc(sizeof(SPINLOCK) * (numlocks + 1))) == NULL)
{
char* logerr = "Memory allocation failed";
print_log_n_stderr(true, true, logerr, logerr, eno);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
for (i = 0; i < numlocks + 1; i++)
{
spinlock_init(&ssl_locks[i]);
}
CRYPTO_set_locking_callback(ssl_locking_function);
CRYPTO_set_dynlock_create_callback(ssl_create_dynlock);
CRYPTO_set_dynlock_destroy_callback(ssl_free_dynlock);
CRYPTO_set_dynlock_lock_callback(ssl_lock_dynlock);
#ifdef OPENSSL_1_0
CRYPTO_THREADID_set_callback(maxscale_ssl_id);
#else
CRYPTO_set_id_callback(pthread_self);
#endif
/* register exit function for embedded MySQL library */
l = atexit(libmysqld_done);
if (l != 0)
{
char* fprerr = "Failed to register exit function for\n* "
"embedded MySQL library.\n* Exiting.";
char* logerr = "Failed to register exit function libmysql_done "
"for MaxScale. Exiting.";
print_log_n_stderr(true, true, logerr, fprerr, 0);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
/**
* Resolve the full pathname for configuration file and check for
* read accessibility.
*/
char pathbuf[PATH_MAX + 1];
snprintf(pathbuf, PATH_MAX, "%s", get_configdir());
pathbuf[PATH_MAX] = '\0';
if (pathbuf[strlen(pathbuf) - 1] != '/')
{
strcat(pathbuf, "/");
}
if (!resolve_maxscale_conf_fname(&cnf_file_path, pathbuf, cnf_file_arg))
{
rc = MAXSCALE_BADCONFIG;
goto return_main;
}
if ((ini_rval = ini_parse(cnf_file_path, cnf_preparser, NULL)) != 0)
{
char errorbuffer[STRING_BUFFER_SIZE];
if (ini_rval > 0)
{
snprintf(errorbuffer, sizeof(errorbuffer),
"Error: Failed to pre-parse configuration file. Error on line %d.", ini_rval);
}
else if (ini_rval == -1)
{
snprintf(errorbuffer, sizeof(errorbuffer),
"Error: Failed to pre-parse configuration file. Failed to open file.");
}
else
{
snprintf(errorbuffer, sizeof(errorbuffer),
"Error: Failed to pre-parse configuration file. Memory allocation failed.");
}
print_log_n_stderr(true, true, errorbuffer, errorbuffer, 0);
rc = MAXSCALE_BADCONFIG;
goto return_main;
}
/** Use the cache dir for the mysql folder of the embedded library */
snprintf(mysql_home, PATH_MAX, "%s/mysql", get_cachedir());
mysql_home[PATH_MAX] = '\0';
setenv("MYSQL_HOME", mysql_home, 1);
/**
* Init Log Manager for MaxScale.
*/
{
bool succp;
if (mkdir(get_logdir(), 0777) != 0 && errno != EEXIST)
{
fprintf(stderr,
"Error: Cannot create log directory: %s\n",
default_logdir);
goto return_main;
}
if (!(*syslog_enabled))
{
printf("Syslog logging is disabled.\n");
}
if (!(*maxlog_enabled))
{
printf("MaxScale logging is disabled.\n");
}
mxs_log_set_syslog_enabled(*syslog_enabled);
mxs_log_set_maxlog_enabled(*maxlog_enabled);
mxs_log_target_t log_target = MXS_LOG_TARGET_FS;
if (to_stdout)
{
log_target = MXS_LOG_TARGET_STDOUT;
}
else if (*log_to_shm)
{
log_target = MXS_LOG_TARGET_SHMEM;
}
succp = mxs_log_init(NULL, get_logdir(), log_target);
if (!succp)
{
rc = MAXSCALE_BADCONFIG;
goto return_main;
}
}
if (daemon_mode)
{
if (!change_cwd())
{
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
}
MXS_NOTICE("MariaDB MaxScale %s started", MAXSCALE_VERSION);
MXS_NOTICE("MaxScale is running in process %i", getpid());
/*
* Set the data directory for the mysqld library. We use
* a unique directory name to avoid conflicts if multiple
* instances of MaxScale are being run on the same machine.
*/
if (create_datadir(get_datadir(), datadir))
{
set_process_datadir(datadir);
}
else
{
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("Cannot create data directory '%s': %d %s\n",
datadir, errno, strerror_r(errno, errbuf, sizeof(errbuf)));
goto return_main;
}
if (!daemon_mode)
{
fprintf(stderr,
"Configuration file : %s\n"
"Log directory : %s\n"
"Data directory : %s\n"
"Module directory : %s\n"
"Service cache : %s\n\n",
cnf_file_path,
get_logdir(),
get_datadir(),
get_libdir(),
get_cachedir());
}
MXS_NOTICE("Configuration file: %s", cnf_file_path);
MXS_NOTICE("Log directory: %s", get_logdir());
MXS_NOTICE("Data directory: %s", get_datadir());
MXS_NOTICE("Module directory: %s", get_libdir());
MXS_NOTICE("Service cache: %s", get_cachedir());
if (!config_load(cnf_file_path))
{
char* fprerr =
"Failed to open, read or process the MaxScale configuration "
"file. Exiting. See the error log for details.";
print_log_n_stderr(false, true, fprerr, fprerr, 0);
MXS_ERROR("Failed to open, read or process the MaxScale configuration file %s. "
"Exiting.",
cnf_file_path);
rc = MAXSCALE_BADCONFIG;
goto return_main;
}
GATEWAY_CONF* cnf = config_get_global_options();
ss_dassert(cnf);
if (!qc_init(cnf->qc_name, cnf->qc_args))
{
char* logerr = "Failed to initialise query classifier library.";
print_log_n_stderr(true, true, logerr, logerr, eno);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
if (config_check)
{
MXS_NOTICE("Configuration was successfully verified.");
rc = MAXSCALE_SHUTDOWN;
goto return_main;
}
if (mysql_library_init(0, NULL, NULL))
{
if (!daemon_mode)
{
char* fprerr = "Failed to initialise the MySQL library. "
"Exiting.";
print_log_n_stderr(false, true, fprerr, fprerr, 0);
if (mysql_errno(NULL) == 2000)
{
if (strncmp(mysql_error(NULL),
"Unknown MySQL error",
strlen("Unknown MySQL error")) != 0)
{
fprintf(stderr,
"*\n* Error : MySQL Error should "
"be \"Unknown MySQL error\" "
"instead of\n* %s\n* Hint "
":\n* Ensure that you have "
"MySQL error messages file, errmsg.sys in "
"\n* %s/mysql\n* Ensure that Embedded "
"Server Library version matches "
"exactly with that of the errmsg.sys "
"file.\n*\n",
mysql_error(NULL),
get_langdir());
}
else
{
fprintf(stderr,
"*\n* Error : MySQL Error %d, %s"
"\n*\n",
mysql_errno(NULL),
mysql_error(NULL));
}
}
}
MXS_ERROR("mysql_library_init failed. It is a "
"mandatory component, required by router services and "
"the MaxScale core. Error %d, %s. Exiting.",
mysql_errno(NULL),
mysql_error(NULL));
rc = MAXSCALE_NOLIBRARY;
goto return_main;
}
libmysql_initialized = TRUE;
/** Check if a MaxScale process is already running */
if (pid_file_exists())
{
/** There is a process with the PID of the maxscale.pid file running.
* Assuming that this is an already running MaxScale process, we
* should exit with an error code. */
rc = MAXSCALE_ALREADYRUNNING;
goto return_main;
}
/* Write process pid into MaxScale pidfile */
if (write_pid_file() != 0)
{
rc = MAXSCALE_ALREADYRUNNING;
goto return_main;
}
/** Initialize statistics */
ts_stats_init();
/* Init MaxScale poll system */
poll_init();
/**
* Init mysql thread context for main thread as well. Needed when users
* are queried from backends.
*/
mysql_thread_init();
/** Start all monitors */
monitorStartAll();
/** Start the services that were created above */
n_services = serviceStartAll();
if (n_services == 0)
{
char* logerr = "Failed to start all MaxScale services. Exiting.";
print_log_n_stderr(true, true, logerr, logerr, 0);
rc = MAXSCALE_NOSERVICES;
goto return_main;
}
/*<
* Start periodic log flusher thread.
*/
log_flush_timeout_ms = 1000;
if (thread_start(&log_flush_thr, log_flush_cb, (void *) &log_flush_timeout_ms) == NULL)
{
char* logerr = "Failed to start log flushing thread.";
print_log_n_stderr(true, true, logerr, logerr, 0);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
/*
* Start the housekeeper thread
*/
hkinit();
/*<
* Start the polling threads, note this is one less than is
* configured as the main thread will also poll.
*/
n_threads = config_threadcount();
threads = calloc(n_threads, sizeof(THREAD));
/*<
* Start server threads.
*/
for (thread_id = 0; thread_id < n_threads - 1; thread_id++)
{
if (thread_start(&threads[thread_id], worker_thread_main,
(void *)(thread_id + 1)) == NULL)
{
char* logerr = "Failed to start worker thread.";
print_log_n_stderr(true, true, logerr, logerr, 0);
rc = MAXSCALE_INTERNALERROR;
goto return_main;
}
}
MXS_NOTICE("MaxScale started with %d server threads.", config_threadcount());
/**
* Successful start, notify the parent process that it can exit.
*/
ss_dassert(rc == MAXSCALE_SHUTDOWN);
if (daemon_mode)
{
write_child_exit_code(daemon_pipe[1], rc);
}
/*<
* Serve clients.
*/
poll_waitevents((void *)0);
/*<
* Wait server threads' completion.
*/
for (thread_id = 0; thread_id < n_threads - 1; thread_id++)
{
thread_wait(threads[thread_id]);
}
/*<
* Wait the flush thread.
*/
thread_wait(log_flush_thr);
/*< Stop all the monitors */
monitorStopAll();
log_exit_status();
MXS_NOTICE("MaxScale is shutting down.");
/** Release mysql thread context*/
mysql_thread_end();
qc_end();
utils_end();
cleanup_process_datadir();
MXS_NOTICE("MaxScale shutdown completed.");
unload_all_modules();
/* Remove Pidfile */
unlock_pidfile();
unlink_pidfile();
return_main:
mxs_log_flush_sync();
if (daemon_mode && rc != MAXSCALE_SHUTDOWN)
{
/** Notify the parent process that an error has occurred */
write_child_exit_code(daemon_pipe[1], rc);
}
if (threads)
{
free(threads);
}
if (cnf_file_path)
{
free(cnf_file_path);
}
return rc;
} /*< End of main */
/*<
* Shutdown MaxScale server
*/
void
shutdown_server()
{
service_shutdown();
poll_shutdown();
hkshutdown();
memlog_flush_all();
log_flush_shutdown();
}
static void log_flush_shutdown(void)
{
do_exit = TRUE;
}
/**
* Periodic log flusher to ensure that log buffers are
* written to log even if block buffer used for temporarily
* storing log contents are not full.
*
* @param arg - Flush frequency in milliseconds
*
*
*/
static void log_flush_cb(void* arg)
{
ssize_t timeout_ms = *(ssize_t *)arg;
struct timespec ts1;
ts1.tv_sec = timeout_ms / 1000;
ts1.tv_nsec = (timeout_ms % 1000) * 1000000;
MXS_NOTICE("Started MaxScale log flusher.");
while (!do_exit)
{
mxs_log_flush();
nanosleep(&ts1, NULL);
}
MXS_NOTICE("Finished MaxScale log flusher.");
}
static void unlock_pidfile()
{
if (pidfd != PIDFD_CLOSED)
{
if (flock(pidfd, LOCK_UN | LOCK_NB) != 0)
{
char logbuf[STRING_BUFFER_SIZE + PATH_MAX];
char* logerr = "Failed to unlock PID file '%s'.";
snprintf(logbuf, sizeof(logbuf), logerr, pidfile);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
}
close(pidfd);
}
}
/**
* Unlink pid file, called at program exit
*/
static void unlink_pidfile(void)
{
if (strlen(pidfile))
{
if (unlink(pidfile))
{
char errbuf[STRERROR_BUFLEN];
fprintf(stderr,
"MaxScale failed to remove pidfile %s: error %d, %s\n",
pidfile,
errno,
strerror_r(errno, errbuf, sizeof(errbuf)));
}
}
}
/**
* Check if the maxscale.pid file exists and has a valid PID in it. If one has already been
* written and a MaxScale process is running, this instance of MaxScale should shut down.
* @return True if the conditions for starting MaxScale are not met and false if
* no PID file was found or there is no process running with the PID of the maxscale.pid
* file. If false is returned, this process should continue normally.
*/
bool pid_file_exists()
{
char pathbuf[PATH_MAX + 1];
char logbuf[STRING_BUFFER_SIZE + PATH_MAX];
char pidbuf[STRING_BUFFER_SIZE];
pid_t pid;
bool lock_failed = false;
snprintf(pathbuf, PATH_MAX, "%s/maxscale.pid", get_piddir());
pathbuf[PATH_MAX] = '\0';
if (access(pathbuf, F_OK) != 0)
{
return false;
}
if (access(pathbuf, R_OK) == 0)
{
int fd, b;
if ((fd = open(pathbuf, O_RDWR)) == -1)
{
char* logerr = "Failed to open PID file '%s'.";
snprintf(logbuf, sizeof(logbuf), logerr, pathbuf);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
return true;
}
if (flock(fd, LOCK_EX | LOCK_NB))
{
if (errno != EWOULDBLOCK)
{
char* logerr = "Failed to lock PID file '%s'.";
snprintf(logbuf, sizeof(logbuf), logerr, pathbuf);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
close(fd);
return true;
}
lock_failed = true;
}
pidfd = fd;
b = read(fd, pidbuf, sizeof(pidbuf));
if (b == -1)
{
char* logerr = "Failed to read from PID file '%s'.";
snprintf(logbuf, sizeof(logbuf), logerr, pathbuf);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
unlock_pidfile();
return true;
}
else if (b == 0)
{
/** Empty file */
char* logerr = "PID file read from '%s'. File was empty.\n"
"If the file is the correct PID file and no other MaxScale processes "
"are running, please remove it manually and start MaxScale again.";
snprintf(logbuf, sizeof(logbuf), logerr, pathbuf);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
unlock_pidfile();
return true;
}
pidbuf[b < sizeof(pidbuf) ? b : sizeof(pidbuf) - 1] = '\0';
pid = strtol(pidbuf, NULL, 0);
if (pid < 1)
{
/** Bad PID */
char* logerr = "PID file read from '%s'. File contents not valid.\n"
"If the file is the correct PID file and no other MaxScale processes "
"are running, please remove it manually and start MaxScale again.";
snprintf(logbuf, sizeof(logbuf), logerr, pathbuf);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
unlock_pidfile();
return true;
}
if (kill(pid, 0) == -1)
{
if (errno == ESRCH)
{
/** no such process, old PID file */
if (lock_failed)
{
char* logerr =
"Locking the PID file '%s' failed. "
"Read PID from file and no process found with PID %d. "
"Confirm that no other process holds the lock on the PID file.";
snprintf(logbuf, sizeof(logbuf), logerr, pathbuf, pid);
print_log_n_stderr(true, true, logbuf, logbuf, 0);
close(fd);
}
return lock_failed;
}
else
{
char* logerr = "Failed to check the existence of process %d read from file '%s'";
snprintf(logbuf, sizeof(logbuf), logerr, pid, pathbuf);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
unlock_pidfile();
}
}
else
{
char* logerr =
"MaxScale is already running. Process id: %d. "
"Use another location for the PID file to run multiple "
"instances of MaxScale on the same machine.";
snprintf(logbuf, sizeof(logbuf), logerr, pid);
print_log_n_stderr(true, true, logbuf, logbuf, 0);
unlock_pidfile();
}
}
else
{
char* logerr = "Cannot open PID file '%s', no read permissions. "
"Please confirm that the user running MaxScale has read permissions on the file.";
snprintf(logbuf, sizeof(logbuf), logerr, pathbuf);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
}
return true;
}
/**
* Write process pid into pidfile anc close it
* Parameters:
* @param home_dir The MaxScale home dir
* @return 0 on success, 1 on failure
*
*/
static int write_pid_file()
{
char logbuf[STRING_BUFFER_SIZE + PATH_MAX];
char pidstr[STRING_BUFFER_SIZE];
snprintf(pidfile, PATH_MAX, "%s/maxscale.pid", get_piddir());
if (pidfd == PIDFD_CLOSED)
{
int fd = -1;
fd = open(pidfile, O_WRONLY | O_CREAT, 0777);
if (fd == -1)
{
char* logerr = "Failed to open PID file '%s'.";
snprintf(logbuf, sizeof(logbuf), logerr, pidfile);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
return -1;
}
if (flock(fd, LOCK_EX | LOCK_NB))
{
if (errno == EWOULDBLOCK)
{
snprintf(logbuf, sizeof(logbuf),
"Failed to lock PID file '%s', another process is holding a lock on it. "
"Please confirm that no other MaxScale process is using the same "
"PID file location.", pidfile);
}
else
{
snprintf(logbuf, sizeof(logbuf), "Failed to lock PID file '%s'.", pidfile);
}
print_log_n_stderr(true, true, logbuf, logbuf, errno);
close(fd);
return -1;
}
pidfd = fd;
}
/* truncate pidfile content */
if (ftruncate(pidfd, 0))
{
char* logerr = "MaxScale failed to truncate PID file '%s'.";
snprintf(logbuf, sizeof(logbuf), logerr, pidfile);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
unlock_pidfile();
return -1;
}
snprintf(pidstr, sizeof(pidstr) - 1, "%d", getpid());
if (pwrite(pidfd, pidstr, strlen(pidstr), 0) != (ssize_t)strlen(pidstr))
{
char* logerr = "MaxScale failed to write into PID file '%s'.";
snprintf(logbuf, sizeof(logbuf), logerr, pidfile);
print_log_n_stderr(true, true, logbuf, logbuf, errno);
unlock_pidfile();
return -1;
}
/* success */
return 0;
}
bool handle_path_arg(char** dest, char* path, char* arg, bool rd, bool wr)
{
char pathbuffer[PATH_MAX + 2];
char* errstr;
bool rval = false;
if (path == NULL && arg == NULL)
{
return rval;
}
if (path)
{
snprintf(pathbuffer, PATH_MAX, "%s", path);
if (pathbuffer[strlen(path) - 1] != '/')
{
strcat(pathbuffer, "/");
}
if (arg && strlen(pathbuffer) + strlen(arg) + 1 < PATH_MAX)
{
strcat(pathbuffer, arg);
}
if ((errstr = check_dir_access(pathbuffer, rd, wr)) == NULL)
{
*dest = strdup(pathbuffer);
rval = true;
}
else
{
print_log_n_stderr(true, true, errstr, errstr, 0);
free(errstr);
errstr = NULL;
}
}
return rval;
}
void set_log_augmentation(const char* value)
{
// Command line arguments are handled first, thus command line argument
// has priority.
static bool augmentation_set = false;
if (!augmentation_set)
{
mxs_log_set_augmentation(atoi(value));
augmentation_set = true;
}
}
/**
* Pre-parse the configuration file for various directory paths.
* @param data Parameter passed by inih
* @param section Section name
* @param name Parameter name
* @param value Parameter value
* @return 0 on error, 1 when successful
*/
static int cnf_preparser(void* data, const char* section, const char* name, const char* value)
{
GATEWAY_CONF* cnf = config_get_global_options();
char *tmp;
/** These are read from the configuration file. These will not override
* command line parameters but will override default values. */
if (strcasecmp(section, "maxscale") == 0)
{
if (strcmp(name, "logdir") == 0)
{
if (strcmp(get_logdir(), default_logdir) == 0)
{
if (handle_path_arg(&tmp, (char*)value, NULL, true, true))
{
set_logdir(tmp);
}
else
{
return 0;
}
}
}
else if (strcmp(name, "libdir") == 0)
{
if (strcmp(get_libdir(), default_libdir) == 0)
{
if (handle_path_arg(&tmp, (char*)value, NULL, true, false))
{
set_libdir(tmp);
}
else
{
return 0;
}
}
}
else if (strcmp(name, "piddir") == 0)
{
if (strcmp(get_piddir(), default_piddir) == 0)
{
if (handle_path_arg(&tmp, (char*)value, NULL, true, true))
{
set_piddir(tmp);
}
else
{
return 0;
}
}
}
else if (strcmp(name, "datadir") == 0)
{
if (!datadir_defined)
{
if (handle_path_arg(&tmp, (char*)value, NULL, true, false))
{
snprintf(datadir, PATH_MAX, "%s", tmp);
datadir[PATH_MAX] = '\0';
set_datadir(tmp);
datadir_defined = true;
}
else
{
return 0;
}
}
}
else if (strcmp(name, "cachedir") == 0)
{
if (strcmp(get_cachedir(), default_cachedir) == 0)
{
if (handle_path_arg((char**)&tmp, (char*)value, NULL, true, false))
{
set_cachedir(tmp);
}
else
{
return 0;
}
}
}
else if (strcmp(name, "language") == 0)
{
if (strcmp(get_langdir(), default_langdir) == 0)
{
if (handle_path_arg((char**)&tmp, (char*)value, NULL, true, false))
{
set_langdir(tmp);
}
else
{
return 0;
}
}
}
else if (strcmp(name, "execdir") == 0)
{
if (strcmp(get_execdir(), default_execdir) == 0)
{
if (handle_path_arg((char**)&tmp, (char*)value, NULL, true, false))
{
set_execdir(tmp);
}
else
{
return 0;
}
}
}
else if (strcmp(name, "syslog") == 0)
{
if (!syslog_configured)
{
cnf->syslog = config_truth_value((char*)value);
}
}
else if (strcmp(name, "maxlog") == 0)
{
if (!maxlog_configured)
{
cnf->maxlog = config_truth_value((char*)value);
}
}
else if (strcmp(name, "log_augmentation") == 0)
{
set_log_augmentation(value);
}
else if (strcmp(name, "log_to_shm") == 0)
{
if (!log_to_shm_configured)
{
cnf->log_to_shm = config_truth_value((char*)value);
}
}
}
return 1;
}
static int set_user(const char* user)
{
errno = 0;
struct passwd *pwname;
int rval;
pwname = getpwnam(user);
if (pwname == NULL)
{
char errbuf[STRERROR_BUFLEN];
printf("Error: Failed to retrieve user information for '%s': %d %s\n",
user, errno, errno == 0 ? "User not found" : strerror_r(errno, errbuf, sizeof(errbuf)));
return -1;
}
rval = setgid(pwname->pw_gid);
if (rval != 0)
{
char errbuf[STRERROR_BUFLEN];
printf("Error: Failed to change group to '%d': %d %s\n",
pwname->pw_gid, errno, strerror_r(errno, errbuf, sizeof(errbuf)));
return rval;
}
rval = setuid(pwname->pw_uid);
if (rval != 0)
{
char errbuf[STRERROR_BUFLEN];
printf("Error: Failed to change user to '%s': %d %s\n",
pwname->pw_name, errno, strerror_r(errno, errbuf, sizeof(errbuf)));
return rval;
}
if (prctl(PR_GET_DUMPABLE) == 0)
{
if (prctl(PR_SET_DUMPABLE , 1) == -1)
{
char errbuf[STRERROR_BUFLEN];
printf("Error: Failed to set dumpable flag on for the process '%s': %d %s\n",
pwname->pw_name, errno, strerror_r(errno, errbuf, sizeof(errbuf)));
return -1;
}
}
#ifdef SS_DEBUG
else
{
printf("Running MaxScale as: %s %d:%d\n", pwname->pw_name, pwname->pw_uid, pwname->pw_gid);
}
#endif
return rval;
}
/**
* Write the exit status of the child process to the parent process.
* @param fd File descriptor to write to
* @param code Exit status of the child process
*/
void write_child_exit_code(int fd, int code)
{
/** Notify the parent process that an error has occurred */
write(fd, &code, sizeof (int));
close(fd);
}
/**
* Change the current working directory
*
* Change the current working directory to the log directory. If this is not
* possible, try to change location to the file system root. If this also fails,
* return with an error.
* @return True if changing the current working directory was successful.
*/
static bool change_cwd()
{
bool rval = true;
if (chdir(get_logdir()) != 0)
{
char errbuf[STRERROR_BUFLEN];
MXS_ERROR("Failed to change working directory to '%s': %d, %s. "
"Trying to change working directory to '/'.",
get_logdir(), errno, strerror_r(errno, errbuf, sizeof (errbuf)));
if (chdir("/") != 0)
{
MXS_ERROR("Failed to change working directory to '/': %d, %s",
errno, strerror_r(errno, errbuf, sizeof (errbuf)));
rval = false;
}
else
{
MXS_WARNING("Using '/' instead of '%s' as the current working directory.",
get_logdir());
}
}
else
{
MXS_NOTICE("Working directory: %s", get_logdir());
}
return rval;
}
/**
* @brief Log a message about the last received signal
*/
static void log_exit_status()
{
switch (last_signal)
{
case SIGTERM:
MXS_NOTICE("MaxScale received signal SIGTERM. Exiting.");
break;
case SIGINT:
MXS_NOTICE("MaxScale received signal SIGINT. Exiting.");
break;
default:
break;
}
}