private void OnPurgeOrphan(string msg, string reply, string subject) { // This may take a long time (it can unbind many services), so we run it on a different thread; ThreadPool.QueueUserWorkItem( (data) => { Logger.Debug(Strings.OnPurgeOrphanDebugLogMessage, ServiceDescription()); SimpleResponse response = new SimpleResponse(); try { PurgeOrphanRequest request = new PurgeOrphanRequest(); request.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); bool result = this.PurgeOrphan(request.OrphanInsList, request.OrphanBindingList); if (result) { NodeNats.Publish(reply, null, EncodeSuccess(response)); } else { NodeNats.Publish(reply, null, EncodeFailure(response)); } } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }); }
private void OnBind(string msg, string reply, string subject) { Logger.Debug(Strings.BindRequestLogMessage, ServiceDescription(), msg, reply); BindResponse response = new BindResponse(); BindRequest bind_message = new BindRequest(); bind_message.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); string name = bind_message.Name; // Create a service credentials object with a name set, so we can run this operation in parallel for different service instances. ServiceCredentials nameCredentials = new ServiceCredentials(); nameCredentials.Name = name; nameCredentials.ServiceWorkFactory.StartNew( () => { try { Dictionary <string, object> bind_opts = bind_message.BindOptions; ServiceCredentials credentials = bind_message.Credentials; response.Credentials = this.Bind(name, bind_opts, credentials); NodeNats.Publish(reply, null, EncodeSuccess(response)); } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }); }
private void OnEnableInstance(string msg, string reply, string subject) { Logger.Debug(Strings.OnEnableInstanceDebugMessage, ServiceDescription(), msg, reply); object[] credentials = new object[0]; credentials = JsonConvertibleObject.DeserializeFromJsonArray(msg); ServiceCredentials prov_cred = new ServiceCredentials(); Dictionary <string, object> binding_creds_hash = new Dictionary <string, object>(); prov_cred.FromJsonIntermediateObject(credentials[0]); binding_creds_hash = JsonConvertibleObject.ObjectToValue <Dictionary <string, object> >(credentials[1]); prov_cred.ServiceWorkFactory.StartNew( () => { try { this.EnableInstance(ref prov_cred, ref binding_creds_hash); // Update node_id in provision credentials.. prov_cred.NodeId = this.nodeId; credentials[0] = prov_cred; credentials[1] = binding_creds_hash; NodeNats.Publish(reply, null, JsonConvertibleObject.SerializeToJson(credentials)); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }); }
private void OnRestore(string msg, string reply, string subject) { Logger.Debug(Strings.OnRestoreDebugLogMessage, ServiceDescription(), msg, reply); SimpleResponse response = new SimpleResponse(); try { RestoreRequest restore_message = new RestoreRequest(); restore_message.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); string instance_id = restore_message.InstanceId; string backup_path = restore_message.BackupPath; // TODO: vladi: need to make this parallel when we implement the actual restore for mssql bool result = this.Restore(instance_id, backup_path); if (result) { NodeNats.Publish(reply, null, EncodeSuccess(response)); } else { NodeNats.Publish(reply, null, EncodeFailure(response)); } } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }
private void OnImportInstance(string msg, string reply, string subject) { Logger.Debug(Strings.OnImportInstanceDebugLogMessage, ServiceDescription(), msg, reply); object[] credentials = new object[0]; credentials = JsonConvertibleObject.DeserializeFromJsonArray(msg); ProvisionedServicePlanType plan = (ProvisionedServicePlanType)Enum.Parse(typeof(ProvisionedServicePlanType), JsonConvertibleObject.ObjectToValue <string>(credentials[0])); ServiceCredentials prov_cred = new ServiceCredentials(); ServiceCredentials binding_creds = new ServiceCredentials(); prov_cred.FromJsonIntermediateObject(credentials[1]); binding_creds.FromJsonIntermediateObject(credentials[2]); prov_cred.ServiceWorkFactory.StartNew( () => { try { string instance = prov_cred.Name; string file_path = this.GetMigrationFolder(instance); bool result = this.ImportInstance(prov_cred, binding_creds, file_path, plan); NodeNats.Publish(reply, null, result.ToString()); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }); }
private void OnCleanupNfs(string msg, string reply, string subject) { Logger.Debug(Strings.CleanupNfsLogMessage, ServiceDescription(), msg, reply); object[] request = new object[0]; request = JsonConvertibleObject.DeserializeFromJsonArray(msg); ServiceCredentials prov_cred = new ServiceCredentials(); ServiceCredentials binding_creds = new ServiceCredentials(); prov_cred.FromJsonIntermediateObject(request[0]); binding_creds.FromJsonIntermediateObject(request[1]); prov_cred.ServiceWorkFactory.StartNew( () => { try { string instance = prov_cred.Name; Directory.Delete(this.GetMigrationFolder(instance), true); NodeNats.Publish(reply, null, "true"); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }); }
private void SendNodeAnnouncement(string msg = null, string reply = null) { try { if (!this.NodeReady()) { Logger.Debug(Strings.SendNodeAnnouncementNotReadyDebugLogMessage, ServiceDescription()); return; } Logger.Debug(Strings.SendNodeAnnouncementDebugLogMessage, ServiceDescription(), reply != null ? reply : "everyone"); DiscoverMessage discoverMessage = new DiscoverMessage(); if (msg != null) { discoverMessage.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); } if (string.IsNullOrEmpty(discoverMessage.Plan) || discoverMessage.Plan == this.plan) { Announcement a = this.AnnouncementDetails; a.Id = this.nodeId; a.Plan = this.plan; NodeNats.Publish(reply != null ? reply : string.Format(CultureInfo.InvariantCulture, Strings.NatsSubjectAnnounce, ServiceName()), null, a.SerializeToJson()); } } catch (Exception ex) { Logger.Warning(ex.ToString()); } }
public void SnapshotStagingState() { List <object> instances = new List <object>(); ForEach(delegate(StagingInstance instance) { try { instance.Lock.EnterReadLock(); instances.Add(instance.Properties.ToJsonIntermediateObject()); } finally { instance.Lock.ExitReadLock(); } }); string appState = JsonConvertibleObject.SerializeToJson(instances); DateTime start = DateTime.Now; File.WriteAllText(this.StagingStateFile, appState); Logger.Debug(Strings.TookXSecondsToSnapshotApplication, DateTime.Now - start); this.snapshotScheduled = false; }
private void OnCheckOrphan(string msg, string reply, string subject) { Logger.Debug(Strings.CheckOrphanLogMessage, ServiceDescription()); CheckOrphanResponse response = new CheckOrphanResponse(); try { CheckOrphanRequest request = new CheckOrphanRequest(); request.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); // TODO: vladi: investigate further if this needs to be parallelized; seems that this would take a very short time, and it's not tied to a specific instance, so it could run on a new thread this.CheckOrphan(request.Handles); response.OrphanInstances = OrphanInstancesHash; response.OrphanBindings = OrphanBindingHash; response.Success = true; } catch (Exception ex) { Logger.Warning(Strings.CheckOrphanExceptionLogMessage, ex.ToString()); response.Success = false; response.Error = new Dictionary <string, object>() { { "message", ex.Message }, { "stack", ex.StackTrace } }; } finally { NodeNats.Publish(string.Format(CultureInfo.InvariantCulture, Strings.NatsSubjectOrphanResult, ServiceName()), null, response.SerializeToJson()); } }
private void OnUnbind(string msg, string reply, string subject) { Logger.Debug(Strings.UnbindRequestDebugLogMessage, ServiceDescription(), msg, reply); SimpleResponse response = new SimpleResponse(); UnbindRequest unbind_req = new UnbindRequest(); unbind_req.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); unbind_req.Credentials.ServiceWorkFactory.StartNew( () => { try { bool result = this.Unbind(unbind_req.Credentials); if (result) { this.NodeNats.Publish(reply, null, EncodeSuccess(response)); } else { this.NodeNats.Publish(reply, null, EncodeFailure(response)); } } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }); }
public void DeserializeFromJsonTest() { string json = @"{""bar"":""foo""}"; testclass tc = new testclass(); tc.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(json)); Assert.AreEqual("foo", tc.testfield); }
/// <summary> /// Runs this the VCAP component. This method is non-blocking. /// </summary> public virtual void Run() { this.Discover = new Dictionary <string, object>() { { "type", this.ComponentType }, { "index", this.Index }, { "uuid", this.UUID }, { "host", string.Format(CultureInfo.InvariantCulture, "{0}:{1}", this.Host, this.Port) }, { "credentials", this.Authentication }, { "start", RubyCompatibility.DateTimeToRubyString(this.StartedAt = DateTime.Now) } }; // Listen for discovery requests VCAPReactor.OnComponentDiscover += delegate(string msg, string reply, string subject) { this.UpdateDiscoverUptime(); VCAPReactor.SendReply(reply, JsonConvertibleObject.SerializeToJson(this.Discover)); }; VCAPReactor.Start(); // Varz is customizable this.Varz = new Dictionary <string, object>(); foreach (string key in this.Discover.Keys) { this.Varz[key] = this.Discover[key]; } this.Varz["num_cores"] = Environment.ProcessorCount; // todo: change this to a more accurate method // consider: // PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time"); // upTime.NextValue(); // TimeSpan ts2 = TimeSpan.FromSeconds(upTime.NextValue()); // Console.WriteLine("{0}d {1}h {2}m {3}s", ts2.Days, ts2.Hours, ts2.Minutes, ts2.Seconds); this.Varz["system_start"] = RubyCompatibility.DateTimeToRubyString(DateTime.Now.AddMilliseconds(-Environment.TickCount)); this.CpuPerformance = new PerformanceCounter(); this.CpuPerformance.CategoryName = "Processor Information"; this.CpuPerformance.CounterName = "% Processor Time"; this.CpuPerformance.InstanceName = "_Total"; this.CpuPerformance.NextValue(); this.Healthz = "ok\n"; this.StartHttpServer(); // Also announce ourselves on startup.. VCAPReactor.SendVCAPComponentAnnounce(JsonConvertibleObject.SerializeToJson(this.Discover)); }
public void DeserializeFromEnumJsonTest() { string json = @"{""bar"":""foo"",""blah"":""enum2"",""field3"":""yyy""}"; testclass tc = new testclass(); tc.testfield = "asdasd"; tc.testfield2 = testenum.foo; tc.testfield3 = testenum0.xxx; tc.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(json)); Assert.AreEqual("foo", tc.testfield); Assert.AreEqual(testenum.bar, tc.testfield2); Assert.AreEqual(testenum0.yyy, tc.testfield3); }
public void DeserializeEnumNullableJsonTest() { EnumHashNullable nullable = new EnumHashNullable(); nullable.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(@"{""foo"":""enum4""}")); Assert.AreEqual(testenum.bar2, nullable.foo); EnumHashNullable nullable2 = new EnumHashNullable(); nullable.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(@"{}")); Assert.AreEqual(null, nullable2.foo); }
public void DeserializeFromArrayJsonTest() { string json = @"[{""bar"":""foo""},1]"; object[] objects = JsonConvertibleObject.DeserializeFromJsonArray(json); testclass tc = new testclass(); tc.FromJsonIntermediateObject(objects[0]); Assert.AreEqual("foo", tc.testfield); int i = JsonConvertibleObject.ObjectToValue <int>(objects[1]); Assert.AreEqual(1, i); }
protected override bool Unprovision(string name, ServiceCredentials[] bindings) { if (string.IsNullOrEmpty(name)) { return(false); } Logger.Debug(Strings.SqlNodeUnprovisionDatabaseDebugMessage, name, JsonConvertibleObject.SerializeToJson(bindings.Select(binding => binding.ToJsonIntermediateObject()).ToArray())); ProvisionedService provisioned_service = ProvisionedService.GetService(name); if (provisioned_service == null) { throw new MSSqlErrorException(MSSqlErrorException.MSSqlConfigNotFound, name); } // TODO: validate that database files are not lingering // Delete all bindings, ignore not_found error since we are unprovision try { if (bindings != null) { foreach (ServiceCredentials credential in bindings) { this.Unbind(credential); } } } catch (Exception) { // ignore } this.DeleteDatabase(provisioned_service); long storage = this.StorageForService(provisioned_service); this.availableStorageBytes += storage; this.availableCapacity += this.CapacityUnit(); if (!provisioned_service.Destroy()) { Logger.Error(Strings.SqlNodeDeleteServiceErrorMessage, provisioned_service.Name); throw new MSSqlErrorException(MSSqlErrorException.MSSqlLocalDBError); } Logger.Debug(Strings.SqlNodeUnprovisionSuccessDebugMessage, name); return(true); }
/// <summary> /// Binds a SQL Server database to an app. /// </summary> /// <param name="name">The name of the service.</param> /// <param name="bindOptions">Binding options.</param> /// <param name="credentials">Already existing credentials.</param> /// <returns> /// A new set of credentials used for binding. /// </returns> protected override ServiceCredentials Bind(string name, Dictionary <string, object> bindOptions, ServiceCredentials credentials) { Logger.Debug(Strings.SqlNodeBindServiceDebugMessage, name, JsonConvertibleObject.SerializeToJson(bindOptions)); Dictionary <string, object> binding = null; try { ProvisionedService service = ProvisionedService.GetService(name); if (service == null) { throw new MSSqlErrorException(MSSqlErrorException.MSSqlConfigNotFound, name); } // create new credential for binding binding = new Dictionary <string, object>(); if (credentials != null) { binding["user"] = credentials.User; binding["password"] = credentials.Password; } else { binding["user"] = "******" + Credentials.GenerateCredential(); binding["password"] = "******" + Credentials.GenerateCredential(); } binding["bind_opts"] = bindOptions; this.CreateDatabaseUser(name, binding["user"] as string, binding["password"] as string); ServiceCredentials response = this.GenerateCredential(name, binding["user"] as string, binding["password"] as string); Logger.Debug(Strings.SqlNodeBindResponseDebugMessage, response.SerializeToJson()); this.bindingServed += 1; return(response); } catch (Exception) { if (binding != null) { this.DeleteDatabaseUser(binding["user"] as string); } throw; } }
public void DeserializeComplicatedJsonTest() { //Arrange string jString = @"{""v1"":1,""nv1"":1,""nv2"":null,""child"":{""x"":1}}"; //Act parenttest a = new parenttest(); a.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(jString)); //Assert Assert.AreEqual(a.v1, 1); Assert.AreEqual(a.nv1, 1); Assert.AreEqual(a.nv2, null); Assert.AreNotEqual(a.ct, null); Assert.AreEqual(a.ct.x, 1); Assert.AreEqual(a.ct2, null); }
private void OnProvision(string msg, string reply, string subject) { Logger.Debug(Strings.OnProvisionRequestDebugLogMessage, ServiceDescription(), msg, reply); ProvisionResponse response = new ProvisionResponse(); ProvisionRequest provision_req = new ProvisionRequest(); provision_req.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); ProvisionedServicePlanType plan = provision_req.Plan; ServiceCredentials credentials = provision_req.Credentials; if (credentials == null) { credentials = GenerateCredentials(); } credentials.ServiceWorkFactory.StartNew( () => { try { ServiceCredentials credential = Provision(plan, credentials); credential.NodeId = this.nodeId; response.Credentials = credential; Logger.Debug( Strings.OnProvisionSuccessDebugLogMessage, ServiceDescription(), msg, response.SerializeToJson()); NodeNats.Publish(reply, null, EncodeSuccess(response)); } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response)); } }); }
private void OnUnprovision(string msg, string reply, string subject) { Logger.Debug(Strings.UnprovisionRequestDebugLogMessage, ServiceDescription(), msg); SimpleResponse response = new SimpleResponse(); UnprovisionRequest unprovision_req = new UnprovisionRequest(); unprovision_req.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(msg)); string name = unprovision_req.Name; // Create a service credentials object with a name set, so we can run this operation in parallel for different service instances. ServiceCredentials credentials = new ServiceCredentials(); credentials.Name = name; credentials.ServiceWorkFactory.StartNew( () => { try { ServiceCredentials[] bindings = unprovision_req.Bindings; bool result = this.Unprovision(name, bindings); if (result) { this.NodeNats.Publish(reply, null, EncodeSuccess(response)); } else { this.NodeNats.Publish(reply, null, EncodeFailure(response)); } } catch (Exception ex) { Logger.Warning(ex.ToString()); NodeNats.Publish(reply, null, EncodeFailure(response, ex)); } }); }
/// <summary> /// Snapshots the state of the applications. /// </summary> public void SnapshotAppState() { List <object> instances = new List <object>(); ForEach(delegate(DropletInstance instance) { try { instance.Lock.EnterReadLock(); instances.Add(instance.Properties.ToJsonIntermediateObject()); } finally { instance.Lock.ExitReadLock(); } }); string appState = JsonConvertibleObject.SerializeToJson(instances); DateTime start = DateTime.Now; string tmpFilename = Path.Combine( Path.GetDirectoryName(this.AppStateFile), string.Format(CultureInfo.InvariantCulture, Strings.SnapshotTemplate, new Guid().ToString())); File.WriteAllText(tmpFilename, appState); if (File.Exists(this.AppStateFile)) { File.Delete(this.AppStateFile); } File.Move(tmpFilename, this.AppStateFile); Logger.Debug(Strings.TookXSecondsToSnapshotApplication, DateTime.Now - start); this.snapshotScheduled = false; }
private void OnDisableInstance(string msg, string reply, string subject) { Logger.Debug(Strings.OnDisableInstanceDebugLogMessage, ServiceDescription(), msg, reply); object[] credentials = new object[0]; credentials = JsonConvertibleObject.DeserializeFromJsonArray(msg); ServiceCredentials prov_cred = new ServiceCredentials(); ServiceCredentials binding_creds = new ServiceCredentials(); prov_cred.FromJsonIntermediateObject(credentials[0]); binding_creds.FromJsonIntermediateObject(credentials[1]); prov_cred.ServiceWorkFactory.StartNew( () => { try { string instance = prov_cred.Name; string file_path = this.GetMigrationFolder(instance); Directory.CreateDirectory(file_path); bool result = this.DisableInstance(prov_cred, binding_creds); if (result) { result = this.DumpInstance(prov_cred, binding_creds, file_path); } NodeNats.Publish(reply, null, result.ToString()); } catch (Exception ex) { Logger.Warning(ex.ToString()); } }); }
/// <summary> /// Starts the HTTP server used for healthz and varz. /// </summary> private void StartHttpServer() { MonitoringServer = new MonitoringServer(this.Port, this.Host, this.Authentication[0], this.Authentication[1]); MonitoringServer.VarzRequested += delegate(object sender, VarzRequestEventArgs response) { try { this.VarzLock.EnterWriteLock(); response.VarzMessage = JsonConvertibleObject.SerializeToJson(this.Varz); } finally { this.VarzLock.ExitWriteLock(); } }; MonitoringServer.HealthzRequested += delegate(object sender, HealthzRequestEventArgs response) { response.HealthzMessage = this.Healthz; }; MonitoringServer.Start(); }
public void LoadPlugin() { // in startup, we have the class name and assembly to load as a plugin string startup = File.ReadAllText(Path.Combine(this.Properties.Directory, "startup")); VcapPluginStagingInfo pluginInfo = new VcapPluginStagingInfo(); pluginInfo.FromJsonIntermediateObject(JsonConvertibleObject.DeserializeFromJson(startup)); this.ErrorLog = new Utilities.FileLogger(Path.Combine(this.properties.Directory, pluginInfo.Logs.DeaErrorLog)); // check to see if the plugin is in the instance directory if (File.Exists(Path.Combine(this.Properties.Directory, pluginInfo.Assembly))) { Guid pluginId = PluginHost.LoadPlugin(Path.Combine(this.Properties.Directory, pluginInfo.Assembly), pluginInfo.ClassName); this.Plugin = PluginHost.CreateInstance(pluginId); } else { // if not load the plugin from the dea Guid pluginId = PluginHost.LoadPlugin(pluginInfo.Assembly, pluginInfo.ClassName); this.Plugin = PluginHost.CreateInstance(pluginId); } }
private void ReceiveData(byte[] data, int bytesRead) { if (this.buf == null) { this.buf = new List <byte>(bytesRead); } this.buf.AddRange(data.Take(bytesRead)); while (this.buf != null) { switch (this.parseState) { case ParseState.AwaitingControlLine: { ASCIIEncoding ascii = new ASCIIEncoding(); string strBuffer = ascii.GetString(this.buf.ToArray()); if (this.resource.MSG.IsMatch(strBuffer)) { Match match = this.resource.MSG.Match(strBuffer); strBuffer = this.resource.MSG.Replace(strBuffer, string.Empty); this.subscriptionId = Convert.ToInt32(match.Groups[2].Value, CultureInfo.InvariantCulture); this.reply = match.Groups[4].Value; this.needed = Convert.ToInt32(match.Groups[5].Value, CultureInfo.InvariantCulture); this.parseState = ParseState.AwaitingMsgPayload; } else if (this.resource.OK.IsMatch(strBuffer)) { strBuffer = this.resource.OK.Replace(strBuffer, string.Empty); } else if (this.resource.ERR.IsMatch(strBuffer)) { if (this.OnError != null) { this.OnError(this, new ReactorErrorEventArgs(this.resource.ERR.Match(strBuffer).Groups[1].Value)); } strBuffer = this.resource.ERR.Replace(strBuffer, string.Empty); } else if (this.resource.PING.IsMatch(strBuffer)) { this.SendCommand(this.resource.PONGRESPONSE); strBuffer = this.resource.PING.Replace(strBuffer, string.Empty); } else if (this.resource.PONG.IsMatch(strBuffer)) { if (this.pongs.Count > 0) { SimpleCallback callback = this.pongs.Dequeue(); try { callback(); } catch (Exception ex) { if (this.OnError != null) { this.OnError(this, new ReactorErrorEventArgs(Language.CallbackException, ex)); } } } strBuffer = this.resource.PONG.Replace(strBuffer, string.Empty); } else if (this.resource.INFO.IsMatch(strBuffer)) { this.serverInfo = JsonConvertibleObject.ObjectToValue <Dictionary <string, object> >(JsonConvertibleObject.DeserializeFromJson(this.resource.INFO.Match(strBuffer).Groups[1].Value)); strBuffer = this.resource.INFO.Replace(strBuffer, string.Empty); } else if (this.resource.UNKNOWN.IsMatch(strBuffer)) { if (this.OnError != null) { this.OnError(this, new ReactorErrorEventArgs(Language.ERRUnknownProtocol + this.resource.UNKNOWN.Match(strBuffer).Value)); } strBuffer = this.resource.UNKNOWN.Replace(strBuffer, string.Empty); } else { this.buf = ascii.GetBytes(strBuffer).ToList(); return; } this.buf = ascii.GetBytes(strBuffer).ToList(); if (this.buf != null && this.buf.Count == 0) { this.buf = null; } } break; case ParseState.AwaitingMsgPayload: { if (this.buf.Count < (this.needed + Resource.CRLF.Length)) { return; } ASCIIEncoding ascii = new ASCIIEncoding(); string strBuffer = ascii.GetString(this.buf.ToArray()); this.OnMessage(this.subscriptionId, this.reply, strBuffer.Substring(0, this.needed)); strBuffer = strBuffer.Substring(this.needed + Resource.CRLF.Length); this.reply = string.Empty; this.subscriptionId = this.needed = 0; this.parseState = ParseState.AwaitingControlLine; this.buf = ascii.GetBytes(strBuffer).ToList(); if (this.buf != null && this.buf.Count == 0) { this.buf = null; } } break; } } }
/// <summary> /// Connects this instance. /// </summary> private void Connect() { this.readBuffer = new byte[this.tcpClient.ReceiveBufferSize]; this.tcpClient.GetStream().BeginRead(this.readBuffer, 0, this.readBuffer.Length, this.ReadTCPData, this.tcpClient.GetStream()); Dictionary <string, object> cs = new Dictionary <string, object>() { { "verbose", this.verbose }, { "pedantic", this.pedantic } }; if (!string.IsNullOrEmpty(this.serverUri.UserInfo)) { string[] credentials = this.serverUri.UserInfo.Split(':'); cs["user"] = credentials.Length > 0 ? credentials[0] : string.Empty; cs["pass"] = credentials.Length > 1 ? credentials[1] : string.Empty; } this.status = ConnectionStatus.Open; this.parseState = ParseState.AwaitingControlLine; this.SendCommand(string.Format(CultureInfo.InvariantCulture, "CONNECT {0}{1}", JsonConvertibleObject.SerializeToJson(cs), Resource.CRLF)); lock (this.pendingCommandsLock) { if (this.pendingCommands.Count > 0) { this.FlushPendingCommands(); } } if (this.OnError == null) { this.OnError = new EventHandler <ReactorErrorEventArgs>(delegate(object sender, ReactorErrorEventArgs args) { throw new ReactorException(this.serverUri, args.Message); }); } // if (OnConnect != null && Status != ConnectionStatus.REConecting) if (this.OnConnect != null) { // We will round trip the server here to make sure all state from any pending commands // has been processed before calling the connect callback. this.QueueServer(delegate { this.OnConnect(this, null); }); } }
/// <summary> /// Registers a component using the specified options. /// </summary> /// <param name="options">The options for the component.</param> public void Register(Dictionary <string, object> options) { if (options == null) { throw new ArgumentNullException("options"); } this.Varz = new Dictionary <string, object>(); string uuid = Guid.NewGuid().ToString("N"); object type = options["type"]; object index = options.ContainsKey("index") ? options["index"] : null; if (index != null) { uuid = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", index, uuid); } string host = options["host"].ToString(); int port = options.ContainsKey("statusPort") ? (int)options["statusPort"] : 0; if (port < 1) { port = NetworkInterface.GrabEphemeralPort(); } Reactor nats = (Reactor)options["nats"]; //// string[] auth = new string[] //// { //// options.ContainsKey("user") ? options["user"].ToString() : string.Empty, //// options.ContainsKey("password") ? options["password"].ToString() : string.Empty //// }; string[] auth = new string[] { Credentials.GenerateCredential(32), Credentials.GenerateCredential(32) }; // Discover message limited this.discover = new Dictionary <string, object>() { { "type", type }, { "index", index }, { "uuid", uuid }, { "host", string.Format(CultureInfo.InvariantCulture, "{0}:{1}", host, port) }, { "credentials", auth }, { "start", RubyCompatibility.DateTimeToRubyString(DateTime.Now) } }; // Varz is customizable this.Varz = new Dictionary <string, object>(); foreach (string key in this.discover.Keys) { this.Varz[key] = this.discover[key]; } this.Varz["num_cores"] = Environment.ProcessorCount; // todo: change this to a more accurate method // consider: // PerformanceCounter upTime = new PerformanceCounter("System", "System Up Time"); // upTime.NextValue(); // TimeSpan ts2 = TimeSpan.FromSeconds(upTime.NextValue()); // Console.WriteLine("{0}d {1}h {2}m {3}s", ts2.Days, ts2.Hours, ts2.Minutes, ts2.Seconds); this.Varz["system_start"] = RubyCompatibility.DateTimeToRubyString(DateTime.Now.AddMilliseconds(-Environment.TickCount)); this.CpuPerformance = new PerformanceCounter(); this.CpuPerformance.CategoryName = "Processor Information"; this.CpuPerformance.CounterName = "% Processor Time"; this.CpuPerformance.InstanceName = "_Total"; this.CpuPerformance.NextValue(); this.Healthz = "ok\n"; this.StartHttpServer(host, port, auth); // Listen for discovery requests nats.Subscribe( "vcap.component.discover", delegate(string msg, string reply, string subject) { this.UpdateDiscoverUptime(); nats.Publish(reply, null, JsonConvertibleObject.SerializeToJson(this.discover)); }); // Also announce ourselves on startup.. nats.Publish("vcap.component.announce", null, msg: JsonConvertibleObject.SerializeToJson(this.discover)); }
/// <summary> /// Handles the VarzRequested event of the httpMonitoringServer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Uhuru.Utilities.VarzRequestEventArgs"/> instance containing the event data.</param> private void HttpMonitoringServer_VarzRequested(object sender, VarzRequestEventArgs e) { this.UpdateVarz(); e.VarzMessage = JsonConvertibleObject.SerializeToJson(this.Varz); }
public void DeserializeEnumHashsetJsonTest() { testenum asd = JsonConvertibleObject.ObjectToValue <testenum>("enum4"); Assert.AreEqual(testenum.bar2, asd); }
private bool PurgeOrphan(string[] orphanInstancesList, ServiceCredentials[] orphanBindingsList) { bool ret = true; ServiceCredentials[] allBindingsList = this.AllBindingsList(); foreach (string ins in orphanInstancesList) { try { ServiceCredentials[] bindings = allBindingsList.Where(b => b.Name == ins).ToArray(); Logger.Debug(Strings.PurgeOrphanDebugLogMessage, ins, string.Join(", ", JsonConvertibleObject.SerializeToJson(bindings))); ret = ret && this.Unprovision(ins, bindings); // Remove the OBs that are unbinded by unprovision orphanBindingsList = (from ob in orphanBindingsList where !bindings.Any(binding => binding.Name == ob.Name) select ob).ToArray(); } catch (Exception ex) { Logger.Debug(Strings.PurgeOrphanErrorLogMessage, ins, ex.ToString()); } } foreach (ServiceCredentials credential in orphanBindingsList) { // We're running the unbind on the same thread that other stuff is running for this service instance, so we don't get race conditions; need to wait though, so we have a result status credential.ServiceWorkFactory.StartNew( () => { try { Logger.Debug(Strings.PurgeOrphanUnbindBindingDebugLogMessage, credential.SerializeToJson()); ret = ret && this.Unbind(credential); } catch (Exception ex) { Logger.Debug(Strings.PurgeOrphanUnbindBindingErrorLogMessage, credential.SerializeToJson(), ex.ToString()); } }).Wait(); } return(ret); }