public static void SetConfigCache(string configXml, ILoggingAdapter logger = null) { // Set config cache in JavascriptLogging to contents of xe XmlElement xe = ConfigToXe(configXml); JavascriptLogging.SetJsnlogConfiguration(null, logger); JavascriptLogging.GetJsnlogConfiguration(() => xe); }
public JobsToRunData(IActorRef jobTaskerActor) { _cancel = new CancellationTokenSource(); _logger = Context.GetLogger(); _jobTaskerActorRef = jobTaskerActor; Become(Ready); }
public ItemWorker(IActorRef coordinatorActor) { _cancel = new CancellationTokenSource(); _logger = Context.GetLogger(); CoordinatorActor = coordinatorActor; Become(Ready); }
public AtomDocumentRetriever(SubscriptionManager burstManager, ILoggingAdapter adapter, IAtomDocumentRepository documentRepository) { _documentRepository = documentRepository; this.burstManager = burstManager; _adapter = adapter; atomDocumentSerialiser = new AtomDocumentSerialiser(); }
public EventStoreJournal() { _log = Context.GetLogger(); _extension = EventStorePersistence.Instance.Apply(Context.System); _serializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, Formatting = Formatting.Indented, Converters = { new ActorRefConverter(Context) } }; _connection = new Lazy<Task<IEventStoreConnection>>(async () => { try { IEventStoreConnection connection = EventStoreConnection.Create(_extension.EventStoreJournalSettings.ConnectionString, _extension.EventStoreJournalSettings.ConnectionName); await connection.ConnectAsync(); return connection; } catch(Exception exc) { _log.Error(exc.ToString()); return null; } }); }
public BlobStorageSnapshotStore() { _extension = AzureStoragePersistence.Instance.Apply(Context.System); _log = Context.GetLogger(); _settings = new JsonSerializerSettings(); _settings.TypeNameHandling = TypeNameHandling.All; }
public async Task<IEventStoreConnection> CreateAsync(ILoggingAdapter log, string host, int tcpPort) { var address = (await Dns.GetHostAddressesAsync(host)).First(); var connection = EventStoreConnection.Create(CreateConnectionSettings(new AkkaLogger(log)), new IPEndPoint(address, tcpPort)); await connection.ConnectAsync(); return connection; }
public RootGuardianSupervisor(RootActorPath root, IActorRefProvider provider, TaskCompletionSource<Status> terminationPromise, ILoggingAdapter log) { _log = log; _terminationPromise = terminationPromise; _provider = provider; _path = root / "_Root-guardian-supervisor"; //In akka this is root / "bubble-walker" }
public TableStorageJournal() { _log = Context.GetLogger(); _extension = AzureStoragePersistence.Instance.Apply(Context.System); _settings = new JsonSerializerSettings(); _settings.TypeNameHandling = TypeNameHandling.All; }
public JobTasker(IActorRef jobMaster) { ScheduleDelay = Convert.ToInt32(ConfigurationManager.AppSettings["JobTaskerScheduleDelay"]); _jobMaster = jobMaster; _logger = Context.GetLogger(); BecomeReady(); }
public DefaultMessageDispatcher(ActorSystem system, RemoteActorRefProvider provider, ILoggingAdapter log) { this.system = system; this.provider = provider; this.log = log; remoteDaemon = provider.RemoteDaemon; settings = provider.RemoteSettings; }
public FileSubscriber(FileInfo f, TaskCompletionSource<IOResult> completionPromise, int bufferSize, FileMode fileMode) { _f = f; _completionPromise = completionPromise; _fileMode = fileMode; _log = Context.GetLogger(); _requestStrategy = new WatermarkRequestStrategy(highWatermark: bufferSize); }
public ItemDataWorker(Job job, IActorRef workerCoordinatorActor) { _job = job; _cancel = new CancellationTokenSource(); _logger = Context.GetLogger(); WorkerCoordinatorActorRef = workerCoordinatorActor; Become(Ready); }
public OutputStreamSubscriber(Stream outputStream, TaskCompletionSource<IOResult> completionPromise, int bufferSize, bool autoFlush) { _outputStream = outputStream; _completionPromise = completionPromise; _autoFlush = autoFlush; RequestStrategy = new WatermarkRequestStrategy(highWatermark: bufferSize); _log = Context.GetLogger(); }
protected AggregateRootActor(IAggregateRootCreationParameters parameters) { _id = parameters.Id; _projections = parameters.Projections; _snapshotThreshold = parameters.SnapshotThreshold; _exceptions = new List<Exception>(); _log = Context.GetLogger(); }
public ClusterStatus(HostControl hostControl = null) { _clusterStartTime = DateTime.Now; _hostControl = hostControl; _logger = Context.GetLogger(); Cluster.Subscribe(Self, ClusterEvent.InitialStateAsEvents, new[] { typeof(ClusterEvent.IMemberEvent), typeof(ClusterEvent.IReachabilityEvent) }); _currentClusterStateTeller = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimeSpan.FromMilliseconds(10), TimeSpan.FromSeconds(5), Self, new SendCurrentClusterState(), Self); Ready(); }
protected EventStoreSubscriptionView() { _log = Context.GetLogger(); var extension = EventStorePersistence.Instance.Apply(Context.System); _connection = extension.ServerSettings.Connection; _deserializer = extension.JournalSettings.Deserializer; _serializer = Context.System.Serialization.FindSerializerForType(typeof(IPersistentRepresentation)); }
//TODO: use some more efficient approach to handle future work public DedicatedThreadScheduler(ActorSystem system) { _log = Logging.GetLogger(system, this); var precision = system.Settings.Config.GetTimeSpan("akka.scheduler.tick-duration"); var thread = new Thread(_ => { var allWork = new List<ScheduledWork>(); while (true) { if (system.TerminationTask.IsCompleted) { return; } Thread.Sleep(precision); var now = HighResMonotonicClock.Ticks; ScheduledWork work; while(_workQueue.TryDequeue(out work)) { //has work already expired? if (work.TickExpires < now) { work.Action(); } else { //buffer it for later allWork.Add(work); } } //this is completely stupid, but does work.. if (allWork.Count > 0) { var tmp = allWork; allWork = new List<ScheduledWork>(); foreach (var bufferedWork in tmp) { if (bufferedWork.TickExpires < now) { bufferedWork.Action(); } else { allWork.Add(bufferedWork); } } } } }) {IsBackground = true}; thread.Start(); }
public JobWorker(Job job, IActorRef jobTrackingMaster) { _logger = Context.GetLogger(); Job = job; RunningStatus = new JobStatusUpdate(Job); TotalStats = new JobStats(Job); JobTrackingMaster = jobTrackingMaster; // Make the JobTrackingMaster a default subscriber so that it receives all updates. Subscribers.Add(JobTrackingMaster); BecomeReady(); }
public EventStoreJournal() { _log = Context.GetLogger(); var serialization = Context.System.Serialization; _serializer = serialization.FindSerializerForType(typeof(IPersistentRepresentation)); var extension = EventStorePersistence.Instance.Apply(Context.System); var journalSettings = extension.JournalSettings; _deserializer = journalSettings.Deserializer; _connection = extension.ServerSettings.Connection; }
private static Bucket[] CreateWheel(int ticksPerWheel, ILoggingAdapter log) { if (ticksPerWheel <= 0) throw new ArgumentOutOfRangeException(nameof(ticksPerWheel), ticksPerWheel, "Must be greater than 0."); if (ticksPerWheel > 1073741824) throw new ArgumentOutOfRangeException(nameof(ticksPerWheel), ticksPerWheel, "Cannot be greater than 2^30."); ticksPerWheel = NormalizeTicksPerWheel(ticksPerWheel); var wheel = new Bucket[ticksPerWheel]; for (var i = 0; i < wheel.Length; i++) wheel[i] = new Bucket(log); return wheel; }
public EventStoreSnapshotStore() { _log = Context.GetLogger(); _extension = EventStorePersistence.Instance.Apply(Context.System); var serialization = Context.System.Serialization; _serializer = serialization.FindSerializerForType(typeof(SelectedSnapshot)); _connection = new Lazy<Task<IEventStoreConnection>>(async () => { IEventStoreConnection connection = EventStoreConnection.Create(_extension.EventStoreSnapshotSettings.ConnectionString, _extension.EventStoreSnapshotSettings.ConnectionName); await connection.ConnectAsync(); return connection; }); }
/// <summary> /// This method will write the log in a text file that is configured in the .config file. /// </summary> /// <param name="message"></param> /// <param name="logLevel"></param> public static void WriteLog(string message, enumLogLevel logLevel) { try { string logMode = ConfigurationManager.AppSettings["LogMode"]; if (_LoggingAdapter == null) _LoggingAdapter = GetObject(logMode); _LoggingAdapter.WriteLog(message, (int)logLevel); } catch (Exception) { throw; } }
public DedicatedThreadScheduler(Config config, ILoggingAdapter log) : base(config, log) { var precision = SchedulerConfig.GetTimeSpan("akka.scheduler.tick-duration"); _shutdownTimeout = SchedulerConfig.GetTimeSpan("akka.scheduler.shutdown-timeout"); var thread = new Thread(_ => { var allWork = new List<ScheduledWork>(); while (_stopped.Value == null) { Thread.Sleep(precision); var now = HighResMonotonicClock.Ticks; ScheduledWork work; while (_workQueue.TryDequeue(out work)) { //has work already expired? if (work.TickExpires < now) { work.Action(); } else { //buffer it for later allWork.Add(work); } } //this is completely stupid, but does work.. if (allWork.Count > 0) { var tmp = allWork; allWork = new List<ScheduledWork>(); foreach (var bufferedWork in tmp) { if (bufferedWork.TickExpires < now) { bufferedWork.Action(); } else { allWork.Add(bufferedWork); } } } } // shutdown has been signaled FireStopSignal(); }) {IsBackground = true}; thread.Start(); }
public ClusterActorDiscovery(Cluster cluster) { _cluster = cluster; _name = Self.Path.Name; _log = Context.GetLogger(); Receive<ClusterEvent.MemberUp>(m => Handle(m)); Receive<ClusterEvent.ReachableMember>(m => Handle(m)); Receive<ClusterEvent.UnreachableMember>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.RegisterCluster>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.ResyncCluster>(m => Handle(m)); // Receive<ClusterActorDiscoveryMessage.UnregisterCluster>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.ClusterActorUp>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.ClusterActorDown>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.RegisterActor>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.UnregisterActor>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.MonitorActor>(m => Handle(m)); Receive<ClusterActorDiscoveryMessage.UnmonitorActor>(m => Handle(m)); Receive<Terminated>(m => Handle(m)); }
private readonly long _tickDuration; // a timespan expressed as ticks public HashedWheelTimerScheduler(Config scheduler, ILoggingAdapter log) : base(scheduler, log) { var ticksPerWheel = SchedulerConfig.GetInt("akka.scheduler.ticks-per-wheel"); var tickDuration = SchedulerConfig.GetTimeSpan("akka.scheduler.tick-duration"); if (tickDuration.TotalMilliseconds < 10.0d) throw new ArgumentOutOfRangeException("minimum supported akka.scheduler.tick-duration on Windows is 10ms"); // convert tick-duration to ticks _tickDuration = tickDuration.Ticks; // Normalize ticks per wheel to power of two and create the wheel _wheel = CreateWheel(ticksPerWheel, log); _mask = _wheel.Length - 1; // prevent overflow if (_tickDuration >= long.MaxValue / _wheel.Length) throw new ArgumentOutOfRangeException("akka.scheduler.tick-duration", _tickDuration, $"akka.scheduler.tick-duration: {_tickDuration} (expected: 0 < tick-duration in ticks < {long.MaxValue / _wheel.Length}"); _shutdownTimeout = SchedulerConfig.GetTimeSpan("akka.scheduler.shutdown-timeout"); }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="logLevel"></param> /// <param name="logMode"></param> public static void WriteLog(string message, enumLogLevel logLevel, string logMode) { try { if (logMode == "EVENTLOG") { if (_DefaultLoggingAdapter == null) _DefaultLoggingAdapter = GetObject(logMode); _DefaultLoggingAdapter.WriteLog(message, (int)(EventLogEntryType.Information)); } else { if (_LoggingAdapter == null) _LoggingAdapter = GetObject(logMode); _LoggingAdapter.WriteLog(message, (int)logLevel); } } catch (Exception) { throw; } }
public VirtualPathContainer(IActorRefProvider provider, ActorPath path, IInternalActorRef parent, ILoggingAdapter log) { _parent = parent; _log = log; _provider = provider; _path = path; }
/// <summary> /// Initializes a new instance of the <see cref="EventAdapters"/> class. /// </summary> /// <param name="map">TBD</param> /// <param name="bindings">TBD</param> /// <param name="log">TBD</param> protected EventAdapters(ConcurrentDictionary <Type, IEventAdapter> map, IEnumerable <KeyValuePair <Type, IEventAdapter> > bindings, ILoggingAdapter log) { _map = map; _bindings = bindings; _log = log; }
public void Recover(ILoggingAdapter log) { log.Info("Recover Old Application from Backup during Recover"); ZipFile.ExtractToDirectory(_backupFile, _backFrom, true); _backupFile.DeleteFile(); }
public RemoteMetricsOn(ExtendedActorSystem system) { _logFrameSizeExceeding = system.Settings.Config.GetByteSize("akka.remote.log-frame-size-exceeding"); _log = Logging.GetLogger(system, this); }
/// <summary> /// Initializes a new instance of the <see cref="RemoteSystemDaemon" /> class. /// </summary> /// <param name="system">The system.</param> /// <param name="path">The path.</param> /// <param name="parent">The parent.</param> /// <param name="terminator">TBD</param> /// <param name="log">TBD</param> public RemoteSystemDaemon(ActorSystemImpl system, ActorPath path, IInternalActorRef parent, IActorRef terminator, ILoggingAdapter log) : base(system.Provider, path, parent, log) { _terminator = terminator; _system = system; AddressTerminatedTopic.Get(system).Subscribe(this); }
/// <summary> /// TBD /// </summary> /// <param name="client">TBD</param> /// <param name="timeout">TBD</param> public ClientResponseTunnel(IActorRef client, TimeSpan timeout) { _client = client; _log = Context.GetLogger(); Context.SetReceiveTimeout(timeout); }
public TcpClientHandler(HeliosTransport wrappedTransport, ILoggingAdapter log, Address remoteAddress) : base(wrappedTransport, log) { _remoteAddress = remoteAddress; }
protected TcpHandlers(HeliosTransport wrappedTransport, ILoggingAdapter log) : base(wrappedTransport, log) { }
public Subscriber() { _log = Context.GetLogger(); _mediator = DistributedPubSub.Get(Context.System).Mediator; _mediator.Tell(new Subscribe("content", Self)); }
public static ISocketClient CreateClient(ClientConfigurationData conf, DnsEndPoint server, string hostName, ILoggingAdapter logger) { return(new SocketClient(conf, server, hostName, logger)); }
/// <summary> /// TBD /// </summary> /// <param name="system">TBD</param> public RemoteMetricsOn(ExtendedActorSystem system) { // TODO: Need to assert that config key exists _logFrameSizeExceeding = system.Settings.Config.GetByteSize("akka.remote.log-frame-size-exceeding", null); _log = Logging.GetLogger(system, this); }
public WorkerTracker(Dictionary <Item, ObjectStatus> currentItems) { _logger = Context.GetLogger(); _currentItemRecords = currentItems; InitialReceives(); }
/// <summary> /// <para>Await until the given condition evaluates to <c>true</c> or the timeout /// expires, whichever comes first.</para> /// <para>If no timeout is given, take it from the innermost enclosing `within` /// block.</para> /// <para>Note that the timeout is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor /// specified in config value "akka.test.timefactor".</para> /// <para>The parameter <paramref name="interval"/> specifies the time between calls to <paramref name="conditionIsFulfilled"/> /// Between calls the thread sleeps. If <paramref name="interval"/> is undefined the thread only sleeps /// one time, using the <paramref name="max"/> as duration, and then rechecks the condition and ultimately /// succeeds or fails.</para> /// <para>To make sure that tests run as fast as possible, make sure you do not leave this value as undefined, /// instead set it to a relatively small value.</para> /// </summary> /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param> /// <param name="max">The maximum duration. The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. /// scaled by the factor specified in config value "akka.test.timefactor".</param> /// <param name="interval">The time between calls to <paramref name="conditionIsFulfilled"/> to check /// if the condition is fulfilled. Between calls the thread sleeps. If undefined the thread only sleeps /// one time, using the <paramref name="max"/>, and then rechecks the condition and ultimately /// succeeds or fails. /// <para>To make sure that tests run as fast as possible, make sure you do not set this value as undefined, /// instead set it to a relatively small value.</para> /// </param> /// <param name="fail">Action that is called when the timeout expired. /// The parameters conforms to <see cref="string.Format(string,object[])"/></param> /// <param name="logger">If a <see cref="ILoggingAdapter"/> is specified, debug messages will be logged using it. If <c>null</c> nothing will be logged</param> protected static bool InternalAwaitCondition(Func<bool> conditionIsFulfilled, TimeSpan max, TimeSpan? interval, Action<string, object[]> fail, ILoggingAdapter logger) { max.EnsureIsPositiveFinite("max"); var start = Now; var stop = start + max; ConditionalLog(logger, "Awaiting condition for {0}.{1}", max, interval.HasValue ? " Will sleep " + interval.Value + " between checks" : ""); while (!conditionIsFulfilled()) { var now = Now; if (now > stop) { const string message = "Timeout {0} expired while waiting for condition."; ConditionalLog(logger, message, max); fail(message, new object[] { max }); return false; } var sleepDuration = (stop - now).Min(interval); Thread.Sleep(sleepDuration); } ConditionalLog(logger, "Condition fulfilled after {0}", Now-start); return true; }
/// <summary> /// TBD /// </summary> /// <param name="root">TBD</param> /// <param name="provider">TBD</param> /// <param name="terminationPromise">TBD</param> /// <param name="log">TBD</param> public RootGuardianSupervisor(RootActorPath root, IActorRefProvider provider, TaskCompletionSource <Status> terminationPromise, ILoggingAdapter log) { _log = log; _terminationPromise = terminationPromise; _provider = provider; _path = root / "_Root-guardian-supervisor"; //In akka this is root / "bubble-walker" }
public Timer(string name, object message, bool repeat, int generation, IActorContext context, ILoggingAdapter debugLog) { _debugLog = debugLog; Context = context; Generation = generation; Repeat = repeat; Message = message; Name = name; var scheduler = context.System.Scheduler; _scheduler = scheduler; _ref = new Cancelable(scheduler); }
public Bucket(ILoggingAdapter log) { _log = log; }
public TcpServerHandler(HeliosTransport wrappedTransport, ILoggingAdapter log, Task <IAssociationEventListener> associationEventListener) : base(wrappedTransport, log) { _associationEventListener = associationEventListener; }
protected TcpHandler(TcpTransport transport, ILoggingAdapter log) { this.Transport = transport; this.Log = log; }
protected AkkatectureReceiveActor() { Logger = Context.GetLogger(); }
/// <summary> /// Initializes a new instance of the <see cref="RemoteSystemDaemon" /> class. /// </summary> /// <param name="system">The system.</param> /// <param name="path">The path.</param> /// <param name="parent">The parent.</param> /// <param name="terminator"></param> /// <param name="log"></param> public RemoteSystemDaemon(ActorSystemImpl system, ActorPath path, IInternalActorRef parent,IActorRef terminator, ILoggingAdapter log) : base(system.Provider, path, parent, log) { _terminator = terminator; _system = system; AddressTerminatedTopic.Get(system).Subscribe(this); }
public static RealTimeInventoryFinalResult ProcessAndSendResult(this OperationResult <IRealTimeInventory> result, IRequestMessage requestMessage, Func <IRealTimeInventory, IInventoryServiceCompletedMessage> successResponseCompletedMessage, ILoggingAdapter logger, IRealTimeInventory realTimeInventory, IActorRef sender, IActorRef notificationActorRef, IPerformanceService performanceService) { logger?.Info(requestMessage.GetType().Name + " Request was " + (!result.IsSuccessful ? " NOT " : "") + " successful. Current Inventory : " + realTimeInventory.GetCurrentQuantitiesReport()); IInventoryServiceCompletedMessage response; if (!result.IsSuccessful) { response = result.ToInventoryOperationErrorMessage(requestMessage.ProductId); var message = "Error while trying to " + requestMessage.GetType() + " - The sender of the message is " + sender?.Path + result.Exception.ErrorMessage; notificationActorRef?.Tell(message); logger?.Error(message, requestMessage, result, realTimeInventory.GetCurrentQuantitiesReport()); } else { realTimeInventory = result.Data as RealTimeInventory; response = successResponseCompletedMessage(realTimeInventory); logger?.Info(response.GetType().Name + " Response was sent back. Current Inventory : " + realTimeInventory.GetCurrentQuantitiesReport() + " - The sender of the message is " + sender.Path); } sender?.Tell(response); notificationActorRef?.Tell(new RealTimeInventoryChangeMessage(realTimeInventory)); performanceService?.Increment("Completed " + requestMessage.GetType().Name); return(new RealTimeInventoryFinalResult(realTimeInventory as RealTimeInventory, response, result)); }
public ConductorHandler(IActorRef controller, ILoggingAdapter log) { _controller = controller; _log = log; }
public LoggingAdapter(ExtendedActorSystem system) { Log = system.Log; }
/// <summary> /// TBD /// </summary> /// <param name="system">TBD</param> /// <exception cref="NullReferenceException">TBD /// This exception is thrown when the default journal plugin, <c>journal.plugin</c> is not configured. /// </exception> public PersistenceExtension(ExtendedActorSystem system) { _system = system; _system.Settings.InjectTopLevelFallback(Persistence.DefaultConfig()); _config = system.Settings.Config.GetConfig("akka.persistence"); _log = Logging.GetLogger(_system, this); _defaultJournalPluginId = new Lazy <string>(() => { var configPath = _config.GetString("journal.plugin"); if (string.IsNullOrEmpty(configPath)) { throw new NullReferenceException("Default journal plugin is not configured"); } return(configPath); }, LazyThreadSafetyMode.ExecutionAndPublication); _defaultSnapshotPluginId = new Lazy <string>(() => { var configPath = _config.GetString("snapshot-store.plugin"); if (string.IsNullOrEmpty(configPath)) { if (_log.IsWarningEnabled) { _log.Warning("No default snapshot store configured! " + "To configure a default snapshot-store plugin set the `akka.persistence.snapshot-store.plugin` key. " + "For details see 'persistence.conf'"); } return(NoSnapshotStorePluginId); } return(configPath); }, LazyThreadSafetyMode.ExecutionAndPublication); _defaultInternalStashOverflowStrategy = new Lazy <IStashOverflowStrategy>(() => { var configuratorTypeName = _config.GetString("internal-stash-overflow-strategy"); var configuratorType = Type.GetType(configuratorTypeName); return(((IStashOverflowStrategyConfigurator)Activator.CreateInstance(configuratorType)).Create(_system.Settings.Config)); }); Settings = new PersistenceSettings(_system, _config); _config.GetStringList("journal.auto-start-journals").ForEach(id => { if (_log.IsInfoEnabled) { _log.Info("Auto-starting journal plugin `{0}`", id); } JournalFor(id); }); _config.GetStringList("journal.auto-start-snapshot-stores").ForEach(id => { if (_log.IsInfoEnabled) { _log.Info("Auto-starting snapshot store `{0}`", id); } SnapshotStoreFor(id); }); }
/// <summary> /// The main program entry-point. /// </summary> static void Main() { SynchronizationContext.SetSynchronizationContext( new SynchronizationContext() ); // All state data will be written to this directory. DirectoryInfo stateDirectory = new DirectoryInfo(Path.Combine( Directory.GetCurrentDirectory(), "_state" )); if (!stateDirectory.Exists) { stateDirectory.Create(); } ManualResetEvent completed = new ManualResetEvent(initialState: false); try { // Match colour for INFO messages from Akka logger. Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Starting ..."); using (ActorSystem system = ActorSystem.Create("orchestration-example", AkkaConfig)) { Console.WriteLine("Running."); IActorRef app = system.ActorOf(actor => { ILoggingAdapter log = null; IActorRef client = null; IActorRef jobStore = null; IActorRef launcher = null; IActorRef harvester = null; IActorRef dispatcher = null; actor.OnPreStart = context => { log = context.GetLogger(); log.Info("Connecting to Docker..."); context.System.Docker().RequestConnectLocal(context.Self); }; actor.Receive <Connected>((connected, context) => { log.Info("Connected to Docker API (v{0}) at '{1}'.", connected.ApiVersion, connected.EndpointUri); client = connected.Client; log.Info("Initialising job store..."); jobStore = context.ActorOf( // TODO: Decide on supervision strategy. JobStore.Create( stateDirectory.GetFile("job-store.json") ) ); context.Watch(jobStore); jobStore.Tell( new EventBusActor.Subscribe(context.Self) ); }); actor.Receive <EventBusActor.Subscribed>((subscribed, context) => { log.Info("Job store initialised."); log.Info("Initialising harvester..."); harvester = context.ActorOf(Props.Create( () => new Harvester(stateDirectory, jobStore) )); log.Info("Harvester initialised."); log.Info("Initialising dispatcher..."); launcher = context.ActorOf( Props.Create( () => new Launcher(client) ), name: Launcher.ActorName ); dispatcher = context.ActorOf( Dispatcher.Create(stateDirectory, jobStore, launcher), name: Dispatcher.ActorName ); // Wait for the dispatcher to start. Thread.Sleep( // TODO: Find a better way. TimeSpan.FromSeconds(1) ); log.Info("Dispatcher initialised."); log.Info("Creating job..."); jobStore.Tell(new JobStore.CreateJob( targetUrl: new Uri("https://ifconfig.co/json") )); }); actor.Receive <JobStoreEvents.JobCreated>((jobCreated, context) => { log.Info("Job {0} created.", jobCreated.Job.Id); }); actor.Receive <JobStoreEvents.JobStarted>((jobStarted, context) => { log.Info("Job {0} started.", jobStarted.Job.Id); dispatcher.Tell( new Dispatcher.NotifyWhenAllJobsCompleted() ); }); actor.Receive <JobStoreEvents.JobCompleted>((jobStarted, context) => { log.Info("Job {0} completed successfully.", jobStarted.Job.Id); foreach (string jobMessage in jobStarted.Job.Messages) { log.Info("-- {0}", jobMessage); } log.Info("-- Content:"); foreach (string contentLine in (jobStarted.Job.Content ?? String.Empty).Split('\n')) { log.Info("---- {0}", contentLine); } }); actor.Receive <JobStoreEvents.JobFailed>((jobStarted, context) => { log.Info("Job {0} failed.", jobStarted.Job.Id); foreach (string jobMessage in jobStarted.Job.Messages) { log.Info("-- {0}", jobMessage); } }); actor.Receive <Dispatcher.AllJobsCompleted>((allJobsCompleted, context) => { log.Info("All jobs completed."); completed.Set(); }); }, name: "app"); completed.WaitOne(); Console.WriteLine("Shutting down..."); system.Terminate().Wait(); } Console.WriteLine("Shutdown complete."); } catch (Exception unexpectedError) { Console.WriteLine(unexpectedError); } }
/// <summary> /// <para>Await until the given condition evaluates to <c>true</c> or the timeout /// expires, whichever comes first.</para> /// <para>If no timeout is given, take it from the innermost enclosing `within` /// block.</para> /// <para>Note that the timeout is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. scaled by the factor /// specified in config value "akka.test.timefactor".</para> /// <para>The parameter <paramref name="interval"/> specifies the time between calls to <paramref name="conditionIsFulfilled"/> /// Between calls the thread sleeps. If <paramref name="interval"/> is undefined the thread only sleeps /// one time, using the <paramref name="max"/> as duration, and then rechecks the condition and ultimately /// succeeds or fails.</para> /// <para>To make sure that tests run as fast as possible, make sure you do not leave this value as undefined, /// instead set it to a relatively small value.</para> /// </summary> /// <param name="conditionIsFulfilled">The condition that must be fulfilled within the duration.</param> /// <param name="max">The maximum duration. The value is <see cref="Dilated(TimeSpan)">dilated</see>, i.e. /// scaled by the factor specified in config value "akka.test.timefactor".</param> /// <param name="interval">The time between calls to <paramref name="conditionIsFulfilled"/> to check /// if the condition is fulfilled. Between calls the thread sleeps. If undefined the thread only sleeps /// one time, using the <paramref name="max"/>, and then rechecks the condition and ultimately /// succeeds or fails. /// <para>To make sure that tests run as fast as possible, make sure you do not set this value as undefined, /// instead set it to a relatively small value.</para> /// </param> /// <param name="fail">Action that is called when the timeout expired. /// The parameters conforms to <see cref="string.Format(string,object[])"/></param> /// <param name="logger">If a <see cref="ILoggingAdapter"/> is specified, debug messages will be logged using it. If <c>null</c> nothing will be logged</param> /// <returns>TBD</returns> protected static bool InternalAwaitCondition(Func <bool> conditionIsFulfilled, TimeSpan max, TimeSpan?interval, Action <string, object[]> fail, ILoggingAdapter logger) { max.EnsureIsPositiveFinite("max"); var start = Now; var stop = start + max; ConditionalLog(logger, "Awaiting condition for {0}.{1}", max, interval.HasValue ? " Will sleep " + interval.Value + " between checks" : ""); while (!conditionIsFulfilled()) { var now = Now; if (now > stop) { const string message = "Timeout {0} expired while waiting for condition."; ConditionalLog(logger, message, max); fail(message, new object[] { max }); return(false); } var sleepDuration = (stop - now).Min(interval); Thread.Sleep(sleepDuration); } ConditionalLog(logger, "Condition fulfilled after {0}", Now - start); return(true); }
public FactorialBackend() { Log = Logging.GetLogger(Context.System, this); }
public Destination() { _log = Context.GetLogger(); _mediator = DistributedPubSub.Get(Context.System).Mediator; _mediator.Tell(new Put(Self)); }
internal SocketClient(ClientConfigurationData conf, DnsEndPoint server, string hostName, ILoggingAdapter logger) { _server = server; if (conf.ClientCertificates != null) { _clientCertificates = conf.ClientCertificates; } if (conf.Authentication is AuthenticationTls tls) { _clientCertificates = tls.AuthData.TlsCertificates; } if (conf.TrustedCertificateAuthority != null) { _trustedCertificateAuthority = conf.TrustedCertificateAuthority; } _encrypt = conf.UseTls; _serviceUrl = conf.ServiceUrl; _clientConfiguration = conf; _logger = logger; _targetServerName = hostName; //_heartbeat.Start(); //_connectonId = $"{_networkstream.}"; }
/// <summary> /// Extensions depends on loggers being configured before Start() is called /// </summary> private void ConfigureLoggers() { _log = new BusLogging(_eventStream, "ActorSystem(" + _name + ")", GetType(), new DefaultLogMessageFormatter()); }
public RemotingTerminator(IActorRef systemGuardian) { _systemGuardian = systemGuardian; _log = Context.GetLogger(); InitFSM(); }
private static void ConditionalLog(ILoggingAdapter logger, string format, params object[] args) { if (logger != null) logger.Debug(format, args); }
public AkkaLoggingAdapter(ILoggingAdapter logger) => this._logger = logger;