2009-04-28 Gonzalo Paniagua Javier <gonzalo@novell.com>
[mono.git] / mcs / class / Mono.Data.Tds / Mono.Data.Tds.Protocol / TdsConnectionPool.cs
1 //
2 // Mono.Data.TdsClient.TdsConnectionPool.cs
3 //
4 // Author:
5 //   Lluis Sanchez Gual (lluis@ximian.com)
6 //   Christian Hergert (christian.hergert@gmail.com)
7 //   Gonzalo Paniagua Javier (gonzalo@novell.com)
8 //
9 // Copyright (C) 2004 Novell, Inc.
10 // Copyright (C) 2009 Novell, Inc.
11
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System;
34 using System.Collections;
35 using System.Text;
36 using System.Threading;
37
38 namespace Mono.Data.Tds.Protocol 
39 {
40         public class TdsConnectionPoolManager
41         {
42                 Hashtable pools = Hashtable.Synchronized (new Hashtable ());
43                 TdsVersion version;
44                 
45                 public TdsConnectionPoolManager (TdsVersion version)
46                 {
47                         this.version = version;
48                 }
49                 
50                 public TdsConnectionPool GetConnectionPool (string connectionString, TdsConnectionInfo info)
51                 {
52                         TdsConnectionPool pool = (TdsConnectionPool) pools [connectionString];
53                         if (pool == null) {
54                                 pools [connectionString] = new TdsConnectionPool (this, info);
55                                 pool = (TdsConnectionPool) pools [connectionString];
56                         }
57                         return pool;
58                 }
59
60                 public TdsConnectionPool GetConnectionPool (string connectionString)
61                 {
62                         return (TdsConnectionPool) pools [connectionString];
63                 }
64
65                 public virtual Tds CreateConnection (TdsConnectionInfo info)
66                 {
67                         switch (version)
68                         {
69                                 case TdsVersion.tds42:
70                                         return new Tds42 (info.DataSource, info.Port, info.PacketSize, info.Timeout);
71                                 case TdsVersion.tds50:
72                                         return new Tds50 (info.DataSource, info.Port, info.PacketSize, info.Timeout);
73                                 case TdsVersion.tds70:
74                                         return new Tds70 (info.DataSource, info.Port, info.PacketSize, info.Timeout);
75                                 case TdsVersion.tds80:
76                                         return new Tds80 (info.DataSource, info.Port, info.PacketSize, info.Timeout);
77                         }
78                         throw new NotSupportedException ();
79                 }
80
81                 public IDictionary GetConnectionPool ()
82                 {
83                         return pools;
84                 }
85         }
86         
87         public class TdsConnectionInfo
88         {
89                 public TdsConnectionInfo (string dataSource, int port, int packetSize, int timeout, int minSize, int maxSize)
90                 {
91                         DataSource = dataSource;
92                         Port = port;
93                         PacketSize = packetSize;
94                         Timeout = timeout;
95                         PoolMinSize = minSize;
96                         PoolMaxSize = maxSize;
97                 }
98                 
99                 public string DataSource;
100                 public int Port;
101                 public int PacketSize;
102                 public int Timeout;
103                 public int PoolMinSize;
104                 public int PoolMaxSize;
105
106                 public override string ToString ()
107                 {
108                         StringBuilder sb = new StringBuilder ();
109                         sb.AppendFormat ("DataSouce: {0}\n", DataSource);
110                         sb.AppendFormat ("Port: {0}\n", Port);
111                         sb.AppendFormat ("PacketSize: {0}\n", PacketSize);
112                         sb.AppendFormat ("Timeout: {0}\n", Timeout);
113                         sb.AppendFormat ("PoolMinSize: {0}\n", PoolMinSize);
114                         sb.AppendFormat ("PoolMaxSize: {0}", PoolMaxSize);
115                         return sb.ToString ();
116                 }
117         }
118
119         public class TdsConnectionPool
120         {
121                 TdsConnectionInfo info;
122                 bool no_pooling;
123                 TdsConnectionPoolManager manager;
124                 Queue available;
125                 ArrayList conns;
126                 
127                 public TdsConnectionPool (TdsConnectionPoolManager manager, TdsConnectionInfo info)
128                 {
129                         this.info = info;
130                         this.manager = manager;
131                         conns = new ArrayList (info.PoolMaxSize);
132                         available = new Queue (info.PoolMaxSize);
133                         InitializePool ();
134                 }
135
136                 void InitializePool ()
137                 {
138                         /* conns.Count might not be 0 when we are resetting the connection pool */
139                         for (int i = conns.Count; i < info.PoolMinSize; i++) {
140                                 try {
141                                         Tds t = manager.CreateConnection (info);
142                                         conns.Add (t);
143                                         available.Enqueue (t);
144                                 } catch {
145                                         // Ignore. GetConnection will throw again.
146                                 }
147                         }
148                 }
149
150                 public bool Pooling {
151                         get { return !no_pooling; }
152                         set { no_pooling = !value; }
153                 }
154
155                 #region Methods
156
157                 int in_progress;
158                 public Tds GetConnection ()
159                 {
160                         if (no_pooling)
161                                 return manager.CreateConnection (info);
162
163                         Tds result = null;
164                         bool create_new;
165                         int retries = info.PoolMaxSize * 2;
166 retry:
167                         while (result == null) {
168                                 create_new = false;
169                                 lock (available) {
170                                         if (available.Count > 0) {
171                                                 result = (Tds) available.Dequeue ();
172                                                 break; // .. and do the reset out of the loop
173                                         }
174                                         Monitor.Enter (conns);
175                                         try {
176                                                 if (conns.Count >= info.PoolMaxSize - in_progress) {
177                                                         Monitor.Exit (conns);
178                                                         bool got_lock = Monitor.Wait (available, info.Timeout * 1000);
179                                                         if (!got_lock) {
180                                                                 throw new InvalidOperationException (
181                                                                         "Timeout expired. The timeout period elapsed before a " +
182                                                                         "connection could be obtained. A possible explanation " +
183                                                                         "is that all the connections in the pool are in use, " +
184                                                                         "and the maximum pool size is reached.");
185                                                         } else if (available.Count > 0) {
186                                                                 result = (Tds) available.Dequeue ();
187                                                                 break; // .. and do the reset out of the loop
188                                                         }
189                                                         continue;
190                                                 } else {
191                                                         create_new = true;
192                                                         in_progress++;
193                                                 }
194                                         } finally {
195                                                 Monitor.Exit (conns); // Exiting if not owned is ok < 2.x
196                                         }
197                                 }
198                                 if (create_new) {
199                                         try {
200                                                 result = manager.CreateConnection (info);
201                                                 lock (conns)
202                                                         conns.Add (result);
203                                                 return result;
204                                         } finally {
205                                                 lock (available)
206                                                         in_progress--;
207                                         }
208                                 }
209                         }
210
211                         bool remove_cnc = true;
212                         Exception exc = null;
213                         try {
214                                 remove_cnc = (!result.IsConnected || !result.Reset ());
215                         } catch (Exception e) {
216                                 remove_cnc = true;
217                                 exc = e;
218                         }
219                         if (remove_cnc) {
220                                 lock (conns)
221                                         conns.Remove (result);
222                                 result.Disconnect ();
223                                 retries--;
224                                 if (retries == 0)
225                                         throw exc;
226                                 goto retry;
227                         }
228                         return result;
229                 }
230
231                 public void ReleaseConnection (Tds connection)
232                 {
233                         if (connection == null)
234                                 return;
235                         if (no_pooling) {
236                                 connection.Disconnect ();
237                                 return;
238                         }
239
240                         if (connection.poolStatus == 2) {
241                                 lock (conns)
242                                         conns.Remove (connection);
243                                 connection.Disconnect ();
244                                 connection = null;
245                         }
246                         lock (available) {
247                                 if (connection != null) // connection is still open
248                                         available.Enqueue (connection);
249                                 // We pulse even if we don't queue, because null means that there's a slot
250                                 // available in 'conns'
251                                 Monitor.Pulse (available);
252                         }
253                 }
254
255 #if NET_2_0
256                 public void ResetConnectionPool ()
257                 {
258                         lock (available) {
259                                 lock (conns) {
260                                         Tds tds;
261                                         int i;
262                                         for (i = conns.Count - 1; i >= 0; i++) {
263                                                 tds = (Tds) conns [i];
264                                                 tds.poolStatus = 2; // 2 -> disconnect me upon release
265                                         }
266                                         for (i = available.Count - 1; i >= 0; i--) {
267                                                 tds = (Tds) available.Dequeue ();
268                                                 tds.Disconnect ();
269                                                 conns.Remove (tds);
270                                         }
271                                         available.Clear ();
272                                         InitializePool ();
273                                 }
274                                 Monitor.PulseAll (available);
275                         }
276                 }
277 #endif
278                 #endregion // Methods
279         }
280 }
281