예제 #1
0
 public static RemoteProcess AddRemoteProcess(Participant participant, LocalProcess locaProcess)
 {
     using (DaemonEntities entities = new DaemonEntities())
     {
         try
         {
             entities.Attach(locaProcess);
             entities.Attach(participant);
             RemoteProcess remoteProcess = new RemoteProcess
             {
                 RemoteProcessId = Guid.NewGuid(),
                 LocalProcess    = locaProcess,
                 Participant     = participant,
                 Address         = "127.0.0.1",
                 HubPort         = MxpConstants.DefaultHubPort,
                 Trusted         = false
             };
             entities.AddToRemoteProcess(remoteProcess);
             entities.SaveChanges();
             entities.Detach(remoteProcess);
             return(remoteProcess);
         }
         finally
         {
             entities.Detach(locaProcess);
             entities.Detach(participant);
         }
     }
 }
예제 #2
0
        public static HackContext CreateContext(System.Diagnostics.Process process, WinAPI.ProcessAccessFlags flags = WinAPI.ProcessAccessFlags.All)
        {
            var proc = new LocalProcess(process);
            var mem  = proc.CreateMemoryInterface(flags, true);

            return(new LocalHackContext(proc, mem));
        }
예제 #3
0
 public static Bubble AddBuble(Participant participant, LocalProcess localProcess)
 {
     using (DaemonEntities entities = new DaemonEntities())
     {
         try
         {
             entities.Attach(participant);
             entities.Attach(localProcess);
             Bubble bubble = new Bubble
             {
                 BubbleId        = Guid.NewGuid(),
                 Participant     = participant,
                 LocalProcess    = localProcess,
                 Name            = "New Bubble",
                 Range           = 100,
                 PerceptionRange = 150,
                 Published       = false
             };
             entities.AddToBubble(bubble);
             entities.SaveChanges();
             entities.Detach(bubble);
             return(bubble);
         }
         finally
         {
             entities.Detach(participant);
             entities.Detach(localProcess);
         }
     }
 }
예제 #4
0
 private PwnieHax(LocalProcess process) : base(process, process.CreateMemoryInterface(WinAPI.ProcessAccessFlags.All, true))
 {
     //Initialize & set up low-level keyboard hook
     keyboard = new KeyboardHook();
     keyboard.Hook();
     keyboard.KeyUp   += (o, e) => { OnKeyUp(e.Key); };
     keyboard.KeyDown += (o, e) => { OnKeyDown(e.Key); };
     mouse             = new MouseHook();
     mouse.Hook();
     mouse.MouseEvent += Mouse_MouseEvent;
     //Initialize & set up overlay
     Overlay          = new GameOverlay(this, "PwnieHax");
     Overlay.Drawing += Overlay_Drawing;
     Overlay.DrawOnlyWhenInForeground = false;
     Overlay.RegisterHooks(keyboard, mouse);
     MainForm = Overlay;
     //
     performanceLabel = new SuperiorHackBase.Graphics.Controls.Label()
     {
         Text      = "- FPS\n- read\n- write",
         AutoSize  = true,
         BackColor = BrushDescription.Transparent,
         ForeColor = BrushDescription.White,
         Location  = new Vector2(4, 4),
         Font      = new FontDescription("Courier New", 12f)
     };
     Overlay.RootControl.AddChild(performanceLabel);
     fps = new RoundRobinBuffer(60);
 }
예제 #5
0
        /// <summary>
        ///     Create a string with values of monitored local processes
        /// </summary>
        public static void CreateMonitoredProcessesRecord(LocalProcess p, ref StringBuilder sb)
        {
            p.GetProcessorCpuTime();
            p.GetMemUsed();

            Console.WriteLine();
            Console.WriteLine("-- " + p.ProcessName.ToUpper());

            foreach (var pair in _dictMonitoredProcesses)
            {
                switch (pair.Key)
                {
                case "MonitoredProcessesCPUProcessorTime":
                    if (pair.Value)
                    {
                        sb.Append(p.CpuProcessorTime + StrSeparator);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine("CPU time          : {0} %", p.CpuProcessorTime);
                        Console.ResetColor();
                    }
                    break;

                case "MonitoredProcessesMEMUsed":
                    if (pair.Value)
                    {
                        sb.Append(p.MemUsed + StrSeparator);
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("Mem Used          : {0} MB", p.MemUsed);
                        Console.ResetColor();
                    }
                    break;
                }
            }
        }
예제 #6
0
 public static LocalProcess GetLocalProcess(Guid localProcessId)
 {
     using (DaemonEntities entities = new DaemonEntities())
     {
         LocalProcess localProcess = QueryUtil.First <LocalProcess>((from p in entities.LocalProcess where p.LocalProcessId == localProcessId select p));
         entities.Detach(localProcess);
         return(localProcess);
     }
 }
예제 #7
0
        public void TestMethod1()
        {
            //using (var notepad = new RemoteProcess(Environment.SystemDirectory + "\\notepad.exe", "localhost"))
            //{
            //    notepad.Start();
            //}

            using (var notepad = new LocalProcess(Environment.SystemDirectory + "\\notepad.exe"))
            {
                notepad.Start();
            }
        }
예제 #8
0
        public void TestMethod1()
        {
            //using (var notepad = new RemoteProcess(Environment.SystemDirectory + "\\notepad.exe", "localhost"))
            //{
            //    notepad.Start();
            //}

            using (var notepad = new LocalProcess(Environment.SystemDirectory + "\\notepad.exe"))
            {
                notepad.Start();
            }
        }
예제 #9
0
        protected void AddBubbleButton_Click(object sender, EventArgs e)
        {
            if (LocalProcessList.SelectedValue == null || LocalProcessList.SelectedValue == "")
            {
                return;
            }
            Guid         localProcessId = new Guid(LocalProcessList.SelectedValue);
            LocalProcess localProcess   = LocalProcessLogic.GetLocalProcess(localProcessId);
            Bubble       bubble         = BubbleLogic.AddBuble(DaemonHttpContext.LoggedInParticipant, localProcess);

            Response.Redirect(Request.Url.OriginalString);
        }
예제 #10
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            process           = new LocalProcess();
            process.OnExited += () => {
                View.Window.Close();
            };

            terminalControl         = new ProcessTerminalView(View.Bounds);
            terminalControl.Process = process;

            terminalControl.TitleChanged += TerminalControl_TitleChanged;
            View.AddSubview(terminalControl);

            process.Start();
        }
예제 #11
0
        private static LocalProcess GetWorkerProcess(int port, int unhealthyAfterSeconds,
                                                     int currentRequests = 0)
        {
            string exePath = GetExePath();

            var managedProcess = new LocalProcess(
                WellKnownAgentType.Worker.ToString(), exePath,
                $"{port} {unhealthyAfterSeconds} {currentRequests}",
                "localhost", port);

            managedProcess.ServiceNames.Add("Worker");

            managedProcess.PrioritizeAvailability = true;

            return(managedProcess);
        }
예제 #12
0
        internal LocalMemory(LocalProcess process, bool raiseExceptions, WinAPI.ProcessAccessFlags flags)
        {
            this.process         = process;
            this.raiseExceptions = raiseExceptions;
            this.pageCacheTime   = DateTime.MinValue;
            PageCacheDuration    = TimeSpan.FromSeconds(5);

            if ((flags & WinAPI.ProcessAccessFlags.VirtualMemoryRead) == 0)
            {
                throw new ArgumentException("Flags require at least ProcessAccessFlags.VirtualMemoryRead to be set");
            }

            MemoryHandle = WinAPI.OpenProcess(flags, false, process.PID);
            if (MemoryHandle == IntPtr.Zero)
            {
                throw new Exception("Failed to aquire memory handle", new Win32Exception(Marshal.GetLastWin32Error()));
            }
        }
        /// <summary>
        /// read the config and initialize. Can throw exceptions which will be cleanly caught by
        /// the parent
        /// </summary>
        /// <param name="p">parent to use for callbacks</param>
        /// <param name="name">name of this group in the service</param>
        /// <param name="config">element describing configuration parameters</param>
        public void Initialize(IServiceManager p, string name, XElement config)
        {
            parent       = p;
            logger       = parent.Logger;
            groupName    = name;
            shuttingDown = false;

            // read the target number of processes out of the config. This defaults to 1
            // if not otherwise specified
            int numberOfProcesses = 1;
            var nProcAttr         = config.Attribute("numberOfProcesses");

            if (nProcAttr != null)
            {
                // don't worry about throwing exceptions if this is malformed
                numberOfProcesses = int.Parse(nProcAttr.Value);
            }

            // read the target number of restarts for each process out of the config. This defaults to 5
            // if not otherwise specified
            numberOfVersions = 5;
            var nRestartAttr = config.Attribute("numberOfVersions");

            if (nRestartAttr != null)
            {
                // don't worry about throwing exceptions if this is malformed
                numberOfVersions = int.Parse(nRestartAttr.Value);
            }

            // make a logical process object for each process we are managing
            processes = new LocalProcess[numberOfProcesses];
            for (int i = 0; i < processes.Length; ++i)
            {
                processes[i] = new LocalProcess(this, i);
            }

            // read the descriptor that we will use to create physical processes.
            // don't worry about throwing exceptions if this isn't present or is
            // malformed
            var processElement = config.Descendants("Process").Single();

            processDetails = new ExeDetails();
            processDetails.ReadFromConfig(processElement, logger);
        }
예제 #14
0
        public Task <bool> Set(IWorkContext context)
        {
            Verify.IsNotNull(nameof(context), context);
            context        = context.WithTag(_tag);
            ProcessStarted = false;

            AssertFileExists(context);

            Task t = new LocalProcess()
                     .SetFile(ExeFullFile)
                     .SetWorkingDirectory(Path.GetDirectoryName(ExeFullFile))
                     .SetArguments(Arguments)
                     .SetOutputAction(OutputToLogging)
                     .RunInBackground(context, context.CancellationToken);

            Interlocked.Exchange(ref _hostTask, t);
            ProcessStarted = true;

            return(Task.FromResult(true));
        }
예제 #15
0
        /// <summary>
        ///     Create a string with record header with a list of monitored local processes
        /// </summary>
        public static void CreateMonitoredProcessesFileHeader(LocalProcess p, StringBuilder sb)
        {
            foreach (var pair in _dictMonitoredProcesses)
            {
                switch (pair.Key)
                {
                case "MonitoredProcessesCPUProcessorTime":
                    if (pair.Value)
                    {
                        sb.Append(p.ProcessName + "|" + "CPU time %" + StrSeparator);
                    }
                    break;

                case "MonitoredProcessesMEMUsed":
                    if (pair.Value)
                    {
                        sb.Append(p.ProcessName + "|" + "Mem Used MB" + StrSeparator);
                    }
                    break;
                }
            }
        }
예제 #16
0
        public static LocalProcess ReserveLocalProcess(Participant participant, string address)
        {
            using (DaemonEntities entities = new DaemonEntities())
            {
                entities.Attach(participant);

                try
                {
                    int serverPort = MxpConstants.DefaultServerPort;
                    if ((from l in entities.LocalProcess select l).Count() > 0)
                    {
                        serverPort = (from l in entities.LocalProcess select l).Max(l => l.ServerPort) + 2;
                    }
                    int hubPort = serverPort + 1;

                    LocalProcess localProcess = new LocalProcess
                    {
                        LocalProcessId = Guid.NewGuid(),
                        Participant    = participant,
                        Name           = "(" + serverPort + "," + hubPort + ")",
                        Address        = address,
                        ServerPort     = serverPort,
                        HubPort        = hubPort,
                        Enabled        = false
                    };

                    entities.AddToLocalProcess(localProcess);
                    entities.SaveChanges();
                    entities.Detach(localProcess);

                    return(localProcess);
                }
                finally
                {
                    entities.Detach(participant);
                }
            }
        }
예제 #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World! Starting cluster...");

            ILoggerFactory loggerFactory =
                LoggerFactory.Create(builder => { builder.AddConsole(); });

            Log.SetLoggerFactory(loggerFactory);

            Cluster cluster = new Cluster();

            // Test process that becomes unhealthy after 75 seconds
            LocalProcess localProcessWithBadHealth = GetWorkerProcess(5432, 75);

            cluster.Add(localProcessWithBadHealth);

            // Test recycling by cluster after 3 minutes
            LocalProcess localProcessWithGoodHealth = GetWorkerProcess(5433, -1);

            localProcessWithGoodHealth.RecyclingIntervalHours = 0.05;
            cluster.Add(localProcessWithGoodHealth);

            // Test recycling for busy process after 4.5 minutes
            LocalProcess localProcessWithGoodHealthButAlwaysBusy = GetWorkerProcess(5434, -1, 1);

            localProcessWithGoodHealthButAlwaysBusy.RecyclingIntervalHours = 0.075;
            cluster.Add(localProcessWithGoodHealthButAlwaysBusy);

            _ = cluster.StartAsync();

            Console.WriteLine("Press any key to finish");

            Console.ReadKey();

            cluster.Abort();
        }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = null;

        if (startInfo.Parameters != null)
        {
            parameters = HandlerUtils.Deserialize <CommandHandlerParameters>(startInfo.Parameters);
        }

        try
        {
            OnLogMessage("Execute", $"Running Handler As User [{System.Security.Principal.WindowsIdentity.GetCurrent().Name}]");

            Validate();

            // Replace Any "Special" Handler Variables In Arguments or ReplaceWith elements
            variables            = HandlerUtils.GatherVariables(this, startInfo);
            parameters.Arguments = HandlerUtils.ReplaceHandlerVariables(parameters.Arguments, variables);
            if (parameters.Expressions != null)
            {
                foreach (RegexArguments expression in parameters.Expressions)
                {
                    expression.ReplaceWith = HandlerUtils.ReplaceHandlerVariables(expression.ReplaceWith, variables);
                }
            }

            String args = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);

            bool isDryRun = startInfo.IsDryRun && !(config.SupportsDryRun);
            if (startInfo.IsDryRun && config.SupportsDryRun)
            {
                OnLogMessage("Execute", "DryRun Flag is set, but plan config indicates the command supports DryRun.  Command will execute.");
            }

            if (String.IsNullOrEmpty(config.RunOn))
            {
                SecurityContext runAs = startInfo.RunAs;
                if (runAs != null && runAs.HasCrypto)
                {
                    runAs = startInfo.RunAs.GetCryptoValues(startInfo.RunAs.Crypto, false);
                }
                result = LocalProcess.RunCommand(config.Command, args, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, SynapseLogger, null, isDryRun, config.ReturnStdout, runAs?.Domain, runAs?.UserName, runAs?.Password);
            }
            else
            {
                result = WMIUtil.RunCommand(config.Command, args, config.RunOn, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, config.KillRemoteProcessOnTimeout, SynapseLogger, config.RunOn, isDryRun, config.ReturnStdout);
            }

            if (result.Status == StatusType.None)
            {
                result.Status = HandlerUtils.GetStatusType(result.ExitCode, config.ValidExitCodes);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            throw e;
        }

        OnLogMessage(config.RunOn, "Command finished with exit code = " + result.ExitCode + ".  Returning status [" + result.Status + "].");

        return(result);
    }
예제 #19
0
        public override void Import(IBuildImporterContext context)
        {
            var configurer = (NuGetConfigurer)this.GetExtensionConfigurer();

            if (configurer.AlwaysClearNuGetCache)
            {
                this.LogDebug("Clearing NuGet cache...");
                if (NuGetConfigurer.ClearCache())
                {
                    this.LogDebug("Cache cleared!");
                }
                else
                {
                    this.LogWarning("Error clearing cache; a file may be locked.");
                }
            }

            var nugetExe = configurer != null ? configurer.NuGetExe : null;

            if (string.IsNullOrEmpty(nugetExe))
            {
                nugetExe = Path.Combine(Path.GetDirectoryName(typeof(NuGetBuildImporter).Assembly.Location), "nuget.exe");
            }

            var packageSource = Util.CoalesceStr(this.PackageSource, configurer != null ? configurer.PackageSource : null);

            var args = "install \"" + this.PackageId + "\" -ExcludeVersion -NoCache";

            if (!string.IsNullOrEmpty(this.PackageVersion))
            {
                args += " -Version \"" + this.PackageVersion + "\"";
            }
            if (this.IncludePrerelease)
            {
                args += " -Prerelease";
            }
            if (!string.IsNullOrEmpty(packageSource))
            {
                args += " -Source \"" + packageSource + "\"";
            }

            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                Directory.CreateDirectory(tempPath);

                args += " -OutputDirectory \"" + tempPath + "\"";

                if (!string.IsNullOrWhiteSpace(this.AdditionalArguments))
                {
                    args += " " + this.AdditionalArguments;
                }

                this.LogDebug($"Executing {nugetExe} {args}");
                this.LogInformation("Executing NuGet...");

                using (var process = new LocalProcess(new RemoteProcessStartInfo {
                    FileName = nugetExe, Arguments = args
                }))
                {
                    process.OutputDataReceived += this.Process_OutputDataReceived;
                    process.ErrorDataReceived  += this.Process_ErrorDataReceived;
                    process.Start();
                    process.WaitForExit();

                    if (process.ExitCode != 0)
                    {
                        this.LogError($"NuGet failed with exit code {process.ExitCode}.");
                        return;
                    }
                }

                this.LogInformation("NuGet indicated successful package install.");

                var packageRootPath = Path.Combine(tempPath, this.PackageId);
                var artifactName    = this.PackageId;

                if (this.CaptureIdAndVersion || this.IncludeVersionInArtifactName)
                {
                    try
                    {
                        var nupkgPath = Path.Combine(packageRootPath, this.PackageId + ".nupkg");
                        this.LogDebug($"Attempting to gather metadata from {nupkgPath}...");
                        var nuspec = NuGetPackage.ReadFromNupkgFile(nupkgPath);

                        var packageId      = nuspec.Id;
                        var packageVersion = nuspec.Version.OriginalString;

                        if (this.CaptureIdAndVersion)
                        {
                            this.LogDebug("Setting $ImportedPackageId = " + packageId);
                            SetBuildVariable(context, "ImportedPackageId", packageId);

                            this.LogDebug("Setting $ImportedPackageVersion = " + packageVersion);
                            SetBuildVariable(context, "ImportedPackageVersion", packageVersion);
                        }

                        if (this.IncludeVersionInArtifactName)
                        {
                            artifactName = packageId + "." + packageVersion;
                        }
                    }
                    catch (Exception ex)
                    {
                        this.LogError("Could not read package metadata: " + ex.ToString());
                        return;
                    }
                }

                var rootCapturePath = Path.Combine(packageRootPath, (this.PackageArtifactRoot ?? string.Empty).Replace('/', '\\').TrimStart('/', '\\'));
                this.LogDebug($"Capturing files in {rootCapturePath}...");

                var rootEntry = Util.Files.GetDirectoryEntry(
                    new GetDirectoryEntryCommand
                {
                    Path            = rootCapturePath,
                    IncludeRootPath = true,
                    Recurse         = true
                }
                    ).Entry;

                using (var agent = BuildMasterAgent.CreateLocalAgent())
                {
                    var fileOps    = agent.GetService <IFileOperationsExecuter>();
                    var matches    = Util.Files.Comparison.GetMatches(rootCapturePath, rootEntry, new[] { "!\\" + this.PackageId + ".nupkg", "*" });
                    var artifactId = new ArtifactIdentifier(context.ApplicationId, context.ReleaseNumber, context.BuildNumber, context.DeployableId, artifactName);

                    this.LogInformation($"Creating artifact {artifactName}...");
                    using (var artifact = new ArtifactBuilder(artifactId))
                    {
                        artifact.RootPath = rootCapturePath;

                        foreach (var match in matches)
                        {
                            artifact.Add(match, fileOps);
                        }

                        artifact.Commit();
                    }

                    this.LogInformation("Artifact created.");
                }
            }
            finally
            {
                try
                {
                    DirectoryEx.Delete(tempPath);
                }
                catch
                {
                }
            }
        }
    override public ExecuteResult Execute(HandlerStartInfo startInfo)
    {
        ExecuteResult result = null;

        if (startInfo.Parameters != null)
        {
            parameters = HandlerUtils.Deserialize <ScriptHandlerParameters>(startInfo.Parameters);
        }
        String script = null;

        try
        {
            String command      = null;
            String args         = null;
            bool   isTempScript = false;

            OnLogMessage("Execute", $"Running Handler As User [{System.Security.Principal.WindowsIdentity.GetCurrent().Name}]");

            Validate();

            // Replace Any "Special" Handler Variables In Arguments or ReplaceWith elements
            variables            = HandlerUtils.GatherVariables(this, startInfo);
            parameters.Arguments = HandlerUtils.ReplaceHandlerVariables(parameters.Arguments, variables);
            if (parameters.Expressions != null)
            {
                foreach (RegexArguments expression in parameters.Expressions)
                {
                    expression.ReplaceWith = HandlerUtils.ReplaceHandlerVariables(expression.ReplaceWith, variables);
                }
            }

            switch (config.Type)
            {
            case ScriptType.Powershell:
                command = "powershell.exe";
                if (!String.IsNullOrWhiteSpace(parameters.Script))
                {
                    isTempScript = false;
                    script       = parameters.Script;
                }
                else
                {
                    isTempScript = true;
                    script       = CreateTempScriptFile(parameters.ScriptBlock, "ps1");
                }
                args = config.Arguments + @" -File """ + script + @"""";
                if (!String.IsNullOrWhiteSpace(parameters.Arguments))
                {
                    String scriptArgs = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);
                    args += " " + scriptArgs;
                }
                break;

            case ScriptType.Batch:
                command = "cmd.exe";
                if (!String.IsNullOrWhiteSpace(parameters.Script))
                {
                    isTempScript = false;
                    script       = parameters.Script;
                }
                else
                {
                    isTempScript = true;
                    script       = CreateTempScriptFile(parameters.ScriptBlock, "bat");
                }
                args = config.Arguments + @" """ + script + @"""";
                if (!String.IsNullOrWhiteSpace(parameters.Arguments))
                {
                    String scriptArgs = RegexArguments.Parse(parameters.Arguments, parameters.Expressions);
                    args += " " + scriptArgs;
                }

                break;

            default:
                throw new Exception("Unknown ScriptType [" + config.Type.ToString() + "] Received.");
            }

            bool isDryRun = startInfo.IsDryRun && !(config.SupportsDryRun);
            if (startInfo.IsDryRun && config.SupportsDryRun)
            {
                OnLogMessage("Execute", "DryRun Flag is set, but plan config indicates the script supports DryRun.  Script will execute.");
            }

            if (String.IsNullOrEmpty(config.RunOn))
            {
                SecurityContext runAs = startInfo.RunAs;
                if (runAs != null && runAs.HasCrypto)
                {
                    runAs = startInfo.RunAs.GetCryptoValues(startInfo.RunAs.Crypto, false);
                }
                result = LocalProcess.RunCommand(command, args, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, SynapseLogger, null, isDryRun, config.ReturnStdout, runAs?.Domain, runAs?.UserName, runAs?.Password);
            }
            else
            {
                result = WMIUtil.RunCommand(command, args, config.RunOn, config.WorkingDirectory, config.TimeoutMills, config.TimeoutStatus, config.KillRemoteProcessOnTimeout, SynapseLogger, config.RunOn, isDryRun, config.ReturnStdout);
            }

            if (result.Status == StatusType.None)
            {
                result.Status = HandlerUtils.GetStatusType(result.ExitCode, config.ValidExitCodes);
            }

            if (File.Exists(script) && isTempScript)
            {
                File.Delete(script);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            if (File.Exists(script))
            {
                File.Delete(script);
            }
            throw e;
        }

        OnLogMessage(config.RunOn, "Command finished with exit code = " + result.ExitCode + ".  Returning status [" + result.Status + "].");
        return(result);
    }
예제 #21
0
 public PwnieHax() : this(LocalProcess.Find(PROCESS_NAME))
 {
 }
예제 #22
0
        public void Startup()
        {
            lock (this)
            {
                Thread.CurrentThread.Name   = LocalProcessId.ToString() + "-main";
                MxpOptions.ThreadNamePrefix = LocalProcessId.ToString();

                LogUtil.Info("Daemon Process startup...");

                if (service != null)
                {
                    throw new Exception("DaemonProcess already started.");
                }

                // Preparing database entity context.
                entityContext = new DaemonEntities();

                // Loading configuration from database.
                localProcessEntity = QueryUtil.First <LocalProcess>(
                    from lp in entityContext.LocalProcess where lp.LocalProcessId == LocalProcessId select lp);
                participantEntity = QueryUtil.First <DaemonLogic.Participant>(
                    from lp in entityContext.LocalProcess where lp.LocalProcessId == LocalProcessId select lp.Participant);
                remoteProcessEntities = (from rp in entityContext.RemoteProcess where rp.LocalProcess.LocalProcessId == LocalProcessId select rp).ToList <RemoteProcess>();
                bubbleEntities        = (from b in entityContext.Bubble where b.LocalProcess.LocalProcessId == LocalProcessId select b).ToList <Bubble>();

                LogUtil.Info("Loaded local process configuration: " + localProcessEntity.Address + ":" + localProcessEntity.ServerPort + "/" + localProcessEntity.HubPort);

                // Creating service, bubbles and bubble links.
                service = new CloudService(ConfigurationManager.AppSettings["DaemonMemberWeb"],
                                           localProcessEntity.Address,
                                           localProcessEntity.HubPort,
                                           localProcessEntity.ServerPort,
                                           localProcessEntity.Name,
                                           DaemonProcessConstants.ProgramMajorVersion,
                                           DaemonProcessConstants.ProgramMinorVersion);

                foreach (Bubble bubble in bubbleEntities)
                {
                    CloudBubble cloudBubble = new CloudBubble(bubble.BubbleId, bubble.Name, (float)bubble.Range, (float)bubble.PerceptionRange);
                    cloudBubble.ParticipantConnectAuthorize  += OnParticipantConnectAuthorize;
                    cloudBubble.CloudParticipantDisconnected += OnCloudParticipantDisconnected;
                    service.AddBubble(cloudBubble);

                    foreach (RemoteProcess remoteProcess in remoteProcessEntities)
                    {
                        cloudBubble.AddAllowedRemoteHubAddress(remoteProcess.Address);
                    }

                    // Loading bubble link configuration from database.
                    List <DaemonLogic.BubbleLink> bubbleLinkConfigurations = (from b in entityContext.BubbleLink where b.Bubble.BubbleId == bubble.BubbleId select b).ToList <DaemonLogic.BubbleLink>();

                    foreach (DaemonLogic.BubbleLink bubbleLink in bubbleLinkConfigurations)
                    {
                        service.AddBubbleLink(bubble.BubbleId, bubbleLink.RemoteBubbleId, bubbleLink.Address, bubbleLink.Port, (float)-bubbleLink.X, (float)-bubbleLink.Y, (float)-bubbleLink.Z,
                                              true, true);
                    }
                }

                // Saving process state info to database.
                localProcessStateEntity = new LocalProcessState
                {
                    LocalProcessStateId = Guid.NewGuid(),
                    LocalProcess        = localProcessEntity,
                    Participant         = participantEntity,
                    Created             = DateTime.Now,
                    Modified            = DateTime.Now,
                    Cpu = OnGetProcessingTime(),
                    Mem = (System.Diagnostics.Process.GetCurrentProcess().WorkingSet64) / 1024
                };
                entityContext.AddToLocalProcessState(localProcessStateEntity);
                entityContext.SaveChanges();

                service.Startup(false);

                LogUtil.Info("Daemon Process startup done.");
            }
        }