Files
ntpa/Ntp.Process/Cluster.cs
T
2016-03-06 00:15:13 +01:00

99 lines
3.7 KiB
C#

//
// Cluster.cs
//
// Author:
// Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2013 Carsten Sonne Larsen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using Ntp.Analyzer.Log;
using System.IO;
using System.Threading;
namespace Ntp.Process
{
public sealed class Cluster
{
public Cluster (Scheduler scheduler, IEnumerable<IRequest> peers, LogBase log)
{
this.scheduler = scheduler;
this.peers = peers;
this.log = log;
}
private readonly Scheduler scheduler;
private readonly IEnumerable<IRequest> peers;
private readonly LogBase log;
public void Activate ()
{
log.WriteLine ("Starting cluster module.", Severity.Info);
bool activated = true;
while (true) {
bool otherActive = false;
foreach (IRequest request in peers) {
try {
string answer = request.Send ("ping");
if (answer != null && answer == "*" && activated) {
log.WriteLine ("Cluster node alive: " + request, Severity.Notice);
} else if (answer != null && answer == "active" && activated) {
log.WriteLine ("Cluster node active: " + request, Severity.Notice);
} else if (activated) {
log.WriteLine ("Cluster node dead: " + request, Severity.Notice);
}
if (answer != null && answer == "active") {
otherActive = true;
}
} catch (Exception) {
log.WriteLine ("Error while contacting cluster node " + request, Severity.Warn);
}
}
if (!otherActive) {
//log.WriteLine ("No other nodes active. Activting node.", Severity.Notice);
try {
scheduler.RunOneCycle ();
} catch (Exception e) {
log.WriteLine ("Error in scheduler module. Arborting.", Severity.Error);
log.WriteLine (e.ToString (), Severity.Error);
return;
}
} else {
//log.WriteLine ("Other node active. Going to fallback mode.", Severity.Notice);
Thread.Sleep (10000);
}
activated = false;
}
}
}
}