File: DbConnectionPoolCounters.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (325 lines) | stat: -rw-r--r-- 19,834 bytes parent folder | download | duplicates (6)
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//------------------------------------------------------------------------------
// <copyright file="DbConnectionPoolCounters.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
//------------------------------------------------------------------------------

namespace System.Data.ProviderBase {

    using System;
    using System.Collections;
    using System.Data.Common;
    using System.Diagnostics;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime.ConstrainedExecution;
    using System.Security;
    using System.Security.Permissions;
    using System.Security.Principal;
    using System.Runtime.Versioning;

    internal abstract class DbConnectionPoolCounters {
        private static class CreationData {

            static internal readonly CounterCreationData HardConnectsPerSecond = new CounterCreationData(
                                                                        "HardConnectsPerSecond",
                                                                        "The number of actual connections per second that are being made to servers",
                                                                        PerformanceCounterType.RateOfCountsPerSecond32);

            static internal readonly CounterCreationData HardDisconnectsPerSecond = new CounterCreationData(
                                                                        "HardDisconnectsPerSecond",
                                                                        "The number of actual disconnects per second that are being made to servers",
                                                                        PerformanceCounterType.RateOfCountsPerSecond32);

            static internal readonly CounterCreationData SoftConnectsPerSecond = new CounterCreationData(
                                                                        "SoftConnectsPerSecond",
                                                                        "The number of connections we get from the pool per second",
                                                                        PerformanceCounterType.RateOfCountsPerSecond32);

            static internal readonly CounterCreationData SoftDisconnectsPerSecond = new CounterCreationData(
                                                                        "SoftDisconnectsPerSecond",
                                                                        "The number of connections we return to the pool per second",
                                                                        PerformanceCounterType.RateOfCountsPerSecond32);

            static internal readonly CounterCreationData NumberOfNonPooledConnections = new CounterCreationData(
                                                                        "NumberOfNonPooledConnections",
                                                                        "The number of connections that are not using connection pooling",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfPooledConnections = new CounterCreationData(
                                                                        "NumberOfPooledConnections",
                                                                        "The number of connections that are managed by the connection pooler",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfActiveConnectionPoolGroups = new CounterCreationData(
                                                                        "NumberOfActiveConnectionPoolGroups",
                                                                        "The number of unique connection strings",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfInactiveConnectionPoolGroups = new CounterCreationData(
                                                                        "NumberOfInactiveConnectionPoolGroups",
                                                                        "The number of unique connection strings waiting for pruning",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfActiveConnectionPools = new CounterCreationData(
                                                                        "NumberOfActiveConnectionPools",
                                                                        "The number of connection pools",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfInactiveConnectionPools = new CounterCreationData(
                                                                        "NumberOfInactiveConnectionPools",
                                                                        "The number of connection pools",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfActiveConnections = new CounterCreationData(
                                                                        "NumberOfActiveConnections",
                                                                        "The number of connections currently in-use",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfFreeConnections = new CounterCreationData(
                                                                        "NumberOfFreeConnections",
                                                                        "The number of connections currently available for use",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfStasisConnections = new CounterCreationData(
                                                                        "NumberOfStasisConnections",
                                                                        "The number of connections currently waiting to be made ready for use",
                                                                        PerformanceCounterType.NumberOfItems32);

            static internal readonly CounterCreationData NumberOfReclaimedConnections = new CounterCreationData(
                                                                        "NumberOfReclaimedConnections",
                                                                        "The number of connections we reclaim from GC'd external connections",
                                                                        PerformanceCounterType.NumberOfItems32);
        };

        sealed internal class Counter {
            private PerformanceCounter _instance;
            
            internal Counter (string categoryName, string instanceName, string counterName, PerformanceCounterType counterType) {
                if (ADP.IsPlatformNT5) {
                    try {
                        if (!ADP.IsEmpty(categoryName) && !ADP.IsEmpty(instanceName)) {
                            PerformanceCounter instance = new PerformanceCounter();
                            instance.CategoryName = categoryName;
                            instance.CounterName = counterName;
                            instance.InstanceName = instanceName;
                            instance.InstanceLifetime = PerformanceCounterInstanceLifetime.Process;
                            instance.ReadOnly = false;
                            instance.RawValue = 0;  // make sure we start out at zero
                            _instance = instance;
                        }
                    }
                    catch (InvalidOperationException e) {
                        ADP.TraceExceptionWithoutRethrow(e);
                        // 
                    }
                }
            }


            internal void Decrement() {
                PerformanceCounter instance = _instance;
                if (null != instance) {
                    instance.Decrement();
                }
            }

            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
            internal void Dispose () { // 
                PerformanceCounter instance = _instance;
                _instance = null;
                if (null != instance) {
                    instance.RemoveInstance();
                    // should we be calling instance.Close?
                    // if we do will it exacerbate the Dispose vs. Decrement race condition
                    //instance.Close();
                }
            }

            internal void Increment() {
                PerformanceCounter instance = _instance;
                if (null != instance) {
                    instance.Increment();
                }
            }
        };

        const int CounterInstanceNameMaxLength = 127;

        internal readonly Counter HardConnectsPerSecond;
        internal readonly Counter HardDisconnectsPerSecond;
        internal readonly Counter SoftConnectsPerSecond;
        internal readonly Counter SoftDisconnectsPerSecond;
        internal readonly Counter NumberOfNonPooledConnections;
        internal readonly Counter NumberOfPooledConnections;
        internal readonly Counter NumberOfActiveConnectionPoolGroups;
        internal readonly Counter NumberOfInactiveConnectionPoolGroups;
        internal readonly Counter NumberOfActiveConnectionPools;
        internal readonly Counter NumberOfInactiveConnectionPools;
        internal readonly Counter NumberOfActiveConnections;
        internal readonly Counter NumberOfFreeConnections;
        internal readonly Counter NumberOfStasisConnections;
        internal readonly Counter NumberOfReclaimedConnections;
        
        protected DbConnectionPoolCounters() : this(null, null) {
        }

        protected DbConnectionPoolCounters(string categoryName, string categoryHelp) {
            AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadEventHandler);
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(this.ExitEventHandler);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.ExceptionEventHandler);
            
            string instanceName = null;

            if (!ADP.IsEmpty(categoryName)) {
                if (ADP.IsPlatformNT5) {
                    instanceName = GetInstanceName();
                }
            }
            
            // level 0-3: hard connects/disconnects, plus basic pool/pool entry statistics
            string basicCategoryName = categoryName;            
            HardConnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardConnectsPerSecond.CounterName, CreationData.HardConnectsPerSecond.CounterType);
            HardDisconnectsPerSecond = new Counter(basicCategoryName, instanceName, CreationData.HardDisconnectsPerSecond.CounterName, CreationData.HardDisconnectsPerSecond.CounterType);
            NumberOfNonPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfNonPooledConnections.CounterName, CreationData.NumberOfNonPooledConnections.CounterType);
            NumberOfPooledConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfPooledConnections.CounterName, CreationData.NumberOfPooledConnections.CounterType);
            NumberOfActiveConnectionPoolGroups = new Counter(basicCategoryName, instanceName, CreationData.NumberOfActiveConnectionPoolGroups.CounterName, CreationData.NumberOfActiveConnectionPoolGroups.CounterType);
            NumberOfInactiveConnectionPoolGroups = new Counter(basicCategoryName, instanceName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterName, CreationData.NumberOfInactiveConnectionPoolGroups.CounterType);
            NumberOfActiveConnectionPools = new Counter(basicCategoryName, instanceName, CreationData.NumberOfActiveConnectionPools.CounterName, CreationData.NumberOfActiveConnectionPools.CounterType);
            NumberOfInactiveConnectionPools = new Counter(basicCategoryName, instanceName, CreationData.NumberOfInactiveConnectionPools.CounterName, CreationData.NumberOfInactiveConnectionPools.CounterType);
            NumberOfStasisConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfStasisConnections.CounterName, CreationData.NumberOfStasisConnections.CounterType);
            NumberOfReclaimedConnections = new Counter(basicCategoryName, instanceName, CreationData.NumberOfReclaimedConnections.CounterName, CreationData.NumberOfReclaimedConnections.CounterType);
            
            // level 4: expensive stuff
            string verboseCategoryName = null;
            if (!ADP.IsEmpty(categoryName)) {
                // don't load TraceSwitch if no categoryName so that Odbc/OleDb have a chance of not loading TraceSwitch
                // which are also used by System.Diagnostics.PerformanceCounter.ctor & System.Transactions.get_Current
                TraceSwitch perfCtrSwitch = new TraceSwitch("ConnectionPoolPerformanceCounterDetail", "level of detail to track with connection pool performance counters");
                if (TraceLevel.Verbose == perfCtrSwitch.Level) {
                    verboseCategoryName = categoryName;
                }
            }
            SoftConnectsPerSecond = new Counter(verboseCategoryName, instanceName, CreationData.SoftConnectsPerSecond.CounterName, CreationData.SoftConnectsPerSecond.CounterType);
            SoftDisconnectsPerSecond = new Counter(verboseCategoryName, instanceName, CreationData.SoftDisconnectsPerSecond.CounterName, CreationData.SoftDisconnectsPerSecond.CounterType);
            NumberOfActiveConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfActiveConnections.CounterName, CreationData.NumberOfActiveConnections.CounterType);
            NumberOfFreeConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfFreeConnections.CounterName, CreationData.NumberOfFreeConnections.CounterType);
        }

        [FileIOPermission(SecurityAction.Assert, Unrestricted=true)]
        private string GetAssemblyName() {
            string result = null;

            // First try GetEntryAssembly name, then AppDomain.FriendlyName.
            Assembly assembly = Assembly.GetEntryAssembly();

            if (null != assembly) {
                AssemblyName name = assembly.GetName();
                if (name != null) {
                    result = name.Name; // MDAC 73469
                }
            }
            return result;
        }

        // SxS: this method uses GetCurrentProcessId to construct the instance name.
        // 
        [ResourceExposure(ResourceScope.None)]
        [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
        private string GetInstanceName() {
            string result = null;

            string instanceName = GetAssemblyName(); // instance perfcounter name

            if (ADP.IsEmpty(instanceName)) {
                AppDomain appDomain = AppDomain.CurrentDomain;
                if (null != appDomain) {
                    instanceName = appDomain.FriendlyName;
                }
            }

            // 
            int pid = SafeNativeMethods.GetCurrentProcessId();


            // SQLBUDT #366157 -there are several characters which have special meaning
            // to PERFMON.  They recommend that we translate them as shown below, to 
            // prevent problems.

            result = String.Format((IFormatProvider)null, "{0}[{1}]", instanceName, pid);
            result = result.Replace('(','[').Replace(')',']').Replace('#','_').Replace('/','_').Replace('\\','_'); 

            // SQLBUVSTS #94625 - counter instance name cannot be greater than 127
            if (result.Length > CounterInstanceNameMaxLength) {
                // Replacing the middle part with "[...]"
                // For example: if path is c:\long_path\very_(Ax200)_long__path\perftest.exe and process ID is 1234 than the resulted instance name will be: 
                // c:\long_path\very_(AxM)[...](AxN)_long__path\perftest.exe[1234]
                // while M and N are adjusted to make each part before and after the [...] = 61 (making the total = 61 + 5 + 61 = 127)
                const string insertString = "[...]";
                int firstPartLength = (CounterInstanceNameMaxLength - insertString.Length) / 2;
                int lastPartLength = CounterInstanceNameMaxLength - firstPartLength - insertString.Length;
                result = string.Format((IFormatProvider)null, "{0}{1}{2}",
                    result.Substring(0, firstPartLength),
                    insertString,
                    result.Substring(result.Length - lastPartLength, lastPartLength));

                Debug.Assert(result.Length == CounterInstanceNameMaxLength, 
                    string.Format((IFormatProvider)null, "wrong calculation of the instance name: expected {0}, actual: {1}", CounterInstanceNameMaxLength, result.Length));
            }

            return result;
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        public void Dispose() {
            // ExceptionEventHandler with IsTerminiating may be called before
            // the Connection Close is called or the variables are initialized
            SafeDispose(HardConnectsPerSecond);
            SafeDispose(HardDisconnectsPerSecond);
            SafeDispose(SoftConnectsPerSecond);
            SafeDispose(SoftDisconnectsPerSecond);
            SafeDispose(NumberOfNonPooledConnections);
            SafeDispose(NumberOfPooledConnections);
            SafeDispose(NumberOfActiveConnectionPoolGroups);
            SafeDispose(NumberOfInactiveConnectionPoolGroups);
            SafeDispose(NumberOfActiveConnectionPools);
            SafeDispose(NumberOfActiveConnections);
            SafeDispose(NumberOfFreeConnections);
            SafeDispose(NumberOfStasisConnections);
            SafeDispose(NumberOfReclaimedConnections);
        }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
        private void SafeDispose(Counter counter) { // WebData 103603
            if (null != counter) {
                counter.Dispose();
            }
        }

        [PrePrepareMethod]
        void ExceptionEventHandler (object sender, UnhandledExceptionEventArgs e) {
            if ((null != e) && e.IsTerminating) {
                Dispose();
            }
        }

        [PrePrepareMethod]
        void ExitEventHandler (object sender, EventArgs e) {
            Dispose();
        }

        [PrePrepareMethod]
        void UnloadEventHandler (object sender, EventArgs e) {
            Dispose();
        }
    }
    
    sealed internal class DbConnectionPoolCountersNoCounters : DbConnectionPoolCounters {

        public static readonly DbConnectionPoolCountersNoCounters SingletonInstance = new DbConnectionPoolCountersNoCounters();

        private DbConnectionPoolCountersNoCounters() : base () {
        }
    }
}