public IHttpActionResult Delete()
        {
            ContextSwitch.Go();

            using (var serverSession = new Session())
            {
                serverSession.Log("CLONESDEL: Deleting all clones.");

                try
                {
                    var clonesPath = PathProvider.Translate(ServerConstants.SERVER_CLONES_FOLDER);
                    if (Directory.Exists(clonesPath))
                        Directory.Delete(clonesPath, true);
                }
                catch (Exception e)
                {
                    serverSession.Log("CLONESDEL: Error. {0}", e);
                    return Ok(ClonesKillResult.Error(e));
                }

                serverSession.Log("CLONESDEL: Completed.");

                return Ok(ClonesKillResult.Ok());
            }
        }
        public IHttpActionResult Kill()
        {
            ContextSwitch.Go();

            using (var serverSession = new Session())
            {

                serverSession.Log("CLONESKILL: Killing all clones.");

                foreach (var process in Process.GetProcesses())
                {
                    if (process.ProcessName == "sharpagent")
                    {
                        try
                        {
                            process.Kill();
                        }
                        catch
                        {
                        }
                    }
                }

                serverSession.Log("CLONESKILL: Completed.");

                return Ok(ClonesKillResult.Ok());
            }
        }
Exemplo n.º 3
0
        public IHttpActionResult Clone([FromUri] int port)
        {
            ContextSwitch.Go();

            CloneResult result;

            using (var session = new Session())
            {
                session.Log("CLONE: Creating clone.");
                var cloneFactory = new CloneFactory();
                result = cloneFactory.Create(port);
                session.Log("CLONE: Clone complete.");
            }

            return Ok(result.ConnectionInfo);
        }
Exemplo n.º 4
0
        public IHttpActionResult Clones()
        {
            ContextSwitch.Go();

            DiscoveredClones result;

            using (var serverSession = new Session())
            {
                serverSession.Log("CLONES: Discovering clones.");
                var cloneFactory = new CloneFactory();
                result = cloneFactory.Discover();
                serverSession.Log("CLONES: Results: " + JsonConvert.SerializeObject(result));
                serverSession.Log("CLONES: Clone discovery complete.");
            }

            return Ok(result.CloneInfos);
        }
Exemplo n.º 5
0
 public ITypeProtocolClient AsClient(IPEndPoint ipEndPoint)
 {
     type = "CLIENT";
     using (var session = new Session())
     {
         this.ipEndPoint = ipEndPoint;
         session.Log("CLIENT: Connecting Tcp Socket: {0}", this.ipEndPoint);
         TryingExtensions.UntilNoException(
             () => { this.socket.Connect(this.ipEndPoint); },
             (e) =>
             {
                 session.Log("Tcp Socket Connection Error: {0}", e);
                 session.Flush();
                 Thread.Sleep(50);
             },
             cancellationToken);
         return this;
     }
 }
Exemplo n.º 6
0
        public async Task<IHttpActionResult> Post()
        {
            ContextSwitch.Go();

            using (var session = new Session())
            {

                session.Log("UPLOAD: Starting.");

                var request = Request;
                if (!request.Content.IsMimeMultipartContent())
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

                var root = PathProvider.Translate(ServerConstants.SERVER_UPLOAD_FOLDER).EnsureDirectoryExists();
                var provider = new MultipartFormDataStreamProvider(root);

                await request.Content.ReadAsMultipartAsync(provider);

                var stringResult = provider.FormData["json"];
                var uploadRequest = JsonConvert.DeserializeObject<UploadRequest>(stringResult);

                foreach (var multipartFileData in provider.FileData)
                {
                    session.Log("UPLOAD: Moving file data.");
                    var destFileName = Path.Combine(root, uploadRequest.File);
                    BackupAndMoveFileIfItExists(destFileName);
                    MoveTempFileToTarget(multipartFileData, destFileName);
                }

                var uploadResult = UploadResult.Ok(uploadRequest);

                session.Log("UPLOAD: Completed. {0}", JsonConvert.SerializeObject(uploadResult));

                return Ok(uploadResult);
            }
        }
        private static void CreateSubscriberForType(Type type, int[] ports)
        {
            foreach (var port in ports)
            {
                var thisIpAsEndPoint = ServerDiscovery.GetThisIpAsEndPoint(port);
                var listener = Factory.CreateServer(thisIpAsEndPoint, (r) =>
                {
                    using (var session = new Session())
                    {
                        session.Log("INST-REG-SUB: Received {0}: {1}", thisIpAsEndPoint, r);
                        try
                        {
                            var command = JsonConvert.DeserializeObject<InstanceCommand>(r);

                            var instance = (IImplementKeys) JsonConvert.DeserializeObject(command.Content, type);
                            var key = instance.GetKey();

                            var args = new InstanceSubscriberEntry(instance);
                            var cache = InstanceRegistry.FindOrCreateNotificationCache(type);

                            if (command.Intent == "C")
                            {
                                Debug.WriteLine("SUB-SET: {0}, {1}, {2}", key, r, cache.Count);
                                cache.SetItem(key.ToString(), instance);
                            }
                            if (command.Intent == "D")
                            {
                                Debug.WriteLine("SUB-REM: {0}, {1}, {2}", key, r, cache.Count);
                                cache.ExpireItem(key.ToString());
                            }
                            if (Notifiers != null)
                                Notifiers(args);
                        }
                        catch (Exception err)
                        {
                            session.Log("INST-REG-SUB: Error. We might have a memory leak. {0}", err);
                        }
                    }
                    return "OK";
                });
                Listeners.Add(listener);
            }
        }
Exemplo n.º 8
0
        public IHttpActionResult Get()
        {
            ContextSwitch.Go();

            using (var session = new Session())
            {
                InfoResult infoResult = null;

                infoResult = new InfoResult(
                    InstanceRegistry.GetInstancesNotified<ServerConnectionInfo>().ToList(),
                    InstanceRegistry.GetInstancesNotified<AsynchronousCommandInfo>().ToList());

                Debug.WriteLine("INFO: {0}", infoResult);

                var stringResult = JsonConvert.SerializeObject(infoResult);
                session.Log("INFO: {0}", stringResult);

                return Ok(infoResult);
            }
        }
Exemplo n.º 9
0
        public ITypeProtocolServer AsListener(IPEndPoint ipEndPoint, Func<string, string> handler)
        {
            type = "SERVER";
            using (var session = new Session())
            {
                session.Log("SERVER: Listening on {0}", ipEndPoint);
                socket.Bind(ipEndPoint);
                socket.Listen(ipEndPoint.Port);
            }

            Task.Factory.StartNew(() =>
            {
                new Session().Log("SERVER: Started Listener Thread").Dispose();
                while (!cancellationToken.IsCancellationRequested)
                {
                    using (var session = new Session())
                    {
                        if (cancellationToken.IsCancellationRequested) break;
                        var replySocket = this.socket.Accept();
                        session.Log("SERVER: Client Connected. {0}", replySocket.RemoteEndPoint);
                        if (cancellationToken.IsCancellationRequested) break;
                        Task.Factory.StartNew(() =>
                        {
                            while (replySocket.Connected)
                            {
                                using (var replySession = new Session())
                                {
                                    var numberOfBytes = 0;
                                    var receiveString = string.Empty;
                                    var receiveBytes = new byte[8192];
                                    var totalBytes = new List<byte>();

                                    TryingExtensions.WithContinue(
                                        () =>
                                        {
                                            while (!hasTerminator(totalBytes))
                                            {
                                                numberOfBytes = replySocket.Receive(receiveBytes);
                                                for (int byteIndex = 0; byteIndex < numberOfBytes; byteIndex++)
                                                    totalBytes.Add(receiveBytes[byteIndex]);
                                                receiveBytes = new byte[8192];
                                            }
                                        },
                                        (e) =>
                                        {
                                            replySession.Log("SERVER: Error Receiving. Client probably disconnected. {0}", e);
                                            numberOfBytes = 0;
                                            TryingExtensions.WithContinue(() => replySocket.Close());
                                            TryingExtensions.WithContinue(() => replySocket.Dispose());
                                        });

                                    if (numberOfBytes == 0)
                                        break;

                                    receiveString = Encoding.UTF8.GetString(totalBytes.ToArray(), 0, totalBytes.Count);
                                    var instancePubSubTerminator = Encoding.UTF8.GetString(ServerConstants.INSTANCE_PUB_SUB_TERMINATOR.ToArray());
                                    receiveString = receiveString.Replace(instancePubSubTerminator, "");
                                    replySession.Log("SERVER: Received {0}: {1}", replySocket.RemoteEndPoint, receiveString);

                                    var responseString = handler(receiveString);
                                    replySession.Log("SERVER: Handler {0}: {1}", replySocket.RemoteEndPoint, responseString);

                                    var responseBytes = Encoding.UTF8.GetBytes(responseString);

                                    TryingExtensions.WithContinue(
                                        () =>
                                        {
                                            replySession.Log("SERVER: Replying {0}: {1}", replySocket.RemoteEndPoint, responseString);
                                            replySocket.Send(responseBytes);
                                        },
                                        (e) =>
                                        {
                                            replySession.Log("SERVER: Replying Error {0}: {1}", replySocket.RemoteEndPoint, e);
                                            TryingExtensions.WithContinue(() => replySocket.Close());
                                            TryingExtensions.WithContinue(() => replySocket.Dispose());
                                        });
                                }
                            }
                        });
                    }
                }
                new Session().Log("SERVER: Listener Thread Exited").Dispose();
            });
            return this;
        }
Exemplo n.º 10
0
        public string Send(string payload)
        {
            using (var session = new Session())
            {
                Debug.Assert(this.ipEndPoint != null, "Please call AsClient with a valid ipEndPoint");

                var payloadBytes = Encoding.UTF8.GetBytes(payload).Concat(ServerConstants.INSTANCE_PUB_SUB_TERMINATOR).ToArray();

                TryingExtensions.WithContinue(() =>
                {
                    session.Log("CLIENT: Sending {0}: {1}", this.ipEndPoint, payload);
                    this.socket.Send(payloadBytes);
                }, (e) =>
                {
                    session.Log("CLIENT: Error Sending {0}: {1}. Trying again.", this.ipEndPoint, e);
                    session.Flush();
                    AsClient(this.ipEndPoint);
                    TryingExtensions.WithContinue(() =>
                    {
                        this.socket.Send(payloadBytes);
                    });
                });

                var numberOfBytes = 0;
                var receiveString = string.Empty;
                var receiveBytes = new byte[1024];

                TryingExtensions.WithContinue(() =>
                {
                    session.Log("CLIENT: Receving from {0}", this.ipEndPoint);
                    numberOfBytes = this.socket.Receive(receiveBytes);
                }, (e) =>
                {
                    session.Log("CLIENT: Receiving Error {0}: {1}. Trying again.", this.ipEndPoint, e);
                    numberOfBytes = 0;
                });

                if (numberOfBytes == 0)
                {
                    session.Log("CLIENT: Error State, returning string.Empty");
                    return string.Empty;
                }

                receiveString += Encoding.UTF8.GetString(receiveBytes, 0, numberOfBytes);
                session.Log("CLIENT: Received {0}", receiveString);
                return receiveString;
            }
        }
Exemplo n.º 11
0
 public void Dispose()
 {
     using (var session = new Session())
     {
         session.Log("{0}: Shutting down and disposing", type);
         cancellationToken.Cancel();
         TryingExtensions.WithContinue(() => this.socket.Shutdown(SocketShutdown.Both));
         TryingExtensions.WithContinue(() => this.socket.Close());
         TryingExtensions.WithContinue(() => this.socket.Dispose());
     }
 }
Exemplo n.º 12
0
        public Session RunAsync()
        {
            foreach (var command in commands)
            {
                var commandId = Guid.NewGuid();

                Log("EXEC-ASYNC: Executing command. {0}", commandId.ToString("N"));
                Log("EXEC-ASYNC: {0}", command);
                try
                {
                    command.Execute(baseDirectory, wait:false);
                    var localCommand = command;
                    Task.Factory.StartNew(() =>
                    {
                        using (var session = new Session())
                        {
                            session.Log("EXEC-ASYNC: Command finished. {0}", commandId.ToString("N"));
                            session.Log("EXEC-ASYNC: {0}", localCommand);

                            try
                            {
                                localCommand.Wait();
                            }
                            catch (Exception err1)
                            {
                                session.Log("EXEC-ASYNC: Error Waiting. {0}", err1);
                            }

                            Result = localCommand.Result.Output;
                            session.Log("EXEC-ASYNC: Result. {0}", Result);
                        }
                    });
                }
                catch (Exception err)
                {
                    Log("EXEC-ASYNC: Error ocurred: {0}", err);
                }
            }
            return this;
        }