Beispiel #1
0
        protected void TestKernelCrosscompilation(Type t_kernel)
        {
            var cfg = new CudaConfig {
                BlockDim = new dim3(16, 16, 1)
            };

            cfg.Codebase.OptIn(t => t.Assembly.GetName().Name == "Conflux.Playground");

            using (Runtimes.Activate(new CudaRuntime(cfg, t_kernel)))
            {
                var result       = JitCompiler.DoCompile(cfg, t_kernel);
                var s_ptx_actual = result.Ptx;
                var s_hir_actual = result.Hir.DumpAsText();

                var asm        = MethodInfo.GetCurrentMethod().DeclaringType.Assembly;
                var @namespace = MethodInfo.GetCurrentMethod().DeclaringType.Namespace;
                @namespace += ".Reference.";
                var ptx_fileName = asm.GetManifestResourceNames().SingleOrDefault2(
                    n => String.Compare(n, @namespace + t_kernel.Name + ".ptx", true) == 0);
                var hir_fileName = asm.GetManifestResourceNames().SingleOrDefault2(
                    n => String.Compare(n, @namespace + t_kernel.Name + ".hir", true) == 0);

                Verify(s_ptx_actual, ptx_fileName, "crosscompiled PTX", t_kernel);
                Verify(s_hir_actual, hir_fileName, "crosscompiled HIR", t_kernel);
            }
        }
Beispiel #2
0
        private static bool CanRunOnCurrentRuntime(Runtimes skippedRuntimes)
        {
            if (skippedRuntimes == Runtimes.None)
            {
                return(true);
            }

            if (TestPlatformHelper.IsNETCore)
            {
                if (skippedRuntimes.HasFlag(Runtimes.NETCore))
                {
                    return(false);
                }
            }
            else if (TestPlatformHelper.IsMono)
            {
                if (skippedRuntimes.HasFlag(Runtimes.Mono))
                {
                    return(false);
                }
            }
            else if (TestPlatformHelper.IsNETFramework)
            {
                if (skippedRuntimes.HasFlag(Runtimes.NETFramework))
                {
                    return(false);
                }
            }

            return(true);
        }
        private void DiscoverGMS2()
        {
            string runtimesPath = Environment.ExpandEnvironmentVariables(SettingsWindow.GameMakerStudio2RuntimesPath);

            if (!Directory.Exists(runtimesPath))
            {
                return;
            }

            Regex runtimePattern = new Regex(@"^runtime-(.*)$");

            foreach (var runtimePath in Directory.EnumerateDirectories(runtimesPath))
            {
                Match m = runtimePattern.Match(System.IO.Path.GetFileName(runtimePath));
                if (!m.Success)
                {
                    continue;
                }

                string runtimeRunner = System.IO.Path.Combine(runtimePath, @"windows\Runner.exe");
                if (!File.Exists(runtimeRunner))
                {
                    continue;
                }

                Runtimes.Add(new Runtime()
                {
                    Version = m.Groups[1].Value, Path = runtimeRunner
                });
            }
        }
Beispiel #4
0
 Object IRuntime.Execute(params Object[] args)
 {
     using (Runtimes.Activate(this))
     {
         return(Execute(args));
     }
 }
Beispiel #5
0
        public IEnumerable <string> ExpandRuntime(string runtime)
        {
            // Could this be faster? Sure! But we can refactor once it works and has tests
            yield return(runtime);

            // Try to expand the runtime based on the graph
            var deduper    = new HashSet <string>();
            var expansions = new List <string>();

            deduper.Add(runtime);
            expansions.Add(runtime);
            for (var i = 0; i < expansions.Count; i++)
            {
                // expansions.Count will keep growing as we add items, but thats OK, we want to expand until we stop getting new items
                RuntimeDescription desc;
                if (Runtimes.TryGetValue(expansions[i], out desc))
                {
                    // Add the inherited runtimes to the list
                    foreach (var inheritedRuntime in desc.InheritedRuntimes)
                    {
                        if (deduper.Add(inheritedRuntime))
                        {
                            yield return(inheritedRuntime);

                            expansions.Add(inheritedRuntime);
                        }
                    }
                }
            }
        }
 public void DiscoverRuntimes(string dataFilePath, UndertaleData data)
 {
     Runtimes.Clear();
     DiscoverGameExe(dataFilePath, data);
     DiscoverGMS2();
     DiscoverGMS1();
 }
Beispiel #7
0
        private void GenerateBatchFiles()
        {
            string relativeAppBase;

            if (NoSource)
            {
                relativeAppBase = string.Format(@"{0}\{1}\{2}\{3}\{4}",
                                                AppRootName,
                                                "packages",
                                                _project.Name,
                                                _project.Version,
                                                "root");
            }
            else
            {
                relativeAppBase = string.Format(@"{0}\{1}\{2}", AppRootName, "src", _project.Name);
            }

            const string template = @"
@""{0}{1}.exe"" --appbase ""%~dp0{2}"" Microsoft.Framework.ApplicationHost {3} %*
";

            foreach (var commandName in _project.Commands.Keys)
            {
                var runtimeFolder = string.Empty;
                if (Runtimes.Any())
                {
                    runtimeFolder = string.Format(@"%~dp0{0}\packages\{1}\bin\", AppRootName, Runtimes.First().Name);
                }

                File.WriteAllText(
                    Path.Combine(OutputPath, commandName + ".cmd"),
                    string.Format(template, runtimeFolder, Runtime.Constants.BootstrapperExeName, relativeAppBase, commandName));
            }
        }
Beispiel #8
0
        public void Emit()
        {
            Reports.Quiet.WriteLine("Copying to output path {0}", OutputPath);

            var mainProject = Projects.Single(project => project.Name == _project.Name);

            foreach (var deploymentPackage in Packages)
            {
                deploymentPackage.Emit(this);
            }

            foreach (var deploymentProject in Projects)
            {
                deploymentProject.Emit(this);
            }

            foreach (var deploymentRuntime in Runtimes)
            {
                deploymentRuntime.Emit(this);
            }

            mainProject.PostProcess(this);

            WriteGlobalJson();

            string relativeAppBase;

            if (NoSource)
            {
                relativeAppBase = Path.Combine(AppRootName, "packages", _project.Name,
                                               _project.Version.ToString(), "root");
            }
            else
            {
                relativeAppBase = Path.Combine(AppRootName, "src", _project.Name);
            }

            foreach (var commandName in _project.Commands.Keys)
            {
                const string template1 = @"
@""%~dp0{3}\packages\{2}\bin\klr.exe"" --appbase ""%~dp0{1}"" Microsoft.Framework.ApplicationHost {0} %*
";
                const string template2 = @"
@klr.exe --appbase ""%~dp0{1}"" Microsoft.Framework.ApplicationHost {0} %*
";
                if (Runtimes.Any())
                {
                    File.WriteAllText(
                        Path.Combine(OutputPath, commandName + ".cmd"),
                        string.Format(template1, commandName, relativeAppBase, Runtimes.First().Name, AppRootName));
                }
                else
                {
                    File.WriteAllText(
                        Path.Combine(OutputPath, commandName + ".cmd"),
                        string.Format(template2, commandName, relativeAppBase));
                }
            }
        }
Beispiel #9
0
        private void GenerateBashScripts()
        {
            string relativeAppBase;

            if (NoSource)
            {
                relativeAppBase = string.Format("{0}/{1}/{2}/{3}/{4}", AppRootName, "packages", _project.Name,
                                                _project.Version.ToString(), "root");
            }
            else
            {
                relativeAppBase = string.Format("{0}/{1}/{2}", AppRootName, "src", _project.Name);
            }

            const string template = @"#!/usr/bin/env bash

SOURCE=""${{BASH_SOURCE[0]}}""
while [ -h ""$SOURCE"" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""
  SOURCE=""$(readlink ""$SOURCE"")""
  [[ $SOURCE != /* ]] && SOURCE=""$DIR/$SOURCE"" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""

export SET {0}=""$DIR/{1}""

exec ""{2}{3}"" --appbase ""${0}"" Microsoft.Dnx.ApplicationHost --configuration {4} {5} ""$@""";

            foreach (var commandName in _project.Commands.Keys)
            {
                var runtimeFolder = string.Empty;
                if (Runtimes.Any())
                {
                    runtimeFolder = string.Format(@"$DIR/{0}/runtimes/{1}/bin/",
                                                  AppRootName, Runtimes.First().Name);
                }

                var scriptPath = Path.Combine(OutputPath, commandName);
                File.WriteAllText(scriptPath,
                                  string.Format(template,
                                                EnvironmentNames.AppBase,
                                                relativeAppBase,
                                                runtimeFolder,
                                                Runtime.Constants.BootstrapperExeName,
                                                Configuration,
                                                commandName).Replace("\r\n", "\n"));

                if (!RuntimeEnvironmentHelper.IsWindows)
                {
                    if (!FileOperationUtils.MarkExecutable(scriptPath))
                    {
                        Reports.Information.WriteLine("Failed to mark {0} as executable".Yellow(), scriptPath);
                    }
                }
            }
        }
Beispiel #10
0
        public bool Equals(RuntimeGraph other)
        {
            // Breaking this up to ease debugging. The optimizer should be able to handle this, so don't refactor unless you have data :).
            if (other == null)
            {
                return(false);
            }

            return(Runtimes.OrderedEquals(other.Runtimes, pair => pair.Key, StringComparer.Ordinal) &&
                   Supports.OrderedEquals(other.Supports, pair => pair.Key, StringComparer.Ordinal));
        }
Beispiel #11
0
        public PackageSettingsViewModel(IUnitTestEngine engine)
        {
            Runtimes = new[] { new DefaultRuntimeFramework() }
            .Concat(engine.TestEngine.Services.GetService <IAvailableRuntimes>().AvailableRuntimes)
            .ToList();

            PackageSettngs.DomainUsage      = "Default";
            PackageSettngs.IsRunAsX86       = false;
            PackageSettngs.ProcessModel     = "Default";
            PackageSettngs.RuntimeFramework = Runtimes.FirstOrDefault();
        }
Beispiel #12
0
        private void GenerateBatchFiles()
        {
            string relativeAppBase;

            if (NoSource)
            {
                relativeAppBase = $@"packages\{_project.Name}\{_project.Version}\root";
            }
            else
            {
                relativeAppBase = $@"src\{_project.Name}";
            }

            foreach (var commandName in _project.Commands.Keys)
            {
                var runtimeFolder = string.Empty;
                if (Runtimes.Any())
                {
                    runtimeFolder = Runtimes.First().Name;
                }

                var cmdPath   = Path.Combine(OutputPath, AppRootName, commandName + ".cmd");
                var cmdScript = $@"
@echo off
SET DNX_FOLDER={runtimeFolder}
SET ""LOCAL_DNX=%~dp0runtimes\%DNX_FOLDER%\bin\{Runtime.Constants.BootstrapperExeName}.exe""

IF EXIST %LOCAL_DNX% (
  SET ""DNX_PATH=%LOCAL_DNX%""
)

for %%a in (%DNX_HOME%) do (
    IF EXIST %%a\runtimes\%DNX_FOLDER%\bin\{Runtime.Constants.BootstrapperExeName}.exe (
        SET ""HOME_DNX=%%a\runtimes\%DNX_FOLDER%\bin\{Runtime.Constants.BootstrapperExeName}.exe""
        goto :continue
    )
)

:continue

IF ""%HOME_DNX%"" NEQ """" (
  SET ""DNX_PATH=%HOME_DNX%""
)

IF ""%DNX_PATH%"" == """" (
  SET ""DNX_PATH={Runtime.Constants.BootstrapperExeName}.exe""
)

@""%DNX_PATH%"" --project ""%~dp0{relativeAppBase}"" --configuration {Configuration} {commandName} %*
";
                File.WriteAllText(cmdPath, cmdScript);
            }
        }
Beispiel #13
0
        public void RecalculateProperties(IEnumerable <TimeSpan> runtimes)
        {
            if (runtimes == null || !runtimes.Any())
            {
                return;
            }

            Minimum      = Runtimes.Count > 0 ? Runtimes.Min().TotalMilliseconds : 0;
            Maximum      = Runtimes.Count > 0 ? Runtimes.Max().TotalMilliseconds : 0;
            Mean         = Runtimes.Count > 0 ? Runtimes.Average(x => x.TotalMilliseconds) : 0;
            Median       = Runtimes.Count > 0 ? Runtimes[runtimes.Count() / 2].TotalMilliseconds : 0;
            TotalRuntime = Runtimes.Count > 0 ? Runtimes.Select(x => x.TotalMilliseconds).Sum() : 0;
            CalculateStdDev();
        }
        public void Production_DotNet_Startup(string sampleName)
        {
            var framework            = "CoreCLR";
            var applicationFramework = Runtimes.GetFrameworkName(framework);
            var testName             = $"{sampleName}.{framework}.{nameof(Production_DotNet_Startup)}";
            var logger = LogUtility.LoggerFactory.CreateLogger(testName);

            var testProject = _sampleManager.GetDotNetPublishedSample(sampleName, applicationFramework);

            Assert.True(testProject != null, $"Fail to set up test project.");
            logger.LogInformation($"Test project is set up at {testProject}");

            var startInfo = GetStartInfo(testProject, sampleName);

            RunStartup(5000, logger, startInfo);
        }
Beispiel #15
0
 /// <summary>
 /// Find all possible dependencies for package id.
 /// </summary>
 private List <RuntimePackageDependency> FindRuntimeDependenciesInternal(RuntimeDependencyKey key)
 {
     // Find all compatible RIDs
     foreach (var expandedRuntime in ExpandRuntimeCached(key.RuntimeName))
     {
         RuntimeDescription runtimeDescription;
         if (Runtimes.TryGetValue(expandedRuntime, out runtimeDescription))
         {
             if (runtimeDescription.RuntimeDependencySets.TryGetValue(key.PackageId, out var dependencySet))
             {
                 return(dependencySet.Dependencies.Values.AsList());
             }
         }
     }
     return(new List <RuntimePackageDependency>());
 }
Beispiel #16
0
        private void GenerateBashScripts()
        {
            string relativeAppBase;

            if (NoSource)
            {
                relativeAppBase = $"packages/{_project.Name}/{_project.Version}/root";
            }
            else
            {
                relativeAppBase = $"src/{_project.Name}";
            }

            foreach (var commandName in _project.Commands.Keys)
            {
                var runtimeFolder = string.Empty;
                if (Runtimes.Any())
                {
                    var runtime = Runtimes.First().Name;
                    runtimeFolder = $@"$DIR/runtimes/{runtime}/bin/";
                }

                var scriptPath     = Path.Combine(OutputPath, AppRootName, commandName);
                var scriptContents = $@"#!/usr/bin/env bash

SOURCE=""${{BASH_SOURCE[0]}}""
while [ -h ""$SOURCE"" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""
  SOURCE=""$(readlink ""$SOURCE"")""
  [[ $SOURCE != /* ]] && SOURCE=""$DIR/$SOURCE"" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""

exec ""{runtimeFolder}{Runtime.Constants.BootstrapperExeName}"" --project ""$DIR/{relativeAppBase}"" --configuration {Configuration} {commandName} ""$@""";

                File.WriteAllText(scriptPath, scriptContents.Replace("\r\n", "\n"));

                if (!RuntimeEnvironmentHelper.IsWindows)
                {
                    if (!FileOperationUtils.MarkExecutable(scriptPath))
                    {
                        Reports.Information.WriteLine("Failed to mark {0} as executable".Yellow(), scriptPath);
                    }
                }
            }
        }
Beispiel #17
0
 public IEnumerable <RuntimePackageDependency> FindRuntimeDependencies(string runtimeName, string packageId)
 {
     // PERF: We could cache this for a particular (runtimeName,packageId) pair.
     foreach (var expandedRuntime in ExpandRuntime(runtimeName))
     {
         RuntimeDescription runtimeDescription;
         if (Runtimes.TryGetValue(expandedRuntime, out runtimeDescription))
         {
             RuntimeDependencySet dependencySet;
             if (runtimeDescription.RuntimeDependencySets.TryGetValue(packageId, out dependencySet))
             {
                 return(dependencySet.Dependencies.Values);
             }
         }
     }
     return(Enumerable.Empty <RuntimePackageDependency>());
 }
Beispiel #18
0
        private void GenerateBashScripts()
        {
            string relativeAppBase;

            if (NoSource)
            {
                relativeAppBase = string.Format("{0}/{1}/{2}/{3}/{4}", AppRootName, "packages", _project.Name,
                                                _project.Version.ToString(), "root");
            }
            else
            {
                relativeAppBase = string.Format("{0}/{1}/{2}", AppRootName, "src", _project.Name);
            }

            const string template = @"#!/bin/bash

SOURCE=""${{BASH_SOURCE[0]}}""
while [ -h ""$SOURCE"" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""
  SOURCE=""$(readlink ""$SOURCE"")""
  [[ $SOURCE != /* ]] && SOURCE=""$DIR/$SOURCE"" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR=""$( cd -P ""$( dirname ""$SOURCE"" )"" && pwd )""

export SET KRE_APPBASE=""$DIR/{0}""

""{1}klr"" Microsoft.Framework.ApplicationHost {2} ""$@""";

            foreach (var commandName in _project.Commands.Keys)
            {
                var klrFolder = string.Empty;
                if (Runtimes.Any())
                {
                    klrFolder = string.Format(@"$DIR/{0}/packages/{1}/bin/",
                                              AppRootName, Runtimes.First().Name);
                }

                var scriptPath = Path.Combine(OutputPath, commandName);
                File.WriteAllText(scriptPath,
                                  string.Format(template, relativeAppBase, klrFolder, commandName).Replace("\r\n", "\n"));
                if (PlatformHelper.IsMono)
                {
                    MarkExecutable(scriptPath);
                }
            }
        }
Beispiel #19
0
        public IEnumerable <RuntimePackageDependency> FindRuntimeDependencies(string runtimeName, string packageId)
        {
            if (_packagesWithDependencies == null)
            {
                // Find all packages that have runtime dependencies and cache this index.
                _packagesWithDependencies = new HashSet <string>(
                    Runtimes.SelectMany(e => e.Value.RuntimeDependencySets.Select(f => f.Key)),
                    StringComparer.OrdinalIgnoreCase);
            }

            if (_packagesWithDependencies.Contains(packageId))
            {
                var key = new RuntimeDependencyKey(runtimeName, packageId);

                return(_dependencyCache.GetOrAdd(key, k => FindRuntimeDependenciesInternal(k)));
            }

            return(Enumerable.Empty <RuntimePackageDependency>());
        }
Beispiel #20
0
        /// <summary>
        /// Gets all items of type <typeparamref name="T"/> from the data model.
        /// </summary>
        /// <typeparam name="T">The type of items to return.</typeparam>
        /// <returns>
        /// A sequence that contains all items of type <typeparamref name="T"/> from the data model.
        /// </returns>
        public IEnumerable <T> GetItems <T>()
            where T : XTypedElement, new()
        {
            // Constrain the search by namespace to improve performance
            var typeNamespace = typeof(T).Namespace;

            if (typeNamespace == ConceptualModelNamespace)
            {
                return(Runtimes.First().ConceptualModels.Query.Descendants <T>());
            }
            if (typeNamespace == StorageModelNamespace)
            {
                return(Runtimes.First().StorageModels.Query.Descendants <T>());
            }
            if (typeNamespace == MappingNamespace)
            {
                return(Runtimes.First().Mappings.Query.Descendants <T>());
            }
            return(Runtimes.First().Query.Descendants <T>());
        }
        private void DiscoverGameExe(string dataFilePath, UndertaleData data)
        {
            string gameExeName = data?.GeneralInfo?.Filename?.Content;

            if (gameExeName == null)
            {
                return;
            }

            string gameExePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dataFilePath), gameExeName + ".exe");

            if (!File.Exists(gameExePath))
            {
                return;
            }

            Runtimes.Add(new Runtime()
            {
                Version = "Game EXE", Path = gameExePath
            });
        }
        private void DiscoverGMS1()
        {
            string studioRunner = System.IO.Path.Combine(Environment.ExpandEnvironmentVariables(SettingsWindow.GameMakerStudioPath), "Runner.exe");

            if (!File.Exists(studioRunner))
            {
                return;
            }

            string studioDebugger = System.IO.Path.Combine(Environment.ExpandEnvironmentVariables(SettingsWindow.GameMakerStudioPath), @"GMDebug\GMDebug.exe");

            if (!File.Exists(studioDebugger))
            {
                studioDebugger = null;
            }

            Runtimes.Add(new Runtime()
            {
                Version = "1.4.xxx", Path = studioRunner, DebuggerPath = studioDebugger
            });
        }
Beispiel #23
0
        public IEnumerable <string> ExpandRuntime(string runtime)
        {
            // Could this be faster? Sure! But we can refactor once it works and has tests
            yield return(runtime);

            // Try to expand the runtime based on the graph
            var deduper = Cache <string> .RentHashSet();

            var expansions = Cache <string> .RentList();

            deduper.Add(runtime);
            expansions.Add(runtime);
            for (var i = 0; i < expansions.Count; i++)
            {
                // expansions.Count will keep growing as we add items, but thats OK, we want to expand until we stop getting new items
                RuntimeDescription desc;
                if (Runtimes.TryGetValue(expansions[i], out desc))
                {
                    // Add the inherited runtimes to the list
                    var inheritedRuntimes = desc.InheritedRuntimes;
                    var count             = inheritedRuntimes.Count;
                    for (var r = 0; r < count; r++)
                    {
                        var inheritedRuntime = inheritedRuntimes[r];
                        if (deduper.Add(inheritedRuntime))
                        {
                            yield return(inheritedRuntime);

                            expansions.Add(inheritedRuntime);
                        }
                    }
                }
            }

            Cache <string> .ReleaseHashSet(deduper);

            Cache <string> .ReleaseList(expansions);
        }
Beispiel #24
0
        public async Task <StressTestServerStartResult> StartAsync()
        {
            var framework    = "CoreCLR";
            var fullTestName = $"{_testMethodName}.{_testName}.{framework}";

            fullTestName = fullTestName.Replace('_', '.');

            var loggerFactory = LogUtility.LoggerFactory;

            _logger = loggerFactory.CreateLogger(fullTestName);

            var baseAddress = $"http://localhost:{_port}/";

            var p = new DeploymentParameters(
                PathHelper.GetTestAppFolder(_testName),
                _serverType,
                RuntimeFlavor.CoreClr,
                RuntimeArchitecture.x64)
            {
                SiteName = _testName,
                ApplicationBaseUriHint = baseAddress,
                TargetFramework        = Runtimes.GetFrameworkName(framework),
            };

            var deployerLoggerFactory = StressConfig.Instance.DeployerLogging ?
                                        loggerFactory :
                                        NullLoggerFactory.Instance;

            _applicationDeployer = ApplicationDeployerFactory.Create(p, deployerLoggerFactory);
            var deploymentResult = _applicationDeployer.DeployAsync().Result;

            baseAddress = deploymentResult.ApplicationBaseUri;

            _logger.LogInformation($"Test project is set up at {deploymentResult.ContentRoot}");

            var result = new StressTestServerStartResult
            {
                ServerHandle = this
            };
            var serverVerificationClient = new HttpClient
            {
                BaseAddress = new Uri(baseAddress)
            };

            HttpResponseMessage response = null;

            for (var i = 0; i < 20; ++i)
            {
                try
                {
                    _logger.LogInformation($"Pinging {serverVerificationClient.BaseAddress} to ensure server booted properly");
                    response = await serverVerificationClient.GetAsync(serverVerificationClient.BaseAddress);

                    break;
                }
                catch (TimeoutException)
                {
                    _logger.LogError("Http client timeout.");
                    break;
                }
                catch (Exception)
                {
                    _logger.LogInformation("Failed to ping server. Retrying...");
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                    continue;
                }
            }

            result.SuccessfullyStarted = false;
            if (response != null)
            {
                _logger.LogInformation($"Response {response.StatusCode}");

                if (response.IsSuccessStatusCode)
                {
                    _logger.LogInformation("Server started successfully");
                    result.SuccessfullyStarted = true;
                    ClientFactory = () => new RequestTrackingHttpClient(baseAddress, _metricCollector);
                }
            }

            return(result);
        }
Beispiel #25
0
 public override int GetHashCode()
 {
     return(Runtimes.GetHashCode());
 }
Beispiel #26
0
 /// <summary>
 /// Gets the .NET runtime location to use for extraction
 /// </summary>
 public static string GetRuntime(bool useSelfContained) => useSelfContained ? ExecutingRuntime : Runtimes.First();
Beispiel #27
0
 /// <summary>
 ///     Initialize an instance
 /// </summary>
 /// <param name="skippedRuntimes"></param>
 public SkipOnRuntimesAttribute(Runtimes skippedRuntimes)
 {
     _skippedRuntimes = skippedRuntimes;
 }
        public void GracefulExit(string sampleName)
        {
            var framework           = "CoreCLR";
            var appliationFramework = Runtimes.GetFrameworkName(framework);
            var testName            = $"{sampleName}.{framework}.{nameof(GracefulExit)}";
            var logger = LogUtility.LoggerFactory.CreateLogger(testName);

            var testProject = _sampleManager.GetDotNetPublishedSample(sampleName, appliationFramework);

            Assert.True(testProject != null, $"Fail to set up test project.");
            logger.LogInformation($"Test project is set up at {testProject}");

            var startInfo = GetStartInfo(testProject, sampleName);
            var process   = Process.Start(startInfo);
            HttpResponseMessage response = null;

            try
            {
                Task <HttpResponseMessage> webtask = null;
                var url = "http://localhost:5000/";
                var responseRetrived = false;
                using (var client = new HttpClient())
                {
                    for (var i = 0; i < _retry; ++i)
                    {
                        try
                        {
                            webtask = client.GetAsync(url);
                            if (webtask.Wait(_timeout))
                            {
                                responseRetrived = true;
                                break;
                            }
                            else
                            {
                                logger.LogError("Http client timeout.");
                                break;
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
                if (responseRetrived)
                {
                    response = webtask.Result;
                    response.EnsureSuccessStatusCode();
                }
            }
            finally
            {
                if (process != null && !process.HasExited)
                {
                    process.KillTree();
                }
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
Beispiel #29
0
        public void Emit()
        {
            Console.WriteLine("Copying to output path {0}", OutputPath);

            var mainProject = Projects.Single(project => project.Name == _project.Name);

            foreach (var deploymentPackage in Packages)
            {
                deploymentPackage.Emit(this);
            }

            foreach (var deploymentProject in Projects)
            {
                // TODO: temporarily we always emit sources for main project to make sure "k run"
                // can find entry point of the program. Later we should make main project
                // a nukpg too.
                if (deploymentProject == mainProject)
                {
                    deploymentProject.EmitSource(this);
                }
                else
                {
                    if (NoSource)
                    {
                        deploymentProject.EmitNupkg(this);
                    }
                    else
                    {
                        deploymentProject.EmitSource(this);
                    }
                }
            }

            foreach (var deploymentRuntime in Runtimes)
            {
                deploymentRuntime.Emit(this);
            }

            mainProject.PostProcess(this);

            WriteGlobalJson();

            foreach (var commandName in _project.Commands.Keys)
            {
                const string template1 = @"
@""%~dp0{3}\packages\{2}\bin\klr.exe"" --appbase ""%~dp0{1}"" Microsoft.Framework.ApplicationHost {0} %*
";
                const string template2 = @"
@klr.exe --appbase ""%~dp0{1}"" Microsoft.Framework.ApplicationHost {0} %*
";
                if (Runtimes.Any())
                {
                    File.WriteAllText(
                        Path.Combine(OutputPath, commandName + ".cmd"),
                        string.Format(template1, commandName, Path.Combine(AppRootName, "src", _project.Name),
                                      Runtimes.First().Name, AppRootName));
                }
                else
                {
                    File.WriteAllText(
                        Path.Combine(OutputPath, commandName + ".cmd"),
                        string.Format(template2, commandName, Path.Combine(AppRootName, "src", _project.Name)));
                }
            }
        }
        private async Task LoadAsync()
        {
            var rootUri = "https://api.nuviot.com/api/simulator/network/runtime";

            switch (_environment)
            {
            case Environments.Development:
                rootUri = "https://dev.nuviot.com/api/simulator/network/runtime";
                break;

            case Environments.Testing:
                rootUri = "https://test.nuviot.com/api/simulator/network/runtime";
                break;

            case Environments.LocalDevelopment:
                rootUri = "http://localhost:5001/api/simulator/network/runtime";
                break;

            default:
                break;
            }

            var requestId = Guid.NewGuid().ToId();
            var dateStamp = DateTime.UtcNow.ToJSONString();
            var version   = "1.0.0";

            var bldr = new StringBuilder();

            //Adding the \r\n manualy ensures that the we don't have any
            //platform specific code messing with our signature.
            bldr.Append($"{requestId}\r\n");
            bldr.Append($"{dateStamp}\r\n");
            bldr.Append($"{version}\r\n");
            bldr.Append($"{_org.Id}\r\n");
            bldr.Append($"{_user.Id}\r\n");
            bldr.Append($"{_simulatorNetworkId}\r\n");

            var sasKey = GetSignature(requestId, _simAccessKey, bldr.ToString());

            _adminLogger.AddCustomEvent(Core.PlatformSupport.LogLevel.Message, "SimulatorRuntimeManager_InitAsync", $"Requesting configuration from: {rootUri} ");
            Console.WriteLine($"Requesting configuration from: {rootUri}");


            var client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("SAS", sasKey);
            client.DefaultRequestHeaders.Add(REQUEST_ID, requestId);
            client.DefaultRequestHeaders.Add(ORG_ID, _org.Id);
            client.DefaultRequestHeaders.Add(ORG, _org.Text);
            client.DefaultRequestHeaders.Add(USER_ID, _user.Id);
            client.DefaultRequestHeaders.Add(USER, _user.Text);
            client.DefaultRequestHeaders.Add(NETWORK_ID, _simulatorNetworkId);
            client.DefaultRequestHeaders.Add(DATE, dateStamp);
            client.DefaultRequestHeaders.Add(VERSION, version);

            try
            {
                var json = await client.GetStringAsync(rootUri);

                Runtimes.Clear();

                var network = JsonConvert.DeserializeObject <SimulatorNetwork>(json);
                Console.WriteLine($"Loaded simulator network {network.Name}");

                foreach (var sim in network.Simulators)
                {
                    var services = _factory.GetServices();
                    var runtime  = new SimulatorRuntime(services, Publisher, _adminLogger, sim);
                    await runtime.StartAsync();

                    Runtimes.Add(runtime);
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error loading runtime.");
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }
        }