Ejemplo n.º 1
0
        internal Database(IICDbType dbType, string connectionString)
        {
            _configItem                  = new IICDbConfigItem();
            _configItem.DbType           = dbType;
            _configItem.ConnectionString = connectionString;

            _tracing      = TracingManager.GetTracing("Database.[ConnStr=" + connectionString + "]");
            _perfCounters = IICPerformanceCounterFactory.GetCounters <DatabasePerfCounters>(".");

            switch (_configItem.DbType)
            {
            case IICDbType.SqlServer2005:
                _operation = new SqlServerDatabase(_configItem.ConnectionString, 120);
                break;

            case IICDbType.Mysql:
                _operation = new MysqlDatabase(_configItem.ConnectionString, 120);
                break;

            case IICDbType.MysqlBatchInsert:
                _operation = new MysqlBatchInsert(_configItem.ConnectionString);
                break;

            default:
                throw new NotSupportedException(string.Format("Not Support DbType:{0} {1}", _configItem.DbType, _configItem.Name));
            }
        }
Ejemplo n.º 2
0
        private DatabaseOperationContext Prepare(string info, string spName, string[] parameters, object[] values)
        {
            DatabaseOperationContext ctx = new DatabaseOperationContext();

            ctx.Info       = info;
            ctx.SpName     = spName;
            ctx.Parameters = parameters;
            ctx.Values     = values;
            ctx.Ex         = null;
            ctx.Watch      = Stopwatch.StartNew();

            if (parameters != null && values != null && parameters.Length != values.Length)
            {
                string msg = string.Format("{0} Parameters({1}) != Values({2})", spName, parameters.Length, values.Length);
                throw new InvalidOperationException(msg);
            }

            ctx.Operation = GetInnerOperation();
            TracingManager.Info(
                delegate() {
                _tracing.Info(info + ":\r\n" + ctx.Operation.FormatSql(spName, parameters, values));
            }
                );

            ctx.Observer = GetObserverItem(spName);

            _perfCounters.CommandExecutedTotal.Increment();
            _perfCounters.CommandExecutedPerSec.Increment();
            return(ctx);
        }
Ejemplo n.º 3
0
        private void ReturnInner <T>(RpcResponseHeader response, T results)
        {
            try {
                if (Interlocked.CompareExchange(ref _hasReturned, 1, 0) != 0)
                {
                    string msg = string.Format("Return more than once <{0}.{1}>", this.ServiceName, this.MethodName);
                    throw new NotSupportedException(msg);
                }

                TracingManager.Info(
                    delegate() {
                    _observer.ResponseTracer.InfoFmt2(
                        _request.FromService + "@" + _request.FromComputer,
                        _request.ToUri,
                        "Args={0}\r\nResults={1}",
                        ObjectHelper.DumpObject(_args),
                        ObjectHelper.DumpObject(results)
                        );
                }
                    );

                _trans.SendResponse(response, results);
                _observer.Track(true, response.Error, (int)_watch.ElapsedMilliseconds);
            } catch (Exception innerEx) {
                SystemLog.Error(LogEventID.RpcFailed, innerEx, "RpcServerContext.ReturnError Failed");
            } finally {
                _perfCounters.ConcurrentContext.Decrement();
                _perfCounters.InvokeFailed.Increment();
            }
        }
Ejemplo n.º 4
0
        public T GetArgs <T>()
        {
            try {
                if (!_request.HasBody)
                {
                    object a = null;
                    return((T)a);
                }

                T ret = _trans.ReceiceRequest <T>();
                _args = ret;
                TracingManager.Info(
                    delegate() {
                    _observer.RequestTracer.InfoFmt2(
                        _request.ServiceAtComputer,
                        _request.ToUri,
                        "Args={0}",
                        ObjectHelper.DumpObject(_args)
                        );
                }
                    );
                return(ret);
            } catch (Exception ex) {
                _observer.RequestTracer.ErrorFmt2(
                    ex,
                    _request.ServiceAtComputer,
                    _request.ToUri,
                    "Args={0}",
                    ObjectHelper.DumpObject(_args)
                    );
                throw new RpcException("RpcServerContext.GetArgs", "", RpcErrorCode.InvaildRequestArgs, ex);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///		初始化Web
        /// </summary>
        public static void InitWeb()
        {
            if (_current != null && _current.ServiceName != NULL)
            {
                return;
            }

            lock (_syncRoot) {
                string runMode      = WebConfigurationManager.AppSettings["RunMode"];
                string centerUrl    = WebConfigurationManager.AppSettings["CenterUrl"];
                string serviceName  = WebConfigurationManager.AppSettings["ServiceName"];
                string computerName = WebConfigurationManager.AppSettings["ComputerName"] ?? Environment.MachineName;

                if (runMode == "LocalWeb")
                {
                    _current = new ServiceSettingsConfigProxy(serviceName);
                    IICConfigurationManager.Loader = new LocalConfigurationLoader();
                    _current.UpdateConfig(ServiceRunMode.LocalWeb, null);
                    RpcProxyFactory.RegisterClientChannel(new RpcPipeClientChannel());
                    TracingManager.UpdateConfig();
                }
                else
                {
                    _current = new ServiceSettingsConfigProxy(serviceName, computerName);
                    RpcProxyFactory.RegisterClientChannel(new RpcHttpClientChannel());
                    RpcProxyFactory.RegisterClientChannel(new RpcPipeClientChannel());
                    HAConfigurationLoader loader   = new HAConfigurationLoader(serviceName, computerName, centerUrl);
                    HAServiceSettings     settings = loader.LoadServiceSettings();
                    IICConfigurationManager.Loader = loader;
                    _current.UpdateConfig(ServiceRunMode.HAWeb, settings);
                    TracingManager.UpdateConfig();
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///		使用HA方式初始化服务
        /// </summary>
        /// <param name="serviceName">服务名</param>
        /// <param name="computerName">获取配置使用的计算机名</param>
        /// <param name="centerUrl">HACenter的Url</param>
        public static void InitServiceHa(string serviceName, string computerName, string centerUrl)
        {
            if (_current != null && _current.ServiceName != NULL)
            {
                return;
            }

            lock (_syncRoot) {
                _current = new ServiceSettingsConfigProxy(serviceName, computerName);

                RpcHttpClientChannel channel = new RpcHttpClientChannel();
                RpcProxyFactory.RegisterClientChannel(channel);

                HAGetConfigArgs args = new HAGetConfigArgs();
                args.ServiceName  = serviceName;
                args.ComputerName = computerName;

                var proxy = RpcProxyFactory.GetProxy <IHACenterConfigService>(centerUrl);
                HAServiceSettings settings = proxy.Invoke <HAGetConfigArgs, HAServiceSettings>(
                    "LoadServiceSettings",
                    args);

                IICConfigurationManager.Loader = new HAConfigurationLoader(serviceName, computerName, centerUrl);

                _current.UpdateConfig(ServiceRunMode.HAService, settings);
                TracingManager.UpdateConfig();
            }
        }
Ejemplo n.º 7
0
        internal Database(string configKey)
        {
            _configKey    = configKey;
            _tracing      = TracingManager.GetTracing("Database." + configKey);
            _perfCounters = IICPerformanceCounterFactory.GetCounters <DatabasePerfCounters>(configKey);

            try {
                GetInnerOperation();
            } catch (Exception ex) {
                SystemLog.Error(LogEventID.DatabaseFailed, ex, "Database GetFailed <{0}>", configKey);
            }
        }
Ejemplo n.º 8
0
        public LRUCacheManager(string name, int cacheCount)
        {
            if (!Stopwatch.IsHighResolution)
            {
                throw new NotSupportedException();
            }

            _cacheName  = name;
            _cacheCount = cacheCount;
            _counters   = IICPerformanceCounterFactory.GetCounters <PerfCounters>(_cacheName);
            _tracing    = TracingManager.GetTracing("LRUCacheManager." + _cacheName);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Runs the specified task.
 /// </summary>
 /// <param name="task">The task.</param>
 /// <param name="taskOption">The task option.</param>
 /// <param name="exceptionHandler">The exception handler.</param>
 /// <returns></returns>
 public static Task Run(Action task, TaskCreationOptions taskOption, Action <Exception> exceptionHandler)
 {
     return(Task.Factory.StartNew(task, taskOption).ContinueWith(t =>
     {
         if (exceptionHandler != null)
         {
             exceptionHandler(t.Exception.InnerException);
         }
         else
         {
             TracingManager.GetTracing(typeof(Async)).Error(string.Format("{0}.Run P3 Failed:\r\n{1}", typeof(Async).Name, t.Exception.InnerException));
         }
     }, TaskContinuationOptions.OnlyOnFaulted));
 }
Ejemplo n.º 10
0
        /// <summary>本地初始化服务, 默认初始化为本地配置, HA会覆盖这个配置</summary>
        public static void InitService(string serviceName)
        {
            if (_current != null && _current.ServiceName != NULL)
            {
                return;
            }

            lock (_syncRoot) {
                IICConfigurationManager.Loader = new LocalConfigurationLoader();

                _current = new ServiceSettingsConfigProxy(serviceName);
                _current.UpdateConfig(ServiceRunMode.LocalService, null);
                TracingManager.UpdateConfig();
            }
        }
Ejemplo n.º 11
0
        public T EndInvoke <T>()
        {
            T   retValue;
            var request  = _trans.Request;
            var response = _trans.Response;

            if (response.ErrorCode != RpcErrorCode.OK)
            {
                throw new RpcException(response.ErrorCode, _trans.ServiceUrl, "RpcResponse Failed", response.Error);
            }

            if (typeof(T) == typeof(RpcNull) || _trans.Response.BodyBuffer == null)
            {
                retValue = default(T);
            }
            else
            {
                try {
                    retValue = _trans.Response.BodyBuffer.GetValue <T>();
                } catch (Exception ex) {
                    byte[] buffer = _trans.Response.BodyBuffer.GetByteArray();

                    _observer.RequestTracer.WarnFmt2(
                        ex,
                        request.ServiceAtComputer,
                        request.ContextUri,
                        "ResponseBuffer byte[{0}] = {1}",
                        buffer.Length,
                        StrUtils.ToHexString(buffer, 500)
                        );
                    throw new RpcException(RpcErrorCode.InvaildResponseArgs, _trans.ServiceUrl, "RpcClientContext.EndInvoke<T>, Failed", ex);
                }
            }

            TracingManager.Info(
                delegate() {
                _observer.ResponseTracer.InfoFmt2(
                    request.FromService,
                    request.ContextUri,
                    "Args={0}\r\nResults={1}",
                    ObjectHelper.DumpObject(request.BodyValue),
                    ObjectHelper.DumpObject(response.BodyValue)
                    );
            }
                );

            return(retValue);
        }
Ejemplo n.º 12
0
        public void SendRequest(Action <long, RpcClientContext, bool> callback, int timeout)
        {
            RpcRequest request = _trans.Request;
            Stopwatch  watch   = new Stopwatch();

            _callback = callback;
            _observer = RpcObserverManager.GetClientItem(_trans.ServerUri.ToString(), request.Service, request.Method, _trans.ServiceRole);

            watch.Start();

            try {
                _trans.SendRequest(
                    delegate {
                    var response     = _trans.Response;
                    long elapseTicks = watch.ElapsedTicks;
                    bool successed   = response.ErrorCode == RpcErrorCode.OK;
                    _observer.Track(successed, response.Error, elapseTicks);
                    _callback(elapseTicks, this, successed);
                },
                    timeout
                    );

                TracingManager.Info(
                    delegate() {
                    _observer.RequestTracer.InfoFmt2(
                        request.ServiceAtComputer,
                        request.ContextUri,
                        "Args = {0}",
                        ObjectHelper.DumpObject(request.BodyValue)
                        );
                }
                    );
            } catch (Exception ex) {
                _observer.RequestTracer.ErrorFmt2(
                    ex,
                    request.FromService,
                    request.ContextUri.ToString(),
                    "Args = {0}",
                    ObjectHelper.DumpObject(request.BodyValue)
                    );

                var  response    = RpcResponse.Create(RpcErrorCode.SendFailed, ex);
                long elapseTicks = watch.ElapsedTicks;
                _observer.Track(false, response.Error, elapseTicks);
                _callback(elapseTicks, this, false);
            }
        }
Ejemplo n.º 13
0
        public T EndInvoke <T>()
        {
            T         retValue = default(T);
            Exception error    = null;

            try {
                if (_response.ErrorCode != RpcErrorCode.OK)
                {
                    throw new RpcException("EndInvoke Failed", _serviceUrl, _response.ErrorCode, _response.Error);
                }

                if (typeof(T) == typeof(RpcNull) || !_response.HasBody)
                {
                    retValue = default(T);
                }
                else
                {
                    retValue = _trans.ReceiveResponse <T>();
                }

                TracingManager.Info(
                    delegate() {
                    _observer.ResponseTracer.InfoFmt2(
                        _request.FromService,
                        _request.ToUri,
                        "Args={0}\r\nResults={1}",
                        ObjectHelper.DumpObject(_args),
                        ObjectHelper.DumpObject((object)retValue)
                        );
                }
                    );

                return(retValue);
            } catch (Exception ex) {
                _observer.ResponseTracer.ErrorFmt2(
                    ex,
                    _request.FromService,
                    _request.ToUri,
                    "Args={0}\r\n",
                    ObjectHelper.DumpObject(_args)
                    );
                error = ex;
                throw;
            }
        }
Ejemplo n.º 14
0
        public LazyQueue(string queueName, int maxBatchCount, int maxIdleMs, Action <T[]> dequeueAction, bool enabledCounters)
        {
            _queueName     = queueName;
            _batchCount    = maxBatchCount;
            _idleMs        = maxIdleMs;
            _dequeueAction = dequeueAction;
            _capacity      = 65536;
            _lastTick      = Environment.TickCount;

            _tracing = TracingManager.GetTracing("LazyQueue." + queueName);
            if (enabledCounters)
            {
                _counters = IICPerformanceCounterFactory.GetCounters <LazyQueuePerfCounters>(queueName);
            }

            _thread              = new Thread(new ThreadStart(ThreadProc));
            _thread.Name         = string.Format("LazyQueue<{0}>:{1}", typeof(T).Name, queueName);
            _thread.IsBackground = true;
            _thread.Start();
        }
Ejemplo n.º 15
0
        public ParallelQueue(string queueName, int maxBatchCount, int maxIdleMs, Action <K, V[]> dequeueAction)
        {
            _queueName     = queueName;
            _maxBatchCount = maxBatchCount;
            _maxIdleMs     = maxIdleMs;
            _dequeueAction = dequeueAction;

            _tracing      = TracingManager.GetTracing("ParalelQueue." + queueName);
            _perfCounters = IICPerformanceCounterFactory.GetCounters <ParallelQueuePerfCounters>(queueName);

            _thread = new Thread(ThreadProc);
            _thread.IsBackground = true;
            _thread.Start();

            int max;
            int foo;

            ThreadPool.GetMaxThreads(out max, out foo);
            _defendWorkerThreadCounts = max / 8;
        }
Ejemplo n.º 16
0
        private static void WriteEventLogInner(EventLogEntryType entryType, string message, LogEventID eventId, int repeat)
        {
            // NextVersion
            //if (repeat != 1) {
            //    message = string.Format("!!!Repeat ({0}) times within last 5 second.\r\n", repeat, message);
            //}
            EventLog.WriteEntry(_eventSource, message, entryType, (int)eventId);

            SystemLogEvent evt = new SystemLogEvent();

            evt.ComputerName = ServiceEnvironment.ComputerName;
            evt.ServiceName  = ServiceEnvironment.ServiceName;
            evt.Time         = DateTime.Now;
            evt.Message      = message;
            evt.Level        = GetTracingLevel(entryType);
            evt.EventId      = eventId;
            evt.Repeat       = repeat;

            TracingManager.Enqueue(evt);
        }
Ejemplo n.º 17
0
        /// <summary>
        ///		获取请求参数
        /// </summary>
        /// <typeparam name="T">请求参数类型</typeparam>
        /// <returns>请求参数</returns>
        public T GetArgs <T>()
        {
            try {
                T ret;
                if (_request.BodyBuffer == null)
                {
                    object a = null;
                    ret = (T)a;
                }
                else
                {
                    ret = _trans.Request.BodyBuffer.GetValue <T>();

                    TracingManager.Info(
                        delegate() {
                        _observer.RequestTracer.InfoFmt2(
                            _request.ServiceAtComputer,
                            _request.ContextUri,
                            "Args={0}",
                            ObjectHelper.DumpObject(_trans.Request.BodyValue)
                            );
                    }
                        );
                }
                return(ret);
            } catch (Exception ex) {
                byte[] buffer = _trans.Request.BodyBuffer.GetByteArray();

                _observer.RequestTracer.ErrorFmt2(
                    ex,
                    _request.ServiceAtComputer,
                    _request.ContextUri,
                    "RequestBuffer byte[{0}] = {1}",
                    buffer.Length,
                    StrUtils.ToHexString(buffer, 500)
                    );
                throw new RpcException(RpcErrorCode.InvaildRequestArgs, _trans.ServiceUrl, "RpcServerContext.GetArgs(), Failed", ex);
            }
        }
Ejemplo n.º 18
0
        internal void SendRequest <TArgs>(TArgs args, int timeout)
        {
            _observer = RpcObserverManager.GetClientItem(_request.ServerUri, _request.Service, _request.Method, _serviceRole);

            Stopwatch watch = new Stopwatch();

            watch.Start();

            try {
                _args = args;
                _trans.SendRequest <TArgs>(
                    _request,
                    args,
                    response => ProcessResponse(response, watch.ElapsedTicks),
                    timeout
                    );

                TracingManager.Info(
                    delegate() {
                    _observer.RequestTracer.InfoFmt2(
                        _request.FromService,
                        _request.ToUri,
                        "Args = {0}",
                        ObjectHelper.DumpObject(_args)
                        );
                }
                    );
            } catch (Exception ex) {
                _observer.RequestTracer.ErrorFmt2(
                    ex,
                    _request.FromService,
                    _request.ToUri.ToString(),
                    "Args = {0}",
                    ObjectHelper.DumpObject(_args)
                    );
                throw;
            }
        }
Ejemplo n.º 19
0
        public void SendRequest(JsonRpcRequest rpcRequest, int timeout, Action <JsonRpcResponse> callback)
        {
            // Console.WriteLine("发送请求11111111111111"+DateTime.Now.ToShortDateString());
            TracingManager.Info(
                delegate()
            {
                string module = null;
                string action = null;
                if (rpcRequest.Header != null)
                {
                    module = rpcRequest.Header["UU-REQUEST-MODULE"] == null ? "" : rpcRequest.Header["UU-REQUEST-MODULE"];
                    action = rpcRequest.Header["UU-REQUEST-ACTION"] == null ? "" : rpcRequest.Header["UU-REQUEST-ACTION"];
                }
                _tracing.Info(string.Format("jsonrpc request:uri={0} module={1} action={2}\r\nrequestbody:{3}",
                                            rpcRequest.ServiceUri, module, action, rpcRequest.ReqBody));
            }
                );
            _sericeUri = rpcRequest.ServiceUri;
            _callback  = callback;

            _webRequest             = HttpWebRequest.Create(new Uri(_sericeUri));
            _webRequest.Method      = "POST";
            _webRequest.Proxy       = null;
            _webRequest.ContentType = "application/json";
            _webRequest.Headers.Add(HttpRequestHeader.From, rpcRequest.FromComputer);
            _webRequest.Headers.Add(HttpRequestHeader.Pragma, rpcRequest.FromService);

            if (rpcRequest.Header != null && rpcRequest.Header.Count > 0)
            {
                foreach (string key in rpcRequest.Header.AllKeys)
                {
                    _webRequest.Headers.Add(key, rpcRequest.Header[key]);
                }
            }

            byte[] buffer = null;
            if (rpcRequest.ReqBody == null)
            {
                _webRequest.ContentLength = 0;
            }
            else
            {
                buffer = Encoding.UTF8.GetBytes(rpcRequest.ReqBody);//Request.BodyBuffer.GetByteArray();
                _webRequest.ContentLength = buffer.Length;
            }

            timeout = timeout > 0 ? timeout : _timeOut;

            if (timeout > 0)
            {
                _waitHandle       = new ManualResetEvent(false);
                _registeredHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(TimeoutCallback), this, timeout, true);
            }
            if (_webRequest.ContentLength == 0)
            {
                _webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
            }
            else
            {
                _webRequest.BeginGetRequestStream(
                    delegate(IAsyncResult asyncResult)
                {
                    JsonRpcHttpClientTransaction trans = (JsonRpcHttpClientTransaction)asyncResult.AsyncState;
                    try
                    {
                        WebRequest webReq = trans._webRequest;

                        Stream stream = webReq.EndGetRequestStream(asyncResult);
                        stream.Write(buffer, 0, buffer.Length);
                        stream.Close();
                        webReq.BeginGetResponse(new AsyncCallback(ResponseCallback), this);
                    }
                    catch (Exception ex)
                    {
                        var rpcResonse = new JsonRpcResponse(JsonRpcErrorCode.SendFailed, null, new JsonRpcException(_sericeUri, "send failed", ex), 0);
                        trans.OnCallback(rpcResonse);
                    }
                },
                    this
                    );
            }
        }
Ejemplo n.º 20
0
        //public bool Wait()
        //{
        //    if (_waitHandle != null)
        //        return _waitHandle.WaitOne(_timeOut + 10000);

        //    return false;
        //}

        private static void ResponseCallback(IAsyncResult asyncResult)
        {
            //Console.WriteLine("接收应答222222222222222" + DateTime.Now.ToShortDateString());
            JsonRpcHttpClientTransaction trans = (JsonRpcHttpClientTransaction)asyncResult.AsyncState;
            JsonRpcResponse response           = null;
            WebResponse     webResponse        = null;

            try
            {
                webResponse        = trans._webRequest.EndGetResponse(asyncResult);
                trans._webResponse = webResponse;

                string warn      = webResponse.Headers.Get("UU-RESPONSE-RC");
                string lengthStr = webResponse.Headers.Get("UU-CONTENT-LENGTH");
                int    length    = 0;
                int.TryParse(lengthStr + "", out length);
                int orginalErrorCode = 0;
                int.TryParse(warn, out orginalErrorCode);
                string respBody = null;
                if (length > 0)
                {
                    Stream       stream       = webResponse.GetResponseStream();
                    StreamReader readerStream = new StreamReader(stream);
                    respBody = readerStream.ReadToEnd();

                    readerStream.Close();
                }

                if (!string.IsNullOrEmpty(warn) && warn != "0")
                {
                    JsonRpcErrorCode errCode = JsonRpcErrorCode.Unknown;
                    Enum.TryParse <JsonRpcErrorCode>(warn, true, out errCode);

                    response = new JsonRpcResponse(errCode, respBody, new JsonRpcException(trans._sericeUri, respBody, new Exception("rc != 0")), orginalErrorCode);
                }
                else
                {
                    response = new JsonRpcResponse(JsonRpcErrorCode.OK, respBody);
                }

                TracingManager.Info(
                    delegate()
                {
                    string responseCode = warn == null ? "0" : warn;

                    _tracing.Info(string.Format("jsonrpc response:response rc ={0}\r\nresponse body:{1}",
                                                responseCode, respBody));
                    //if (responseCode != "0")
                    //{
                    //    _tracing.ErrorFmt(response.Exception, "web data response error ,originalerrorcode is {0}", orginalErrorCode);
                    //}
                }
                    );
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.Timeout)
                {
                    response = new JsonRpcResponse(JsonRpcErrorCode.TransactionTimeout, new JsonRpcException(null, null, ex), 500);
                }
                else
                {
                    response = new JsonRpcResponse(JsonRpcErrorCode.SendFailed, new JsonRpcException(null, null, ex), 500);
                }
            }
            catch (Exception ex)
            {
                SystemLog.Error(LogEventID.RpcFailed, ex, "SendRequest failed");
                response = new JsonRpcResponse(JsonRpcErrorCode.SendFailed, new JsonRpcException(null, null, ex), 500);
            }
            finally
            {
                if (webResponse != null)
                {
                    webResponse.Close();
                }

                trans.OnCallback(response);
            }
        }