protected void InitializeSystem() { LocalLog.AddLine("Reading system SQL queries.."); String Message = "Missing the {0} {1} SQL query. Please add the query into the settings file under SchedulerSettings/Tokens/{0} {1}"; _SqlNextJob = _tokens.Resolve("Scheduler", "NextJob", Message); _SqlJobsInProgress = _tokens.Resolve("Scheduler", "JobsInProgress", Message); _SqlUpdateInProgressStatus = _tokens.Resolve("Scheduler", "UpdateInProgress", Message); _SqlNextDbBackup = _tokens.Resolve("Scheduler", "NextDbBackup", Message); _sqlScheduleCheck = _tokens.Resolve("Scheduler", "ScheduledJobCheck", Message); _sqlQueueScheduledJob = _tokens.Resolve("Scheduler", "QueueScheduledJob", Message); String connID = _tokens.Resolve("Scheduler", "ConnectionID", "Missing the connection ID for the database server. Please add the ConnectionID to the settings file under SchedulerSettings/Tokens/{0} {1}"); LocalLog.AddLine("Reading connection information.."); _ConnectionString = XmlUtilities.RequiredAttribute(_Settings, "//Connections/Connection[@ID='" + connID + "']", "ConnectionString", "No " + connID + " connection information found."); LocalLog.AddLine("Reading location of JAVA.."); _JavaHome = _tokens.Resolve("JavaHome", "Path", "Missing path to JAVA bin directory. Please add the path to SchedulerSettings/Tokens/JavaHome Path"); if (!_JavaHome.EndsWith("\\")) { _JavaHome += "\\"; } LocalLog.AddLine(String.Format("JAVA location is {0}", _JavaHome)); _JarPath = _tokens.Resolve("PieJar", "Path", "Missing path to PIE JAR. Please add the path to SchedulerSettings/Tokens/PieJar Path"); _SettingsFile = _tokens.Resolve("PieSettings", "Path", "Missing path to PIE Settings file. Please add the path to SchedulerSettings/Tokens/PieSettings Path"); if (!File.Exists(_JarPath)) { String errorMessage = String.Format("JAR file {0} not found.", _JarPath); FileNotFoundException ex = new FileNotFoundException(errorMessage); _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error); throw ex; } else { LocalLog.AddLine("Using PIE JAR found at " + _JarPath); } if (!File.Exists(_SettingsFile)) { FileNotFoundException ex = new FileNotFoundException(String.Format("PIE Settings file {0} not found.", _SettingsFile)); _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error); throw ex; } else { LocalLog.AddLine("Using PIE Settings file from " + _SettingsFile); } LocalLog.AddLine("Reading service mode.."); String ServiceMode = _tokens.ResolveOptional("Scheduler", "ServiceMode", "Normal").Replace(" ", ""); if (ServiceMode.IndexOf("DatabaseBackup", StringComparison.CurrentCultureIgnoreCase) != -1) { _IsDbBackup = true; LocalLog.AddLine("*** Running as database backup machine."); } else if (ServiceMode.IndexOf("|SiteDeployment|", StringComparison.CurrentCultureIgnoreCase) != -1) { _IsSiteDeployment = true; LocalLog.AddLine("*** Running as CED site delpoyment machine."); } else { LocalLog.AddLine("Running in normal mode."); } }
/// <summary> /// http请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="type">请求类型</param> /// <param name="data">数据</param> /// <param name="username">用户名</param> /// <param name="pwd">密码</param> /// <returns></returns> private static string CommonHttpRequest(string url, string type, string data = "", string username = "", string pwd = "") { HttpWebRequest myRequest = null; Stream outstream = null; HttpWebResponse myResponse = null; StreamReader reader = null; try { // 构造http请求的对象 myRequest = (HttpWebRequest)WebRequest.Create(url); // 设置 myRequest.ProtocolVersion = HttpVersion.Version10; myRequest.Method = type; if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(pwd)) { myRequest.Credentials = new NetworkCredential(username, pwd); } if (data.Trim() != "") { myRequest.ContentType = "application/json"; //myRequest.ContentLength = data.Length; //myRequest.Headers.Add("data", data); // 转成网络流 byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data); outstream = myRequest.GetRequestStream(); outstream.Flush(); outstream.Write(buf, 0, buf.Length); outstream.Flush(); outstream.Close(); } // 获得接口返回值 myResponse = (HttpWebResponse)myRequest.GetResponse(); reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string ReturnXml = reader.ReadToEnd(); reader.Close(); myResponse.Close(); myRequest.Abort(); return(ReturnXml); } catch (WebException ex) { var res = (HttpWebResponse)ex.Response; StreamReader sr; string strHtml = ex.Message; if (res != null) { sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); strHtml = sr.ReadToEnd(); sr.BaseStream.Seek(0, SeekOrigin.Begin); } if (outstream != null) { outstream.Close(); } if (reader != null) { reader.Close(); } if (myResponse != null) { myResponse.Close(); } if (myRequest != null) { myRequest.Abort(); } string msg = strHtml + Environment.NewLine + "请求地址:" + url; LocalLog.WriteLog(typeof(RestClient), msg); return(""); } }
public void ProcessQueue() { int JobKey = -1; try { // Validate the processing job and update those that are no long running. ValidateRunningJobs(); // Check for any scheduled work CheckScheduledJobs(); // Check for any queued work DataRow dr = GetNextJob(); if (dr == null) { return; } JobKey = MiscUtilities.ObjectToInteger(dr["pkey"], "No primary key is definied"); String JobFileName = MiscUtilities.ObjectToString(dr["definition_name"], "No definition file name is defined."); String RawJobFileName = JobFileName; String lockFilename = MiscUtilities.LockFilename(RawJobFileName); String action_requested = MiscUtilities.ObjectToStringDefault(dr["action_requested"], "rescan"); using (FileStream fs = new FileStream(lockFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine("While file is locked open, processing thread is running. Seeing this message means the thread may not be running, please delete this file."); if (_IsDbBackup) { BackupCastDatabase(JobKey, JobFileName, RawJobFileName); } else { String message = "Processing"; switch (action_requested.ToLower()) { case "publish": JobFileName = _tokens.Resolve("Scheduler", "PublishDefinition", "No publish definition defined in the settings file. Please add a Tokens/Scheduler PublishDefinition"); message = "Publishing"; break; case "empty": case "rescan": message = "Processing"; break; case "onboard": JobFileName = _tokens.Resolve("Scheduler", "OnBoardDefinition", "No onboard definition defined in the settings file. Please add a Tokens/Scheduler OnBoardDefinition"); message = "OnBoarding"; break; default: throw new Exception(String.Format("{0} is not a valid action request.", action_requested)); } // Kick off the definition RunDefinition(JobKey, JobFileName, RawJobFileName, message); } } fs.Close(); } File.Delete(lockFilename); } catch (Exception ex) { lock (_lock) { LocalLog.AddLine("Queue Error: " + ex.Message); } _AppLog.WriteEntry(ex.StackTrace, System.Diagnostics.EventLogEntryType.Error); if (JobKey > 0) { Dictionary <String, Object> sqlParameters = new Dictionary <string, object>(); sqlParameters.Add(":jobkey", JobKey); sqlParameters.Add(":jobstatus", "Error"); sqlParameters.Add(":inprogress", false); sqlParameters.Add(":scanrequested", false); String message = String.Format("Recorded: {0:MMMM d, yyyy HH:mm:ss}, Message: {1} ", DateTime.Now, ex.Message); if (message.Length > 99) { message = message.Substring(0, 99); } sqlParameters.Add(":statusdescription", message); SqlUtilities.ExcecuteNonQuery(_ConnectionString, _SqlUpdateInProgressStatus, sqlParameters); } } }
/// <summary> /// 服务执行后 /// </summary> /// <param name="actionExecutedContext"></param> public override async void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { try { var controller = actionExecutedContext.ActionContext.ControllerContext.Controller; var unitOfWorkProperty = controller.GetType().BaseType.GetField("_UnitOfWorks", System.Reflection.BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); var unitOfWorkDict = (Dictionary <string, IUnitOfWork>)unitOfWorkProperty.GetValue(controller); var serviceContextProperty = controller.GetType().BaseType.GetProperty("ServiceContext", System.Reflection.BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); ServiceContext serviceContext = serviceContextProperty.GetValue(controller) as ServiceContext; string fuWuCsStr = await actionExecutedContext.ActionContext.Request.Content.ReadAsStringAsync(); // 获取服务完整地址信息 string serviceUri = actionExecutedContext.ActionContext.Request.RequestUri.ToString(); // 获取服务信息 string pathAndQuery = actionExecutedContext.ActionContext.Request.RequestUri.PathAndQuery; string server = actionExecutedContext.ActionContext.Request.RequestUri.Host; string port = actionExecutedContext.ActionContext.Request.RequestUri.Port.ToString(); string moKuaiMc = pathAndQuery.Split('/')[1]; string yeWuMc = pathAndQuery.Split('/')[2]; string caoZuoMc = pathAndQuery.Split('/')[3]; StringBuilder sqlLogText = new StringBuilder(); //ESLog eSLog = new ESLog(); StringBuilder stringBuilder = new StringBuilder(); #region 记录调用日志 // 记录日志===================================================================== try { SysLogEntity logEntity = new SysLogEntity(); logEntity.RiZhiID = Guid.NewGuid().ToString(); logEntity.ChuangJianSj = DateTime.Now.ToInvariantString("yyyy/MM/dd HH:mm:ss"); logEntity.RiZhiBt = serviceContext.USERNAME + "[" + serviceContext.USERID + "]成功调用了[" + moKuaiMc + "/" + yeWuMc + "/" + caoZuoMc + "]服务。"; stringBuilder.AppendLine(serviceContext.USERNAME + "[" + serviceContext.USERID + "]成功调用了[" + server + ":" + port + "端口上的" + serviceUri + "]服务。"); stringBuilder.AppendLine(); stringBuilder.AppendLine("参数列表:"); // 服务参数 var fuWuCsList = QueryUrl.GetData(fuWuCsStr); foreach (var item in fuWuCsList) { stringBuilder.AppendLine(item.Key + "=" + Uri.UnescapeDataString(item.Value).DecompressString()); } try { var res = await actionExecutedContext.Response.Content.ReadAsStringAsync(); ServiceResult serviceResult = JsonUtil.DeserializeToObject <ServiceResult>(res); serviceResult.ReturnCode = serviceResult.ReturnCode.DecompressString(); serviceResult.ReturnMessage = serviceResult.ReturnMessage.DecompressString(); serviceResult.ExceptionContent = serviceResult.ExceptionContent.DecompressString(); serviceResult.Content = serviceResult.Content.DecompressString(); stringBuilder.AppendLine("返回内容:"); stringBuilder.AppendLine(JsonUtil.SerializeObject(serviceResult)); } catch (Exception ex) { stringBuilder.AppendLine("返回内容:无,信息:" + ex.ToString()); } logEntity.RiZhiNr = stringBuilder.ToString(); logEntity.FuWuMc = moKuaiMc + "/" + yeWuMc + "/" + caoZuoMc; logEntity.QingQiuLy = serviceContext.DANGQIANCKMC; // 日志类型:1.菜单打开,2.客户端异常,3.服务调用,4服务端异常,5.SQL日志,6.性能日志 logEntity.RiZhiLx = 3; logEntity.YINGYONGID = serviceContext.YINGYONGID; logEntity.XITONGID = serviceContext.XITONGID; logEntity.YINGYONGMC = serviceContext.YINGYONGMC; logEntity.YINGYONGJC = serviceContext.YINGYONGJC; logEntity.VERSION = serviceContext.VERSION; logEntity.IP = serviceContext.IP; logEntity.MAC = serviceContext.MAC; logEntity.COMPUTERNAME = serviceContext.COMPUTERNAME; logEntity.USERNAME = serviceContext.USERNAME; logEntity.USERID = serviceContext.USERID; logEntity.KESHIID = serviceContext.KESHIID; logEntity.KESHIMC = serviceContext.KESHIMC; logEntity.BINGQUID = serviceContext.BINGQUID; logEntity.BINGQUMC = serviceContext.BINGQUMC; logEntity.JIUZHENKSID = serviceContext.JIUZHENKSID; logEntity.JIUZHENKSMC = serviceContext.JiuZhenKSMC; logEntity.YUANQUID = serviceContext.YUANQUID; logEntity.GONGZUOZID = serviceContext.GONGZUOZID; //eSLog.PutLog(logEntity); LogHelper.Intance.PutSysInfoLog(logEntity); // 记录日志===================================================================== } catch (Exception e) { LocalLog.WriteLog(this.GetType(), e); } #endregion List <string> unitOfWorkKeys = new List <string>(unitOfWorkDict.Keys); for (int i = 0; i < unitOfWorkDict.Values.Count; i++) { IUnitOfWork unitOfWork = unitOfWorkDict[unitOfWorkKeys[i]]; #region 记录SQL日志 try { // 记录日志===================================================================== if (!string.IsNullOrWhiteSpace(unitOfWork.SqlLog.ToString())) { sqlLogText.AppendLine(unitOfWork.SqlLog.ToString()); SysLogEntity sqlLogEntity = new SysLogEntity(); sqlLogEntity.RiZhiID = Guid.NewGuid().ToString(); sqlLogEntity.ChuangJianSj = DateTime.Now.ToInvariantString("yyyy/MM/dd HH:mm:ss"); sqlLogEntity.RiZhiBt = "[" + moKuaiMc + "/" + yeWuMc + "/" + caoZuoMc + "]服务运行期间的SQL记录。"; sqlLogEntity.RiZhiNr = unitOfWork.SqlLog.ToString(); sqlLogEntity.FuWuMc = moKuaiMc + "/" + yeWuMc + "/" + caoZuoMc; sqlLogEntity.QingQiuLy = serviceContext.DANGQIANCKMC; // 日志类型:1.菜单打开,2.客户端异常,3.服务调用,4服务端异常,5.SQL日志,6.性能日志 sqlLogEntity.RiZhiLx = 5; sqlLogEntity.YINGYONGID = serviceContext.YINGYONGID; sqlLogEntity.XITONGID = serviceContext.XITONGID; sqlLogEntity.YINGYONGMC = serviceContext.YINGYONGMC; sqlLogEntity.YINGYONGJC = serviceContext.YINGYONGJC; sqlLogEntity.VERSION = serviceContext.VERSION; sqlLogEntity.IP = serviceContext.IP; sqlLogEntity.MAC = serviceContext.MAC; sqlLogEntity.COMPUTERNAME = serviceContext.COMPUTERNAME; sqlLogEntity.USERNAME = serviceContext.USERNAME; sqlLogEntity.USERID = serviceContext.USERID; sqlLogEntity.KESHIID = serviceContext.KESHIID; sqlLogEntity.KESHIMC = serviceContext.KESHIMC; sqlLogEntity.BINGQUID = serviceContext.BINGQUID; sqlLogEntity.BINGQUMC = serviceContext.BINGQUMC; sqlLogEntity.JIUZHENKSID = serviceContext.JIUZHENKSID; sqlLogEntity.JIUZHENKSMC = serviceContext.JiuZhenKSMC; sqlLogEntity.YUANQUID = serviceContext.YUANQUID; sqlLogEntity.GONGZUOZID = serviceContext.GONGZUOZID; //eSLog.PutLog(sqlLogEntity); LogHelper.Intance.PutSysInfoLog(sqlLogEntity); } } catch (Exception e) { LocalLog.WriteLog(this.GetType(), e); } // 记录日志===================================================================== #endregion //try //{ // unitOfWork.MessagePlugin?.Handler(); //} //catch (Exception e) //{ // Enterprise.Log.LogHelper.Intance.Error("业务插件",e.Message, JsonUtil.SerializeObject(e)); //} try { // 是否发送 if (unitOfWork != null && unitOfWork.CurrentMessager.IsPublish) { unitOfWork.CurrentMessager.Context = serviceContext; unitOfWork.CurrentMessager.MoKuaiMc = moKuaiMc; unitOfWork.CurrentMessager.YeWuMc = yeWuMc; unitOfWork.CurrentMessager.CaoZuoMc = caoZuoMc; // 发送消息 using (var client = MessageQueueClientFactory.CreateDbClient()) { client.Publish(moKuaiMc, yeWuMc, caoZuoMc, unitOfWork.CurrentMessager); } //是否需要推送消息处理日志 bool tuiSong = unitOfWork.CurrentMessager.EntityNameList.ToList().Exists(d => Messager.DaiJianCeSTList.Contains(d)); // 将发送的消息异步记录到ES // 需要先将消息内容序列化,否则异步序列化会因部分对象已释放而报错 string riZhiNr = JsonConvert.SerializeObject(unitOfWork.CurrentMessager); string id = unitOfWork.CurrentMessager.ID; await Task.Factory.StartNew(() => { LogHelper.Intance.Info("消息发送", "消息发送成功", riZhiNr, id); if (tuiSong) { dynamic obj = new System.Dynamic.ExpandoObject(); //动态类型字段 可读可写 obj.ID = id; obj.Status = 0; //0表示未处理 obj.ChuLiSJ = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); LogHelper.Intance.Info("消息处理", "消息处理完毕", JsonConvert.SerializeObject(obj), id); } }); } } catch (Exception ex) { // 发送消息队列失败 throw ex; } finally { if (unitOfWork != null) { unitOfWork.Dispose(); unitOfWork = null; } unitOfWork = null; } } unitOfWorkDict.Clear(); var requestContextCacheProperty = controller.GetType().BaseType.GetField("_RequestContextCache", System.Reflection.BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); if (requestContextCacheProperty != null) { var requestContextCacheObj = requestContextCacheProperty.GetValue(controller); if (requestContextCacheObj != null) { var requestContextCache = (ContextCache)requestContextCacheObj; requestContextCache.Clear(); requestContextCache.Dispose(); requestContextCache = null; } } // 记录服务调用耗时日志 var ServiceStartTimeProperty = controller.GetType().BaseType.GetField("_ServiceStartTime", System.Reflection.BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); if (ServiceStartTimeProperty != null) { var ServiceStartTimeObj = ServiceStartTimeProperty.GetValue(controller); if (ServiceStartTimeObj != null) { var serviceStartTime = (long)ServiceStartTimeObj; long nowTicks = DateTime.Now.Ticks; DateTime dateTime = new DateTime(nowTicks - serviceStartTime); float haoShi = (float)Math.Round((decimal)((nowTicks - serviceStartTime) / 10000000d), 4); SysLogEntity logTimeEntity = new SysLogEntity { RiZhiID = Guid.NewGuid().ToString(), ChuangJianSj = DateTime.Now.ToInvariantString("yyyy/MM/dd HH:mm:ss"), RiZhiBt = serviceContext.USERNAME + "[" + serviceContext.USERID + "]调用[" + moKuaiMc + "/" + yeWuMc + "/" + caoZuoMc + "]服务,总耗时:" + haoShi + "秒。", RiZhiNr = "[服务调用耗时:" + haoShi + "秒] " + stringBuilder.ToString() + sqlLogText.ToString(), FuWuHs = haoShi, // 添加耗时 FuWuMc = moKuaiMc + "/" + yeWuMc + "/" + caoZuoMc, QingQiuLy = serviceContext.DANGQIANCKMC, // 日志类型:1.菜单打开,2.客户端异常,3.服务调用,4服务端异常,5.SQL日志,6.性能日志 RiZhiLx = 6, YINGYONGID = serviceContext.YINGYONGID, XITONGID = serviceContext.XITONGID, YINGYONGMC = serviceContext.YINGYONGMC, YINGYONGJC = serviceContext.YINGYONGJC, VERSION = serviceContext.VERSION, IP = serviceContext.IP, MAC = serviceContext.MAC, COMPUTERNAME = serviceContext.COMPUTERNAME, USERNAME = serviceContext.USERNAME, USERID = serviceContext.USERID, KESHIID = serviceContext.KESHIID, KESHIMC = serviceContext.KESHIMC, BINGQUID = serviceContext.BINGQUID, BINGQUMC = serviceContext.BINGQUMC, JIUZHENKSID = serviceContext.JIUZHENKSID, JIUZHENKSMC = serviceContext.JiuZhenKSMC, YUANQUID = serviceContext.YUANQUID, GONGZUOZID = serviceContext.GONGZUOZID }; //eSLog.PutLog(logTimeEntity); LogHelper.Intance.PutSysInfoLog(logTimeEntity); } } } catch (Exception ex) { var controller = actionExecutedContext.ActionContext.ControllerContext.Controller; var serviceContextProperty = controller.GetType().BaseType.GetProperty("ServiceContext", System.Reflection.BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); ServiceContext serviceContext = serviceContextProperty.GetValue(controller) as ServiceContext; // 本地日志 LogHelper.Intance.Error("系统日志", "ApiActionFilterAttribute处理OnActionExecuted报错", "ApiActionFilterAttribute处理OnActionExecuted报错:" + ex.ToString() + "\r\n" + JsonUtil.SerializeObject(serviceContext)); } base.OnActionExecuted(actionExecutedContext); }
private void pieJobCheck(object sender, System.Timers.ElapsedEventArgs e) { try { _timer.Stop(); if (DateTime.Now > _nextMessage) { LocalLog.AddLine("Hourly status. Still checking every 30 seconds.."); } if (_CleanupLogs && (DateTime.Now > _nextLogCleanUp)) { LocalLog.AddLine("Starting to clean up old log files ..."); ScanManager.Common.LogCleanUp lc = new ScanManager.Common.LogCleanUp(_taskManager.ResolveToken("PieLogs", "Path"), _taskManager.ResolveToken("PieLogs", "FileExtension")); LocalLog.AddLine(lc.findOrphanFiles()); LocalLog.AddLine("Completed clean-up."); _nextLogCleanUp = DateTime.Now.AddHours(4); } // Look for free thread for (int i = 0; i < _threadPool.Length; i++) { if ((_threadPool[i] == null) || _threadPool[i].IsAvailable) { _threadPool[i] = new ScanManager.BackgroundProcessing(_taskManager); _threadPool[i].DoWork(); } } if (DateTime.Now > _nextMessage) { LocalLog.AddLine("Check complete."); _nextMessage = DateTime.Now.AddHours(1); } } catch (Exception ex) { LocalLog.AddLine("ERROR: " + ex.Message); } finally { String stopFile = String.Format("{0}{1}stop.txt", MiscUtilities.AppPath(), Path.DirectorySeparatorChar); if (File.Exists(stopFile)) { LocalLog.AddLine(String.Format("Stopping service, waiting for processes to complete. Stop file ({0}) located on the drive.", stopFile)); File.Delete(stopFile); Boolean threadsRunning = true; while (threadsRunning) { threadsRunning = false; for (int i = 0; i < _threadPool.Length; i++) { if ((_threadPool[i] != null) || _threadPool[i].IsBusy) { threadsRunning = true; break; } } if (threadsRunning) { Thread.Sleep(30000); } } Stop(); } else { _timer.Start(); } } }
public virtual async Task <AppendEntriesResult> AppendEntries(AppendEntriesRequest request) { Debug.WriteLine("{0}: GOT APPEND ENTRIES CALL {1}: leader commit {2} : entries: {3}", NodeInfo(), request.Id, request.CommitIndex, String.Concat(request.Entries.Select(e => e.Log + " "))); HeartBeat(request.Id, request.Term); if (request.Entries == null || !request.Entries.Any()) //heartbeat { if (request.CommitIndex > ServerLog.LastIndex) { Debug.WriteLine("{0}: HeartBeat Adding To Server Log up to index {1} leaderCommitIndex {2}", NodeInfo(), request.PreviousLogIndex, request.CommitIndex); LocalLog.Entries.Where(e => e.Index > ServerLog.LastIndex && e.Index <= request.CommitIndex).ForEach(e => ServerLog.Add(e.Term, e.Log)); } return(new AppendEntriesResult(Term, true)); } if (Term < request.Term) //servers term is behind. we need to ensure we are in follower state and reset who we have voted for { StepDown(request.Term, request.Id); return(new AppendEntriesResult(Term, false)); } if (request.Term < Term) { return(new AppendEntriesResult(Term, false)); } if (request.PreviousLogIndex == 0 || (request.PreviousLogIndex <= ServerLog.LastIndex && ServerLog.LastTerm == request.PreviousLogTerm)) { Debug.WriteLine("{0}: huh"); } //reply false if log doesnt contain an entry at prevLogIndex whose term matches prevlogTerm if (!LocalLog.Entries.Any(e => e.Index == request.PreviousLogIndex && e.Term == request.PreviousLogTerm)) //not to sure about this line yet { return(new AppendEntriesResult(Term, false)); } if (LocalLog.Entries.Any(e => e.Index == request.PreviousLogIndex && e.Term != request.PreviousLogTerm)) { //delete the entry and all that follow it LocalLog.RemoveEntryAndThoseAfterIt(request.PreviousLogIndex); } if (request.Entries.Max(e => e.Index) > LocalLog.LastIndex) { Debug.WriteLine("{0}: Adding To Local Log up to index {1} leaderCommitIndex {2}", NodeInfo(), request.Entries.Max(e => e.Index), request.CommitIndex); request.Entries.Where(e => e.Index > LocalLog.LastIndex).ForEach(e => LocalLog.Add(e.Term, e.Log)); } if (request.CommitIndex > ServerLog.LastIndex) { Debug.WriteLine("{0}: Adding To Server Log up to index {1} leaderCommitIndex {2}", NodeInfo(), request.PreviousLogIndex, request.CommitIndex); request.Entries.Where(e => e.Index > ServerLog.LastIndex && e.Index <= request.CommitIndex).ForEach(e => ServerLog.Add(e.Term, e.Log)); } if (request.CommitIndex > CommitIndex) { CommitIndex = Math.Min(request.CommitIndex, LocalLog.LastIndex); } return(new AppendEntriesResult(Term, true)); }
public static void ClearLog() { var localLog = new LocalLog(); localLog.Clear(); }