public void Send(Message msg) { using (var exitSpan = CustomSpan.CreateExit(this, msg.Headers.Add).AsMessageSendTo(msg.Topic)) { MessageRouter.PostMessage(msg); } }
public string Execute(string input, Dictionary <string, object> protocol) { // for every step we create an entry (remember that we create an exit for every call // from the pipeline to an IStep-implementation). We correlate based on the current context // since we never really leave the boundaries of the app. In remote scenarios though, this would // look differently. using (var span = CustomSpan.CreateEntry(this, CorrelationUtil.GetCorrelationFromCurrentContext)) { // wrap the call and bubble exceptions up to gather error-information span.WrapAction(() => { span.SetTag(new string[] { "Input" }, input); string[] words = input.Split(new char[] { ',', ' ', '!', '.', '?' }); int icount = 0; foreach (string word in words) { if (!string.IsNullOrEmpty(word)) { icount++; } } protocol["Word-Count"] = icount; }, true); } return(input); }
static void Main(string[] args) { // let's say you want to connect to a database-system which Instana does not // support for automatic tracing. How would you get tracing for this? // in this example we pretend you had access to the client (or a wrapper around a client) // which you can use for instrumentation. Console.WriteLine("Awesome fake database tracing demo v1.0"); DatabaseClient client = new DatabaseClient(); while (true) { try { Console.Write("Query >"); var text = Console.ReadLine(); // we create an entry-span as the root to our trace here, and we're pretending it was an http-call // by using the AsHttpTo extensions-method... // also we request a call-stack with a maximum of 10 frames to be captured using (var rootSpan = CustomSpan.CreateEntry(null, null, callStackFrames: 10).AsHttpTo("https://somewhere.inthe.cloud/api/databaseaccess")) { // dig into the code of DatabaseClient to see how the rest of the // trace is created by means of the SDK... bool connected = client.Connect("localhost", "superdatabase"); var reader = client.ExecuteQuery(text); } } catch (Exception e) { Console.WriteLine("Could not connect to the database:" + e.Message); } } }
public async Task <IEnumerable <string> > GetDataForTrip(string id) { List <string> allnames = new List <string>(); using (SqlConnection connection = new SqlConnection(_connectionString)) { await connection.OpenAsync(); SqlCommand cmd = new SqlCommand("SELECT TOP (100000) * FROM tblTrip", connection); using (var reader = cmd.ExecuteReader()) { using (var span = CustomSpan.Create(this, SpanType.INTERMEDIATE, "Process Data Items")) { int i = 0; while (reader.Read()) { i++; allnames.Add(reader["Id"].ToString()); } span.SetTag("elements", i.ToString()); } } } return(allnames); }
public static async Task ReceiveMessageAsync(IAmazonSQS amazonSQS) { ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest("http://localhost:9324/queue/test"); receiveMessageRequest.MaxNumberOfMessages = 10; Message correlationMessage = null; ReceiveMessageResponse r = await amazonSQS.ReceiveMessageAsync(receiveMessageRequest); List <DeleteMessageBatchRequestEntry> deleteReqEntries = new List <DeleteMessageBatchRequestEntry>(r.Messages.Count); correlationMessage = r.Messages.FirstOrDefault(); using (var span = CustomSpan.Create() .AsAWSSQSMessageReceive(receiveMessageRequest.QueueUrl)) { span.WrapAction(() => { foreach (var message in r.Messages) { Console.WriteLine("Messageid: " + message.MessageId); Console.WriteLine("Message body:" + message.Body); Console.WriteLine("Recepit: " + message.ReceiptHandle); Console.WriteLine("MD5Body: " + message.MD5OfBody); Console.WriteLine(); deleteReqEntries.Add(new DeleteMessageBatchRequestEntry(message.MessageId, message.ReceiptHandle)); } }, true); span.AsChildOf(() => GetDisInfo(correlationMessage)); } DeleteMessageBatchRequest deleteMessageBatchRequest = new DeleteMessageBatchRequest("http://localhost:9324/queue/test", deleteReqEntries); var response = await amazonSQS.DeleteMessageBatchAsync(deleteMessageBatchRequest); }
private void FrmPopup_Load(object sender, EventArgs e) { using (var span = CustomSpan.Create(this, SpanType.INTERMEDIATE, "Popup Form Load")) { Thread.Sleep(10); } }
private static void Listen() { if (_listening) { return; } _listening = true; foreach (string topic in _topics) { MessageConsumer consumer = new MessageConsumer() { Topic = topic }; } _listenerTask = Task.Factory.StartNew(() => { foreach (Message msg in _messages.GetConsumingEnumerable()) { using (var entrySpan = CustomSpan.CreateEntry(null, () => ExtractCorrelation(msg)).AsMessageReceiveFrom(msg.Topic)) { if (_topicToConsumer.ContainsKey(msg.Topic)) { _topicToConsumer[msg.Topic].HandleMessage(msg); } } } }); }
private void BtnOpenPopup_Click(object sender, EventArgs e) { using (var span = CustomSpan.CreateEntry(this, (ISpanContext)null, "Open Popup Form")) { frmPopup popup = new frmPopup(); popup.Show(); } }
private void FrmMain_Load(object sender, EventArgs e) { // create a trace for loading the main-window. Nothing interesting happens here. // it just displays that any event-handler can be instrumented using (var span = CustomSpan.CreateEntry(this, (ISpanContext)null, "Main Window Load")) { Thread.Sleep(10); } }
private void DoThat(StringBuilder state) { // create one intermediate span for this subtask using (var thatSpan = CustomSpan.Create(this, SpanType.INTERMEDIATE)) { state.Append("...That..."); // and annotate the span with something for us to see thatSpan.SetTag("state", state.ToString()); Thread.Sleep(5); } }
public Task <string> GreetMe(GrainMessage <string> nameMessage) { return(Task.Run <string>(() => { using (var span = CustomSpan.CreateEntry(this, () => { return CorrelateFromMessage <string>(nameMessage); })) { span.SetData("name", nameMessage.Content); span.SetTag("service", this.GetType().Name); return $"Hello {nameMessage.Content}"; } })); }
private List <Country> TransformApiResultToCountryList(HttpResponseMessage response) { // let's create an intermediate span, which will show us how much the // transformation-logic contributes to the overall runtime. using (var span = CustomSpan.Create(this, SpanType.INTERMEDIATE)) { HttpContent content = response.Content; var decoded = content.ReadAsStringAsync().Result; var countries = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Country> >(decoded); span.SetData("count", countries.Count.ToString()); return(countries); } }
private void FillList(List <Country> countries) { // create a span for filling the list with the result from the service // this will let us know whether this loop takes long or not using (var span = CustomSpan.Create(this, SpanType.INTERMEDIATE)) { listView1.Items.Clear(); foreach (Country country in countries) { ListViewItem item = new ListViewItem(new string[] { country.Name, country.Capital, country.Capital, country.Population.ToString() }); listView1.Items.Add(item); } } }
public static DistributedTraceInformation GetCorrelationFromCurrentContext() { // in our example we never leave the scope of our test-application, so the distribution // shown here is artificial. In real-world scenarios, you would put the var context = CustomSpan.GetCurrentContext(); if (context != null) { var dti = new DistributedTraceInformation(); dti.ParentSpanId = context.GetSpanId(); dti.TraceId = context.GetTraceId(); return(dti); } return(null); }
public void StreamingPull() { // First create a topic. PublisherServiceApiClient publisherService = PublisherServiceApiClient.CreateAsync().Result; TopicName topicName = new TopicName("k8s-brewery", "sdk-example-test-topic"); try { publisherService.CreateTopic(topicName); } catch { } // Subscribe to the topic. SubscriberServiceApiClient subscriberService = SubscriberServiceApiClient.CreateAsync().Result; SubscriptionName subscriptionName = new SubscriptionName("k8s-brewery", "sdk-example-test-subscription"); try { subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60); } catch { } // Pull messages from the subscription using SubscriberClient. SubscriberClient subscriber = SubscriberClient.CreateAsync(subscriptionName).Result; List <PubsubMessage> receivedMessages = new List <PubsubMessage>(); // Start the subscriber listening for messages. subscriber.StartAsync((msg, cancellationToken) => { using (var span = CustomSpan.Create() .AsGCPubSubReceive(subscriptionName.SubscriptionId, subscriptionName.ProjectId) .AsChildOf(() => GetDisInfo(msg))) { span.WrapAction(() => { receivedMessages.Add(msg); Console.WriteLine($"[Test] Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}"); Console.WriteLine($"[Test] Text: '{msg.Data.ToStringUtf8()}'"); }, true); return(Task.FromResult(SubscriberClient.Reply.Ack)); } }); }
public bool Connect(string host, string databaseName) { // create the span for the outgoing call. Since we know that we're calling // a database, we can annotate the call accordingly with convenient extension-methods // Here we use: CustomExitSpan.AsDbCallTo() // additionally we request a call-stack to be captured with a maximum of 10 frames using (var connectionSpan = CustomSpan.CreateExit(this, null, callStackFrames: 10) .AsDbCallTo(host + ":" + databaseName, "CONNECT", "sql")) { if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(databaseName)) { Thread.Sleep(2); _isConnected = true; _databaseName = databaseName; } return(_isConnected); } }
static void Main(string[] args) { while (true) { // let's start with a simple entry-span using (var entrySpan = CustomSpan.CreateEntryForNewTrace(null).AsMessageReceiveFrom("out_of_nowhere")) { // now let's do some work. Worker w = new Worker(); w.DoSomeWork("Please do something!"); } Console.WriteLine("Hit <enter> to repeat, enter 'q' to quit>"); var input = Console.ReadLine(); if (input == "q") { break; } } }
private static async Task DoClientWork(IClusterClient client) { await Task.Run(async() => { using (var span = CustomSpan.CreateEntry(null, (ISpanContext)null)) { span.SetTag("service", "OrleansExampleClient"); // example of calling grains from the initialized client var friend = client.GetGrain <IHelloGrain>(0); var message = new GrainMessage <string>("Oliver Twist"); using (var exitSpan = CustomSpan.CreateExit(friend, (name, value) => { message.Headers.Add(name, value); })) { exitSpan.SetTag("service", "OrleansExampleClient"); var response = await friend.GreetMe(message); Console.WriteLine("\n\n{0}\n\n", response); } } }); }
static void Main(string[] args) { Console.WriteLine("Custom Messaging System v1.0"); Console.WriteLine("----------------------------"); MessageClient client = new MessageClient(); client.Connect("awesome-topic"); while (true) { Console.Write("Enter message > "); string message = Console.ReadLine(); using (var rootSpan = CustomSpan.CreateEntryForNewTrace(null)) { client.Send(new Message() { Topic = "awesome-topic", Body = message }); } Thread.Sleep(500); } }
public string Execute(string input, Dictionary <string, object> protocol) { // for every step we create an entry (remember that we create an exit for every call // from the pipeline to an IStep-implementation). We correlate based on the current context // since we never really leave the boundaries of the app. In remote scenarios though, this would // look differently. using (var span = CustomSpan.CreateEntry(this, CorrelationUtil.GetCorrelationFromCurrentContext)) { // wrap the call and bubble exceptions up to gather error-information span.WrapAction(() => { span.SetTag(new string[] { "Input" }, input); if (string.IsNullOrEmpty(input)) { protocol["Validation-Result"] = "Invalid"; throw new ArgumentException("The input for this job was invalid!"); } protocol["Validation-Result"] = "Valid"; }, true); return(input); } }
public void ExecuteJob(string input, Dictionary <string, object> stepResults) { // let's create the root for our trace. A trace always starts with an entry // (something enters a system, which leads to a reaction) using (var traceRoot = CustomSpan.CreateEntryForNewTrace(this)) { // since we want to collect errors happening during the process, we // wrap the call, so that any exception will be automatically collected // and added to our trace, at the call where it happened. traceRoot.WrapAction(() => { string mutatedInput = input; Guid jobId = Guid.NewGuid(); // add some tags to our trace, so that we can identify it later // based on our own data, not instana internals traceRoot.SetTag(new string[] { "JobId" }, jobId.ToString()); traceRoot.SetTag(new string[] { "Pipeline-Length" }, _pipelineSteps.Count.ToString()); traceRoot.SetTag(new string[] { "Input" }, input); // execute each step in the pipeline. // we're pretending to have an exit-call for every step // (it _could_ be a remote-service, but in this example it isn't...) foreach (IStep step in _pipelineSteps) { using (var exit = CustomSpan.CreateExit(this, null)) { // each step could throw an exception, so wrap the call // to extract the error-information and let it automatically be // added to our trace... // after collecting the exception, bubble it up exit.WrapAction(() => { mutatedInput = step.Execute(mutatedInput, stepResults); }, true); } } }, true); } }
public IDataReader ExecuteQuery(string queryText) { // Create the span for the query targeting the database (-fake) using (var commandSpan = CustomSpan.CreateExit(this, null, callStackFrames: 10).AsDbCallTo(_databaseName, queryText, "sql")) { // we're wrapping the basic functionality here, which allows us to collect // errors if they happen automatically. commandSpan.WrapAction(() => { if (!_isConnected) { throw new ArgumentException("The client is not connected, command can not be executed"); } if (string.IsNullOrEmpty(queryText)) { throw new ArgumentException("The command must not be empty!"); } Thread.Sleep(queryText.Length); }, true); return(null); } }
private void BtnRefresh_Click(object sender, EventArgs e) { // when the refresh-button is hit, we have an interesting trace. // so let's start the trace with an entry-span, which will be the root. using (var span = CustomSpan.CreateEntry(this, (ISpanContext)null, "Get Country List")) { // set a tag on the span, so we know which region has been selected by the user span.SetTag("region", cbRegion.SelectedItem == null ? "NONE SELECTED" : (string)cbRegion.SelectedItem); span.SetTag(new string[] { "infrastructure", "machine" }, Environment.MachineName); if (cbRegion.SelectedItem == null) { MessageBox.Show("Please select a region first"); return; } // call the CountryService to get the countries from the selected region // this call will create additional spans! Go ceck CountryService string selectedRegion = (string)cbRegion.SelectedItem; var result = _countryService.GetCountriesByRegion(selectedRegion); if (result.WasSuccessful) { FillList(result.Result); } else { if (result.CallException != null) { MessageBox.Show(result.CallException.Message, "Error calling REST-API", MessageBoxButtons.OK, MessageBoxIcon.Error); span.SetException(result.CallException); } } // set the result of the call on the span span.SetResult(result.StatusCode.ToString()); } }
static void Main(string[] args) { GCPublisherService gcPublisherService = new GCPublisherService(); GCSubscriberService gcSubscriberService = new GCSubscriberService(); gcPublisherService.StartPeriodicallyPublish(2000); gcSubscriberService.StreamingPull(); PublisherServiceApiClient publisher = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName("k8s-brewery", "sdk-example-test-topic-2"); try { publisher.CreateTopic(topicName); } catch (Exception) { Console.WriteLine("Failed to create topic"); } // Publish a message to the topic. PubsubMessage message = new PubsubMessage { Data = ByteString.CopyFromUtf8("Message "), Attributes = { { "Description", "Simple text message " } } }; publisher.Publish(topicName, new[] { message }); SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create(); SubscriptionName subscriptionName = new SubscriptionName("k8s-brewery", "sdk-example-test-subscription-2"); try { subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60); } catch (Exception) { Console.WriteLine("Failed to create subscription"); } PullResponse response = subscriber.Pull(subscriptionName, returnImmediately: true, maxMessages: 100); foreach (ReceivedMessage received in response.ReceivedMessages) { using (var span = CustomSpan.Create() .AsGCPubSubReceive(subscriptionName.SubscriptionId, subscriptionName.ProjectId) .AsChildOf(() => GCSubscriberService.GetDisInfo(received.Message))) { span.WrapAction(() => { PubsubMessage msg = received.Message; Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}"); Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'"); Console.WriteLine($"Attributes: '{string.Join(",", msg.Attributes.Select(x => $"{x.Key}-{x.Value}"))}'"); }, true); } } if (response.ReceivedMessages.Count > 0) { subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId)); } Console.WriteLine("Press any key to close ..."); Console.ReadKey(); }