Пример #1
0
        static async Task <int> MainAsync()
        {
            Logger.LogInformation("TemperatureFilter Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("config/appsettings.json", optional: true)
                                           .AddEnvironmentVariables()
                                           .Build();

            TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);

            ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync(
                transportType,
                ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                ModuleUtil.DefaultTransientRetryStrategy,
                Logger);

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            ModuleConfig moduleConfig = await GetConfigurationAsync(moduleClient);

            Logger.LogInformation($"Using TemperatureThreshold value of {moduleConfig.TemperatureThreshold}");

            var userContext = Tuple.Create(moduleClient, moduleConfig);
            await moduleClient.SetInputMessageHandlerAsync("input1", PrintAndFilterMessages, userContext);

            await cts.Token.WhenCanceled();

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("TemperatureFilter Main() finished.");
            return(0);
        }
Пример #2
0
        static async Task UpdateDeploymentEnvironmentVariablesAsync(TestResultReportingClient apiClient, CancellationTokenSource cts)
        {
            RegistryManager registryManager = null;

            try
            {
                registryManager = RegistryManager.CreateFromConnectionString(Settings.Current.IoTHubConnectionString.OrDefault());
                JObject deploymentJson = await GetEdgeAgentDeploymentManifestJsonAsync(registryManager, Settings.Current.DeviceId);

                DateTime testStartAt = DateTime.UtcNow;
                long     count       = 1;
                var      envVars     = new Dictionary <string, string>();

                while (!cts.IsCancellationRequested && DateTime.UtcNow - testStartAt < Settings.Current.TestDuration)
                {
                    KeyValuePair <string, string> newEnvVar     = AddEnvironmentValue(deploymentJson, Settings.Current.TargetModuleId.OrDefault(), count);
                    ConfigurationContent          configContent = JsonConvert.DeserializeObject <ConfigurationContent>(deploymentJson.ToString());
                    await registryManager.ApplyConfigurationContentOnDeviceAsync(Settings.Current.DeviceId, configContent);

                    envVars.Add(newEnvVar.Key, newEnvVar.Value);
                    var testResult = new DeploymentTestResult(Settings.Current.TrackingId, Settings.Current.ModuleId + ".send", envVars, DateTime.UtcNow);
                    await ModuleUtil.ReportTestResultAsync(apiClient, Logger, testResult);

                    Logger.LogInformation($"Successfully report to TRC for new deployment: tracking id={Settings.Current.TrackingId}, new environment variable={newEnvVar.Key}:{newEnvVar.Value}, EnvVars Count={envVars.Count}.");

                    await Task.Delay(Settings.Current.DeploymentUpdatePeriod, cts.Token);

                    count++;
                }
            }
            finally
            {
                registryManager?.Dispose();
            }
        }
Пример #3
0
        static async Task Main(string[] args)
        {
            Logger.LogInformation($"Starting Deployment Tester with the following settings: \r\n{Settings.Current}");

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            var testResultReportingClient = new TestResultReportingClient {
                BaseUrl = Settings.Current.TestResultCoordinatorUrl.AbsoluteUri
            };

            try
            {
                if (Settings.Current.TestMode == DeploymentTesterMode.Receiver)
                {
                    await ReportDeploymentEnvironmentVariablesAsync(testResultReportingClient);
                }
                else
                {
                    await Task.Delay(Settings.Current.TestStartDelay);
                    await UpdateDeploymentEnvironmentVariablesAsync(testResultReportingClient, cts);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Unexpected exception found.");
                await ModuleUtil.ReportTestResultAsync(testResultReportingClient, Logger, new ErrorTestResult(Settings.Current.TrackingId, Settings.Current.ModuleId, ex));
            }

            await cts.Token.WhenCanceled();

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("DeploymentTester Main() finished.");
        }
Пример #4
0
        static async Task Main(string[] args)
        {
            Logger.LogInformation($"Starting Relayer with the following settings: \r\n{Settings.Current}");
            ModuleClient moduleClient = null;

            try
            {
                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    Settings.Current.TransportType,
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy,
                    Logger);

                (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

                // Receive a message and call ProcessAndSendMessageAsync to send it on its way
                await moduleClient.SetInputMessageHandlerAsync(Settings.Current.InputName, ProcessAndSendMessageAsync, moduleClient);

                await cts.Token.WhenCanceled();

                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
                Logger.LogInformation("Relayer Main() finished.");
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occurred during Relayer.");
            }
            finally
            {
                moduleClient?.CloseAsync();
                moduleClient?.Dispose();
            }
        }
        public async Task StartAsync(
            DateTime runExpirationTime,
            DateTime edgeHubRestartedTime,
            CancellationToken cancellationToken)
        {
            (DateTime msgCompletedTime, HttpStatusCode mgsStatusCode) = await this.SendMessageAsync(
                Settings.Current.TrackingId,
                this.batchId,
                Settings.Current.MessageOutputEndpoint,
                runExpirationTime,
                cancellationToken);

            TestResultBase msgTestResult = new EdgeHubRestartMessageResult(
                this.GetSource(),
                DateTime.UtcNow,
                Settings.Current.TrackingId,
                this.batchId.ToString(),
                this.messageCount.ToString(),
                edgeHubRestartedTime,
                msgCompletedTime,
                mgsStatusCode);

            await ModuleUtil.ReportTestResultAsync(
                this.GetReportClient(),
                this.logger,
                msgTestResult,
                cancellationToken);
        }
Пример #6
0
        override protected void Append(LoggingEvent loggingEvent)
        {
            // Skip if DNN Dev Tools is not installed (to prevent errors with log messages just after module has been uninstalled)
            if (!ModuleUtil.IsInstalled())
            {
                return;
            }

            // Create log event
            var logMessageEvent = new LogMessage(loggingEvent);

            // Queue logging event
            LogMessageQueue.Enqueue(logMessageEvent);
            if (LogMessageQueue.Count > QueueSize)
            {
                LogMessage l;
                LogMessageQueue.TryDequeue(out l);
            }

            // Send log event to clients if log level is not too low
            var level = ServiceLocator.ConfigService.GetLogMessageTraceLevel();

            if (level.Value > loggingEvent.Level.Value)
            {
                return;
            }
            GlobalHost.ConnectionManager.GetHubContext <DnnDevToolsNotificationHub>().Clients.All.OnEvent(logMessageEvent);
        }
Пример #7
0
        static async Task ReportTestInfoAsync()
        {
            var testInfoResults = new string[]
            {
                $"Network Run Profile={Settings.Current.NetworkRunProfile}",
                $"Network Network Id={Settings.Current.NetworkId}",
                $"Network Frequencies={string.Join(",", Settings.Current.Frequencies.Select(f => $"[offline:{f.OfflineFrequency},Online:{f.OnlineFrequency},Runs:{f.RunsCount}]"))}"
            };

            var testResultReportingClient = new TestResultReportingClient()
            {
                BaseUrl = Settings.Current.TestResultCoordinatorEndpoint.AbsoluteUri
            };

            foreach (string testInfo in testInfoResults)
            {
                await ModuleUtil.ReportTestResultAsync(
                    testResultReportingClient,
                    Log,
                    new TestInfoResult(
                        Settings.Current.TrackingId,
                        Settings.Current.ModuleId,
                        testInfo,
                        DateTime.UtcNow));
            }
        }
Пример #8
0
    public static Behavior GetImportModulesBehavior(string filePath, List <Module> modules)
    {
        string previousFilePath = GlobalData.CurrentFilePath;

        return(new Behavior(isRedo => {
            int count = modules.Count;
            for (int idx = 0; idx < count; ++idx)
            {
                Module module = modules[idx];
                ModuleUtil.CreateModuleBehavior(module.Name,
                                                module.Elements,
                                                false,
                                                isRedo);
            }

            GlobalData.CurrentFilePath = filePath;
        },
                            isReUndo => {
            int count = modules.Count;
            for (int idx = 0; idx < count; ++idx)
            {
                Module module = modules[idx];
                ModuleUtil.RemoveModuleBehavior(module.Name);
            }

            GlobalData.CurrentFilePath = previousFilePath;
        },
                            BehaviorType.ImportModules,
                            false));
    }
Пример #9
0
        Settings(
            string eventHubConnectionString,
            string consumerGroupId,
            string deviceId,
            IList <string> excludedModuleIds,
            string webhostPort,
            double tolerance,
            string logAnalyticsWorkspaceIdName,
            string logAnalyticsSharedKeyName,
            string storagePath,
            bool storageOptimizeForPerformance,
            string testInfo)
        {
            Preconditions.CheckNonWhiteSpace(testInfo, nameof(testInfo));

            this.EventHubConnectionString = Preconditions.CheckNonWhiteSpace(eventHubConnectionString, nameof(eventHubConnectionString));
            this.ConsumerGroupId          = Preconditions.CheckNonWhiteSpace(consumerGroupId, nameof(consumerGroupId));
            this.DeviceId                = Preconditions.CheckNonWhiteSpace(deviceId, nameof(deviceId));
            this.ExcludedModuleIds       = excludedModuleIds;
            this.WebhostPort             = Preconditions.CheckNonWhiteSpace(webhostPort, nameof(webhostPort));
            this.ToleranceInMilliseconds = Preconditions.CheckRange(tolerance, 0);
            this.StoragePath             = storagePath;
            this.TestInfo                = ModuleUtil.ParseKeyValuePairs(testInfo, Logger, true);
            this.OptimizeForPerformance  = Preconditions.CheckNotNull(storageOptimizeForPerformance);
            this.LogAnalyticsWorkspaceId = logAnalyticsWorkspaceIdName;
            this.LogAnalyticsSharedKey   = logAnalyticsSharedKeyName;
        }
Пример #10
0
        static async Task Main()
        {
            Logger.LogInformation($"Starting load gen with the following settings:\r\n{Settings.Current}");

            ModuleClient moduleClient = null;

            try
            {
                (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

                Guid batchId = Guid.NewGuid();
                Logger.LogInformation($"Batch Id={batchId}");

                ClientOptions options = new ClientOptions();
                Settings.Current.ModelId.ForEach(m => options.ModelId = m);
                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    Settings.Current.TransportType,
                    options,
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy,
                    Logger);

                Logger.LogInformation($"Load gen delay start for {Settings.Current.TestStartDelay}.");
                await Task.Delay(Settings.Current.TestStartDelay);

                LoadGenSenderBase sender;
                switch (Settings.Current.SenderType)
                {
                case LoadGenSenderType.PriorityMessageSender:
                    sender = new PriorityMessageSender(Logger, moduleClient, batchId, Settings.Current.TrackingId);
                    break;

                case LoadGenSenderType.DefaultSender:
                default:
                    sender = new DefaultMessageSender(Logger, moduleClient, batchId, Settings.Current.TrackingId);
                    break;
                }

                DateTime testStartAt = DateTime.UtcNow;
                await sender.RunAsync(cts, testStartAt);

                Logger.LogInformation("Finish sending messages.");
                await cts.Token.WhenCanceled();

                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occurred during load gen.");
            }
            finally
            {
                Logger.LogInformation("Closing connection to Edge Hub.");
                moduleClient?.CloseAsync();
                moduleClient?.Dispose();
            }

            Logger.LogInformation("Load Gen complete. Exiting.");
        }
Пример #11
0
        static async Task <int> MainAsync()
        {
            Logger.LogInformation("DirectMethodReceiver Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("config/appsettings.json", optional: true)
                                           .AddEnvironmentVariables()
                                           .Build();

            TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);
            ModuleClient  moduleClient  = await ModuleUtil.CreateModuleClientAsync(
                transportType,
                ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                ModuleUtil.DefaultTransientRetryStrategy,
                Logger);

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            await moduleClient.OpenAsync();

            await moduleClient.SetMethodHandlerAsync("HelloWorldMethod", HelloWorldMethodAsync, null);

            await cts.Token.WhenCanceled();

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("DirectMethodReceiver Main() finished.");
            return(0);
        }
Пример #12
0
        static async Task <int> MainAsync()
        {
            Logger.LogInformation("DirectMethodSender Main() started.");

            IConfiguration configuration = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("config/appsettings.json", optional: true)
                                           .AddEnvironmentVariables()
                                           .Build();

            TimeSpan dmDelay = configuration.GetValue("DirectMethodDelay", TimeSpan.FromSeconds(5));
            // Get device id of this device, exposed as a system variable by the iot edge runtime
            string        targetDeviceId = configuration.GetValue <string>("IOTEDGE_DEVICEID");
            string        targetModuleId = configuration.GetValue("TargetModuleId", "DirectMethodReceiver");
            TransportType transportType  = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);

            ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync(
                transportType,
                ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                ModuleUtil.DefaultTransientRetryStrategy,
                Logger);

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

            await CallDirectMethod(moduleClient, dmDelay, targetDeviceId, targetModuleId, cts);

            await moduleClient.CloseAsync();

            completed.Set();
            handler.ForEach(h => GC.KeepAlive(h));
            Logger.LogInformation("DirectMethodSender Main() finished.");
            return(0);
        }
Пример #13
0
        /// <summary>
        /// 根据用户所指定文件类型输出报告
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="runtimeHash">运行时哈希值</param>
        /// <param name="reportType">报告类型枚举,有txt文件,xml文件,json文件,和自定义报告</param>
        /// <param name="customPrinter">可选参数,用于当reportType为custom的时候</param>
        public void PrintReport(string filePath, string runtimeHash, ReportType reportType, IResultPrinter customPrinter = null)
        {
            //检查文件路径正确与否
            string         newFilePath    = ModuleUtil.CheckFilePath(filePath);
            IResultPrinter _resultPrinter = null;

            switch (reportType)
            {
            case ReportType.txt:
                _resultPrinter = new TxtWriter();
                break;

            case ReportType.xml:
                _resultPrinter = new XMLWriter();
                break;

            case ReportType.json:
                _resultPrinter = new JsonWriter();
                break;

            case ReportType.custom:
                //需输入继承IResultPrinter的customPrinter的实例
                if (customPrinter == null)
                {
                    //如果实例为null则抛出异常
                    throw new TestflowRuntimeException(ModuleErrorCode.CustomWriterNonExistent, "Custom ResultPrinter required.");
                }
                _resultPrinter = customPrinter;    //继承IResultPrinter的自定义Printer
                break;
            }
            //输出报告
            _resultPrinter.PrintReport(newFilePath, runtimeHash);
        }
        public async Task StartAsync(
            DateTime runExpirationTime,
            DateTime edgeHubRestartedTime,
            CancellationToken cancellationToken)
        {
            (DateTime dmCompletedTime, HttpStatusCode dmStatusCode) = await this.SendDirectMethodAsync(
                Settings.Current.DeviceId,
                this.directMethodTargetModuleId,
                Settings.Current.DirectMethodName,
                runExpirationTime,
                cancellationToken);

            TestResultBase dmTestResult = new EdgeHubRestartDirectMethodResult(
                this.GetSource(),
                DateTime.UtcNow,
                Settings.Current.TrackingId,
                this.batchId,
                this.directMethodCount,
                edgeHubRestartedTime,
                dmCompletedTime,
                dmStatusCode);

            await ModuleUtil.ReportTestResultAsync(
                this.GetReportClient(),
                this.logger,
                dmTestResult,
                cancellationToken);
        }
Пример #15
0
        async Task SendStatus(string status)
        {
            var result = new LegacyTwinTestResult(this.moduleId, DateTime.UtcNow, status);

            Logger.LogDebug($"Sending report {result.GetFormattedResult()}");
            await ModuleUtil.ReportTestResultAsync(this.testResultReportingClient, Logger, result);
        }
Пример #16
0
        static async Task Main()
        {
            Logger.LogInformation($"Starting load gen with the following settings:\r\n{Settings.Current}");

            ModuleClient moduleClient = null;

            try
            {
                (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), Logger);

                Guid batchId = Guid.NewGuid();
                Logger.LogInformation($"Batch Id={batchId}");

                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    Settings.Current.TransportType,
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy,
                    Logger);

                Logger.LogInformation($"Load gen delay start for {Settings.Current.TestStartDelay}.");
                await Task.Delay(Settings.Current.TestStartDelay);

                DateTime testStartAt      = DateTime.UtcNow;
                long     messageIdCounter = 1;
                while (!cts.IsCancellationRequested &&
                       (Settings.Current.TestDuration == TimeSpan.Zero || DateTime.UtcNow - testStartAt < Settings.Current.TestDuration))
                {
                    try
                    {
                        await SendEventAsync(moduleClient, batchId, Settings.Current.TrackingId, messageIdCounter);

                        messageIdCounter++;
                        await Task.Delay(Settings.Current.MessageFrequency);

                        if (messageIdCounter % 1000 == 0)
                        {
                            Logger.LogInformation($"Sent {messageIdCounter} messages.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex, $"[SendEventAsync] Sequence number {messageIdCounter}, BatchId: {batchId.ToString()};");
                    }
                }

                Logger.LogInformation("Closing connection to Edge Hub.");
                await moduleClient.CloseAsync();

                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error occurred during load gen.");
                moduleClient?.Dispose();
            }

            Logger.LogInformation("Load Gen complete. Exiting.");
        }
Пример #17
0
    public static Behavior GetCreateModuleBehavior(string moduleName)
    {
        string currentModule = GlobalData.CurrentModule;

        return(new Behavior(isReDo => ModuleUtil.CreateModuleBehavior(moduleName),
                            isReUndo => ModuleUtil.RemoveModuleBehavior(moduleName, currentModule),
                            BehaviorType.CreateModule));
    }
        public async Task ProcessEventsAsync(IEnumerable <EventData> events)
        {
            Logger.LogInformation("Processing events from event hub.");

            if (events != null)
            {
                foreach (EventData eventData in events)
                {
                    eventData.Properties.TryGetValue(TestConstants.Message.TrackingIdPropertyName, out object trackingIdFromEvent);
                    eventData.SystemProperties.TryGetValue(DeviceIdPropertyName, out object deviceIdFromEvent);
                    eventData.SystemProperties.TryGetValue(ModuleIdPropertyName, out object moduleIdFromEvent);

                    Logger.LogDebug($"Received event from Event Hub: trackingId={(string)trackingIdFromEvent}, deviceId={(string)deviceIdFromEvent}, moduleId={(string)moduleIdFromEvent}");

                    if (!string.IsNullOrWhiteSpace((string)trackingIdFromEvent) &&
                        string.Equals(trackingIdFromEvent.ToString(), this.trackingId, StringComparison.OrdinalIgnoreCase) &&
                        !string.IsNullOrWhiteSpace((string)deviceIdFromEvent) &&
                        string.Equals(deviceIdFromEvent.ToString(), this.deviceId, StringComparison.OrdinalIgnoreCase) &&
                        !string.IsNullOrWhiteSpace((string)moduleIdFromEvent))
                    {
                        eventData.Properties.TryGetValue(TestConstants.Message.SequenceNumberPropertyName, out object sequenceNumberFromEvent);
                        eventData.Properties.TryGetValue(TestConstants.Message.BatchIdPropertyName, out object batchIdFromEvent);

                        Logger.LogDebug($"Received event from Event Hub: batchId={(string)batchIdFromEvent}, sequenceNumber={(string)sequenceNumberFromEvent}");

                        if (!string.IsNullOrWhiteSpace((string)sequenceNumberFromEvent) &&
                            !string.IsNullOrWhiteSpace((string)batchIdFromEvent))
                        {
                            if (long.TryParse(sequenceNumberFromEvent.ToString(), out long sequenceNumber))
                            {
                                DateTime enqueuedtime = GetEnqueuedTime(deviceIdFromEvent.ToString(), moduleIdFromEvent.ToString(), eventData);

                                // TODO: remove hardcoded eventHub string in next line
                                var result = new TestOperationResult(
                                    (string)moduleIdFromEvent + ".eventHub",
                                    TestOperationResultType.Messages.ToString(),
                                    ModuleUtil.FormatMessagesTestResultValue(
                                        (string)trackingIdFromEvent,
                                        (string)batchIdFromEvent,
                                        (string)sequenceNumberFromEvent),
                                    enqueuedtime);
                                await this.storage.AddResultAsync(result);

                                Logger.LogInformation($"Received event from Event Hub persisted to store: trackingId={(string)trackingIdFromEvent}, deviceId={(string)deviceIdFromEvent}, moduleId={(string)moduleIdFromEvent}, batchId={(string)batchIdFromEvent}, sequenceNumber={(string)sequenceNumberFromEvent}");
                            }
                            else
                            {
                                Logger.LogError($"Message for module [{moduleIdFromEvent}] and device [{this.deviceId}] contains invalid sequence number [{(string)sequenceNumberFromEvent}].");
                            }
                        }
                        else
                        {
                            Logger.LogDebug($"Message for module [{moduleIdFromEvent}] and device [{this.deviceId}] doesn't contain batch id and/or sequence number.");
                        }
                    }
                }
            }
        }
Пример #19
0
        static async Task <DateTime> RestartEdgeHubAsync(
            ServiceClient iotHubServiceClient,
            CancellationToken cancellationToken)
        {
            DateTime startAttemptTime = DateTime.UtcNow;

            CloudToDeviceMethod c2dMethod = new CloudToDeviceMethod("RestartModule");
            string payloadSchema          = "{{ \"SchemaVersion\": \"1.0\", \"Id\": \"{0}\" }}";
            string payload = string.Format(payloadSchema, "edgeHub");

            Logger.LogInformation("RestartModule Method Payload: {0}", payload);
            c2dMethod.SetPayloadJson(payload);

            while (true)
            {
                try
                {
                    // TODO: Introduce the offline scenario to use docker command.
                    CloudToDeviceMethodResult response = await iotHubServiceClient.InvokeDeviceMethodAsync(Settings.Current.DeviceId, "$edgeAgent", c2dMethod);

                    if ((HttpStatusCode)response.Status != HttpStatusCode.OK)
                    {
                        Logger.LogError($"Calling EdgeHub restart failed with status code {response.Status} : {response.GetPayloadAsJson()}.");
                    }
                    else
                    {
                        Logger.LogInformation($"Calling EdgeHub restart succeeded with status code {response.Status}.");
                    }

                    return(DateTime.UtcNow);
                }
                catch (Exception e)
                {
                    Logger.LogError($"Exception caught for payload {payload}: {e}");

                    if (Settings.Current.RestartPeriod < DateTime.UtcNow - startAttemptTime)
                    {
                        string         errorMessage = $"Failed to restart EdgeHub from {startAttemptTime} to {DateTime.UtcNow}:\n\n{e}\n\nPayload: {payload}";
                        TestResultBase errorResult  = new ErrorTestResult(
                            Settings.Current.TrackingId,
                            GetSource(),
                            errorMessage,
                            DateTime.UtcNow);

                        var reportClient = new TestResultReportingClient {
                            BaseUrl = Settings.Current.ReportingEndpointUrl.AbsoluteUri
                        };
                        await ModuleUtil.ReportTestResultAsync(
                            reportClient,
                            Logger,
                            errorResult,
                            cancellationToken);

                        throw;
                    }
                }
            }
        }
Пример #20
0
        private static async Task SetToggleConnectivityMethod(string networkInterfaceName, CancellationToken token)
        {
            // Setting GatewayHostname to empty, since the module will be talking directly to IoTHub, bypassing edge
            // NetworkController is on the host, so it should always have connection
            Environment.SetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME", string.Empty);
            ModuleClient moduleClient = await ModuleUtil.CreateModuleClientAsync(Settings.Current.TransportType, new ClientOptions(), ModuleUtil.DefaultTimeoutErrorDetectionStrategy, ModuleUtil.DefaultTransientRetryStrategy);

            await moduleClient.SetMethodHandlerAsync("toggleConnectivity", ToggleConnectivity, new Tuple <string, CancellationToken>(networkInterfaceName, token));
        }
Пример #21
0
        public Task ReportNetworkStatus(NetworkControllerOperation operation, NetworkControllerStatus networkControllerStatus, NetworkControllerType networkControllerType, bool success = true)
        {
            var networkController = new NetworkControllerResult()
            {
                Operation = operation.ToString(), OperationStatus = success ? "Success" : "Failed", NetworkControllerType = networkControllerType, NetworkControllerStatus = networkControllerStatus, TrackingId = this.trackingId
            };

            return(ModuleUtil.ReportStatus(this.trcClient, Log, this.moduleId, networkController.ToString(), TestOperationResultType.Network.ToString()));
        }
        async Task <Tuple <DateTime, HttpStatusCode> > SendMessageAsync(
            string trackingId,
            Guid batchId,
            string msgOutputEndpoint,
            DateTime runExpirationTime,
            CancellationToken cancellationToken)
        {
            ModuleClient moduleClient = await this.GetModuleClientAsync();

            this.messageCount++;

            while ((!cancellationToken.IsCancellationRequested) && (DateTime.UtcNow < runExpirationTime))
            {
                Message message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { data = DateTime.UtcNow.ToString() })));
                message.Properties.Add("sequenceNumber", this.messageCount.ToString());
                message.Properties.Add("batchId", batchId.ToString());
                message.Properties.Add("trackingId", trackingId);

                try
                {
                    // Sending the result via edgeHub
                    await moduleClient.SendEventAsync(msgOutputEndpoint, message);

                    this.logger.LogInformation($"[SendMessageAsync] Send Message with count {this.messageCount}: finished.");
                    return(new Tuple <DateTime, HttpStatusCode>(DateTime.UtcNow, HttpStatusCode.OK));
                }
                catch (Exception ex)
                {
                    if (ex is TimeoutException)
                    {
                        // TimeoutException is expected to happen while the EdgeHub is down.
                        // Let's log the attempt and retry the message send until successful
                        this.logger.LogDebug(ex, $"[SendMessageAsync] Exception caught with SequenceNumber {this.messageCount}, BatchId: {batchId.ToString()}");
                    }
                    else
                    {
                        string errorMessage = $"[SendMessageAsync] Exception caught with SequenceNumber {this.messageCount}, BatchId: {batchId.ToString()}";
                        this.logger.LogError(ex, errorMessage);

                        TestResultBase errorResult = new ErrorTestResult(
                            Settings.Current.TrackingId,
                            this.GetSource(),
                            errorMessage,
                            DateTime.UtcNow);

                        await ModuleUtil.ReportTestResultAsync(
                            this.GetReportClient(),
                            this.logger,
                            errorResult,
                            cancellationToken);
                    }
                }
            }

            return(new Tuple <DateTime, HttpStatusCode>(DateTime.UtcNow, HttpStatusCode.InternalServerError));
        }
Пример #23
0
        async Task SendReportAsync(string source, StatusCode statusCode, TwinCollection details, string exception = "")
        {
            var result = new TwinTestResult()
            {
                Operation = statusCode.ToString(), Properties = details, ErrorMessage = exception, TrackingId = this.trackingId
            };

            Logger.LogDebug($"Sending report {result.ToString()}");
            await ModuleUtil.ReportStatus(this.trcClient, Logger, source, result.ToString(), TestOperationResultType.Twin.ToString());
        }
Пример #24
0
    public static Behavior GetOpenModuleBehavior(string moduleName, CombineType combineType = CombineType.Independent)
    {
        string previousModuleName = GlobalData.CurrentModule;

        return(new Behavior(isRedo => ModuleUtil.OpenModule(moduleName),
                            isReUndo => ModuleUtil.OpenModule(previousModuleName),
                            BehaviorType.OpenModule,
                            false,
                            combineType));
    }
Пример #25
0
        static async Task <int> MainAsync()
        {
            Console.WriteLine($"{DateTime.Now.ToLocalTime()}>\t The PumpSimulator Main() has started.");
            SetupTelemetry();

            try
            {
                RetrieveSettingsFromConfig();

                var simulatorParameters = SimulatorParameters.Create();
                (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null);

                Console.WriteLine(
                    $"Initializing simulated sensor to send {(SendUnlimitedMessages(messageCount) ? "unlimited" : messageCount.ToString())} "
                    + $"messages, at an interval of {messageDelay.TotalSeconds} seconds.\n"
                    + $"To change this, set the environment variable {MessageCountConfigKey} to the number of messages that should be sent (set it to -1 to send unlimited messages).");

                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    protocol,
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy);

                ModuleClient userContext = moduleClient;
                reportedProperties = new TwinCollection();

                await moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdated, userContext);

                await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

                await moduleClient.SetMethodHandlerAsync("ping", PingMethod, null);

                await moduleClient.SetMethodHandlerAsync("check", CheckMethod, null);

                await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext);

                await RetrieveSettingsFromTwin(moduleClient);
                await SendEvents(moduleClient, messageCount, simulatorParameters, cts);

                await cts.Token.WhenCanceled();

                completed.Set();
                handler.ForEach(h => GC.KeepAlive(h));
                Console.WriteLine("SimulatedTemperatureSensor Main() finished.");
                return(0);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine($"{DateTime.Now.ToLocalTime()}>\t PumpSimulator Main() error.");
                Console.WriteLine(ex.Message);
                var telemetry = new ExceptionTelemetry(ex);
                telemetryClient.TrackException(telemetry);
                return(-1);
            }
        }
Пример #26
0
 public static void RemoveSelectedDisplayObjectOrModules()
 {
     if (GlobalData.CurrentSelectDisplayObjectDic.Count > 0)
     {
         DisplayObjectUtil.RemoveSelectedDisplayObject();
     }
     else
     {
         ModuleUtil.CheckRemoveCurrentModule();
     }
 }
Пример #27
0
        static async Task <int> Init()
        {
            Console.WriteLine("PumpModule Main() started.");
            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null);


            // Setup App Insights
            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY")))
            {
                Console.WriteLine($"\t\t AppInsights: Enabled");
                insights        = true;
                telemetryClient = new TelemetryClient();
                telemetryClient.Context.Device.Id = Environment.MachineName;
                telemetryClient.TrackEvent("Module started");
                telemetryClient.GetMetric("PumpCount").TrackValue(1);
            }

            try
            {
                var appSettings = SimulatorParameters.Create();
                debug = appSettings.Debug;

                Console.WriteLine(
                    $"\t\t Initializing Simulator MessageCount:{(SendUnlimitedMessages(appSettings.MessageCount) ? "unlimited" : appSettings.MessageCount.ToString())}");

                moduleClient = await ModuleUtil.CreateModuleClientAsync(
                    appSettings.Protocol,
                    ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                    ModuleUtil.DefaultTransientRetryStrategy);

                await moduleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdated, appSettings);

                await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

                await moduleClient.SetMethodHandlerAsync("ping", PingMethod, null);

                await moduleClient.SetMethodHandlerAsync("checkin", CheckInMethod, null);

                await RetrieveSettingsFromTwin(appSettings);
                await SendEvents(moduleClient, appSettings, cts);

                Console.WriteLine("PumpModule Main() finished.");
                return(0);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine($"{DateTime.Now.ToLocalTime()}>\t PumpSimulator Main() error.");
                Console.WriteLine(ex.Message);
                var telemetry = new ExceptionTelemetry(ex);
                telemetryClient.TrackException(telemetry);
                return(-1);
            }
        }
Пример #28
0
        public async Task InitAsync()
        {
            this.moduleClient = await ModuleUtil.CreateModuleClientAsync(
                this.configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only),
                ModuleUtil.DefaultTimeoutErrorDetectionStrategy,
                ModuleUtil.DefaultTransientRetryStrategy,
                this.logger);

            await this.moduleClient.OpenAsync();

            await this.moduleClient.SetMethodHandlerAsync("HelloWorldMethod", this.HelloWorldMethodAsync, null);
        }
        public ActionResult Index()
        {
            var model = new LocalizationEditorViewModel
            {
                Categories     = _persister.GetLocalizations(),
                Languages      = _persister.GetEnabledLanguages(),
                Versions       = _persister.GetTranslationFileVersions(),
                PowertoolsMode = !Settings.AutoPopulated.DisablePowertoolsMode
            };

            return(View(ModuleUtil.PathTo("Views/LocalizationEditor/Index.cshtml"), model));
        }
Пример #30
0
        private void OnCreated(object source, FileSystemEventArgs e)
        {
            // Do nothing if module has been uninstalled
            if (!ModuleUtil.IsInstalled())
            {
                return;
            }

            // Do nothing, if DNN Dev Tools or mail catch is not enabled
            if (!ServiceLocator.ConfigService.GetEnable() || !ServiceLocator.ConfigService.GetEnableMailCatch())
            {
                return;
            }

            Logger.DebugFormat("New mail in pickup folder detected (File: {0})", e.FullPath);

            // Start new background thread and wait until file is completely written and no longer locked
            new Thread(() =>
            {
                var start = DateTime.Now;
                var file  = new FileInfo(e.FullPath);
                while (true)
                {
                    Thread.Sleep(100);

                    // Break if file is not released after max timeout
                    if (start - DateTime.Now > new TimeSpan(0, 0, 1))
                    {
                        break;
                    }

                    // Test if file is still locked
                    if (FileUtil.IsFileLocked(file))
                    {
                        continue;
                    }

                    // Try to parse mail
                    var message = EmlFileParser.ParseEmlFile(e.FullPath);
                    if (message == null)
                    {
                        return;
                    }

                    // Send mail notification to clients
                    var mail = new Mail(System.IO.Path.GetFileNameWithoutExtension(e.Name), message);
                    GlobalHost.ConnectionManager.GetHubContext <DnnDevToolsNotificationHub>().Clients.All.OnEvent(mail);

                    break;
                }
            }).Start();
        }