summaryrefslogtreecommitdiff
path: root/project2/sql/rdbmsDataSource.cpp
blob: bf69dcd7995e55f53d59c5da0524f7e64b2c6010 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#include <pch.hpp>
#include "rdbmsDataSource.h"
#include "connectionLoader.h"
#include <sys/utsname.h>
#include "logger.h"
#include "scripts.h"
#include <errno.h>
#include <boost/foreach.hpp>

SimpleMessageException(UnknownConnectionProvider);

/// Specialized ElementLoader for instances of RdbmsDataSource; handles persistent DB connections
class RdbmsDataSourceLoader : public ElementLoader::For<RdbmsDataSource> {
	public:
		void onIdle()
		{
			// Disconnect all cached database connections
			RdbmsDataSource::dbhosts.clear();
		}
		static bool isConnectionExpired(const RdbmsDataSource::DBHosts::value_type & con)
		{
			return con.second->isExpired();
		}
		void onPeriodic()
		{
			// Disconnect expired database connections
			RdbmsDataSource::DBHosts::iterator i;
			while ((i = std::find_if(RdbmsDataSource::dbhosts.begin(), RdbmsDataSource::dbhosts.end(), isConnectionExpired)) != RdbmsDataSource::dbhosts.end()) {
				RdbmsDataSource::dbhosts.erase(i);
			}
		}
		void onIteration()
		{
			RdbmsDataSource::changedDSNs.clear();
		}
};
DECLARE_CUSTOM_LOADER("rdbmsdatasource", RdbmsDataSourceLoader);

RdbmsDataSource::DBHosts RdbmsDataSource::dbhosts;
RdbmsDataSource::FailedHosts RdbmsDataSource::failedhosts;
RdbmsDataSource::DSNSet RdbmsDataSource::changedDSNs;

RdbmsDataSource::RdbmsDataSource(ScriptNodePtr p) :
	DataSource(p),
	masterDsn(p->child("masterdsn")),
	preferLocal(p->value("preferlocal", true, NULL))
{
	BOOST_FOREACH(ScriptNodePtr node, p->childrenIn("readonly")) {
		roDSNs.insert(ReadonlyDSNs::value_type(node->value("host", NULL).as<std::string>(), node));
	}
}

RdbmsDataSource::~RdbmsDataSource()
{
}

const DB::Connection &
RdbmsDataSource::getWritable() const
{
	ConnectionPtr master = connectTo(masterDsn);
	if (!master->txOpen) {
		master->connection->beginTx();
		master->txOpen = true;
	}
	changedDSNs.insert(name);
	return *master->connection;
}

const DB::Connection &
RdbmsDataSource::getReadonly() const
{
	if (changedDSNs.find(name) != changedDSNs.end()) {
		return *connectTo(masterDsn)->connection;
	}
	if (localhost.length() == 0 && preferLocal) {
		struct utsname name;
		if (uname(&name)) {
			Logger()->messagef(LOG_WARNING, "%s: Unable to determine local host name (%d:%s)",
					__PRETTY_FUNCTION__, errno, strerror(errno));
			localhost = "unknown";
		}
		else {
			localhost = name.nodename;
		}
	}
	if (preferLocal) {
		ReadonlyDSNs::const_iterator ro = roDSNs.find(localhost);
		try {
			if (ro == roDSNs.end()) {
				Logger()->messagef(LOG_INFO, "%s: No database host matches local host name (%s) Will use master DSN",
						__PRETTY_FUNCTION__, localhost.c_str());
				return *connectTo(masterDsn)->connection;
			}
			return *connectTo(ro->second)->connection;
		}
		catch (...) {
			// Failed to connect to a preferred DB... carry on and try the others...
		}
	}
	BOOST_FOREACH(ReadonlyDSNs::value_type db, roDSNs) {
		try {
			return *connectTo(db.second)->connection;
		}
		catch (...) {
		}
	}
	return *connectTo(masterDsn)->connection;
}

void
RdbmsDataSource::commit()
{
	DBHosts::const_iterator m = dbhosts.find(masterDsn);
	if (m != dbhosts.end() && m->second->txOpen) {
		m->second->connection->commitTx();
		m->second->txOpen = false;
	}
}

void
RdbmsDataSource::rollback()
{
	DBHosts::const_iterator m = dbhosts.find(masterDsn);
	if (m != dbhosts.end() && m->second->txOpen) {
		m->second->connection->rollbackTx();
		m->second->txOpen = false;
	}
	changedDSNs.erase(name);
}

RdbmsDataSource::ConnectionPtr
RdbmsDataSource::connectTo(const ConnectionInfo & dsn)
{
	FailedHosts::iterator dbf = failedhosts.find(dsn);
	if (dbf != failedhosts.end()) {
		if (time(NULL) - 20 > dbf->second.FailureTime) {
			failedhosts.erase(dbf);
		}
		else {
			throw dbf->second;
		}
	}
	DBHosts::const_iterator dbi = dbhosts.find(dsn);
	if (dbi != dbhosts.end()) {
		try {
			dbi->second->connection->ping();
			dbi->second->touch();
			return dbi->second;
		}
		catch (...) {
			// Connection in failed state
			Logger()->messagef(LOG_DEBUG, "%s: Cached connection failed", __PRETTY_FUNCTION__);
		}
	}
	
	try {
		ConnectionPtr db = ConnectionPtr(new RdbmsConnection(dsn.connect(), 300));
		dbhosts[dsn] = db;
		db->touch();
		return db;
	}
	catch (const DB::ConnectionError & e) {
		Logger()->messagef(LOG_NOTICE, "%s: connection error message to '%s' -> %s",
				__PRETTY_FUNCTION__, dsn.dsn.c_str(), e.what());
		failedhosts.insert(FailedHosts::value_type(dsn, e));
		throw;
	}
}

RdbmsDataSource::RdbmsConnection::RdbmsConnection(const DB::Connection * con, time_t kat) :
	connection(con),
	txOpen(false),
	lastUsedTime(0),
	keepAliveTime(kat)
{
}

RdbmsDataSource::RdbmsConnection::~RdbmsConnection()
{
	connection->finish();
	delete connection;
}

void
RdbmsDataSource::RdbmsConnection::touch() const
{
	time(&lastUsedTime);
}

bool
RdbmsDataSource::RdbmsConnection::isExpired() const
{
	return (time(NULL) > lastUsedTime + keepAliveTime);
}

RdbmsDataSource::ConnectionInfo::ConnectionInfo(ScriptNodePtr node) :
	dsn(node->value("dsn", NULL).as<std::string>()),
	typeId(InstanceMap<ConnectionLoader, std::string>::Get<UnknownConnectionProvider>(node->value("provider", NULL)))
{
}

DB::Connection *
RdbmsDataSource::ConnectionInfo::connect() const
{
	return typeId->create(dsn);
}

bool
RdbmsDataSource::ConnectionInfo::operator<(const RdbmsDataSource::ConnectionInfo & other) const
{
	return ((typeId < other.typeId) || ((typeId == other.typeId) && (dsn < other.dsn)));
}