<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lisa Botty on Medium]]></title>
        <description><![CDATA[Stories by Lisa Botty on Medium]]></description>
        <link>https://medium.com/@lisa_botty?source=rss-48122f8e28f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nhilJhZbnErUaG-mIsWhHQ.png</url>
            <title>Stories by Lisa Botty on Medium</title>
            <link>https://medium.com/@lisa_botty?source=rss-48122f8e28f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 09:24:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lisa_botty/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TIGeR on guard for performance — Part 3]]></title>
            <link>https://medium.com/italabs/tiger-performance-part3-en-bb3e468b296e?source=rss-48122f8e28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb3e468b296e</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[italabs]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[stories]]></category>
            <dc:creator><![CDATA[Lisa Botty]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 15:01:01 GMT</pubDate>
            <atom:updated>2019-02-01T09:20:44.202Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>TIGeR on guard for performance — Part 3</strong></h3><h4>Introduction</h4><p>In the <a href="https://medium.com/italabs/tiger-performance-part2-en-140008c250e2">previous</a> (second) part of the article, we went into more details about the TIGeR components architecture and told you how to install and set them up in their basic configuration.</p><p>In this (third) part, we will describe how to set up Telegraf for reading the specific Windows counters (PerfCounters) of our product, apply load to the tested server (we will feed the TIGeR), show how to display values from these counters in Grafana, and also consider some Grafana’s fine-tuning issues related to visualization, variables, and notifications (start “TIGeR training”).</p><h4>Part 3. Taming the TIGeR</h4><h4>Feeding the TIGeR (applying load)</h4><p>First of all, let us remind that InfluxDB and Grafana’s server part should be launched and running by now (for example, they are allocated to a separate server where they are always running).</p><p>For our test product, we use a load client, which we created specifically for this purpose. You will probably have your own methods to apply load (dedicated tools), but in any case, we will record metrics from the Windows counters:</p><p>· The counters which our product creates during the installation process (all important code places are covered with them)</p><p>· System counters (CPU, Memory, Disk, etc.) — optional, depending on objectives.</p><p>At this point, we have to choose counters to take metrics from. In our configuration, we have the basic, system counters (let us leave them there), but we will add our own ones. To do so, insert the following lines at the very end of the Telegraf configuration file:</p><p><em>[[inputs.win_perf_counters.object]]</em></p><p><em># Your product name</em></p><p><em>ObjectName = “</em><strong><em>Test Engine — Client Manager</em></strong><em>”</em></p><p><em>Instances = [“</em><strong><em>default</em></strong><em>”]</em></p><p><em>Counters = [</em></p><p><em>“</em><strong><em>Counter name 1</em></strong><em>”,</em></p><p><em>“</em><strong><em>Counter name 1</em></strong><em>”,</em></p><p><em>“</em><strong><em>Counter name …</em></strong><em>”</em></p><p><em>]</em></p><p><em>Measurement = “</em><strong><em>Test_CM</em></strong><em>”</em></p><p><em>FailOnMissing = </em><strong><em>true</em></strong></p><p>The text in bold type shows the places you will have to replace with your options:</p><p>· <strong><em>Test Engine — ClientManager and Counter name …</em></strong> — category and counters names: you can check them when you add them to the Windows System Monitor snap-in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*bDFoVirCsUjx_UvPpn5tIg.png" /></figure><p>· <strong><em>default</em></strong> — the selected object (counter) instance name, an example is shown in the screenshot above</p><p>· <strong><em>Test_CM</em></strong> — the readings retrieval or run name; in fact, it is the table where the data will be recorded (we were reviewing it, using the InfluxDB chart in the second part of the article)</p><p>· <em>FailOnMissing = </em><strong><em>true</em></strong> — the debugging parameter (it can be deleted or set to <strong><em>false</em></strong> afterward); it interrupts the Telegraf startup if there are issues with finding any counters when it is run. Otherwise, the agent will start but will not retrieve readings from such “bad” counters. Consequently, nothing will be displayed in Grafana, and that may prove confusing — there is no load, the counter does not work, or there is an issue with Telegraf.</p><p>Now, to simplify understanding, we are showing an example with one load scenario for one run of autotests. In real testing, we can have more scenarios during one run (for example, “Rough working morning”, “Calm day off”, etc.). That is why we have to somehow split the data stream for each scenario in such cases so that <strong>during one run, we could distinguish among the tested scenarios displayed in Grafana afterward (as for us, this is a very important point).</strong></p><p>For example, we can do it by:</p><p>· adding specific tags to the Telegraf agent’s configuration section [global_tags] and using them to have a possibility to group data on the charts:</p><p><em>[global_tags]</em></p><p><em>scenario = “morning”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*vPHNRBkkJbeUJTOAJnU8_A.png" /></figure><p>· changing the Measurement (table) name in the same place — in the agent configuration — and then filtering data by these parameters when plotting the chart:</p><p><em>Measurement = “Test_CM_Morning”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*CpvR6BO1oW6bLrNoLRKMNQ.png" /></figure><p>We will touch on this topic in more detail in the next parts of the article when we start automating data collection, taking the product build numbers into account.</p><p>Now, it is time to apply the load (we run the load client on our side: we mentioned it at the very beginning of this part of the article) and start the Telegraf agent after that. If you do it the other way round, the agent will return zero data for a while, and that may “spoil” the final chart appearance. On the other hand, you may need a scenario where it will be important to “capture” the moment when the load starts. So, both start options may prove useful.</p><p>In general, the TIGeR components start charts look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*DUvNErLoimI6VPZ295IAHQ.png" /></figure><p>While the load is being applied and data is being obtained, it is time to slightly fine-tune our test dashboard in Grafana:</p><p>· add a new Graph-type panel and get in its settings</p><p>· select Data Source (it is <em>Perf_DB</em> with us, we created it above)</p><p>· specify <em>FROM default Test_CM SELECT field</em> (counter name) below in the query builder</p><p>· we can similarly add other counters in the same builder (the Add Query button)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fe2SQDp-oCJjRa3RH4DyQA.png" /></figure><p>We return to the dashboard after that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syeuwK-oFTf1igXj3uLacw.png" /></figure><p>Marginally, this is already enough to see the big picture (see the screenshots above — the example of two load test runs with two charts on two counters).</p><p>However, we commonly have to adjust something for our specific objectives as well (in the first part of the article, we set them on our own example), and now, we will start making improvements.</p><h4>Training the TIGeR (visualization, variables, and alerts)</h4><p>Let us start with alerts. They are warnings sent via the pre-configured channel (like in Grafana) generated by a specific trigger. Channels are more than enough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*_b2M1VHBcWgySwEo0yNGFA.png" /></figure><p>We will not consider everything — mail, instant messengers, webhook, etc. now. Everything is simple there, but in our test sample, notifications are set to be sent to mail. At the same time, we want to note that the SMTP parameters are set up in the Grafana configuration file — <em>defaults.ini</em></p><p>Let us have a look at one example: send a letter if the server processor utilization exceeds 50% in a certain period of time while testing the product.</p><p>Select the “CPU Usage” property on our test dashboard, then, select the Alert tab and create a rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZpPsysUE6ChVfqfJAd1cw.png" /></figure><p>The arrows indicate what default values were altered:</p><p>· threshold value of <em>50</em> (%, as in the chart vertical scale) was set</p><p>· in the <em>query</em> box <em>(A, 5m, now)</em> we altered <em>5m</em> for <em>1m</em>,</p><p>here A is the query sequence number from the builder (it is displayed in the builder, on the “Metrics” tab next to the queries)</p><p><em>5m (1m)</em> and <em>now</em> — view the period from the current time to 5 minutes (1 minute) back.</p><p>As a result, according to our settings, we will receive alerts to the mail specified if in each such time interval (between the current time and one minute back) the average value of all “A” query results (in this panel, there is one query for the CPU) will exceed 50%.</p><p>Put it simply: the load was applied and one minute passed, and then, if the average CPU utilization level during this minute was higher than 50%, a letter will come. And every minute it will happen like this — the alert will come or will not. Certainly, this is just an example. Actually, with such settings, the alert letters may “bury” us (if the CPU is highly utilized as often happens during the tests). Therefore, you have to make settings based on experience and on your notification requirements.</p><p>All the other alert parameters are not difficult to comprehend. So, we will not describe them.</p><p>Practically, it happens like this: we apply the load to the workstation’s processor (where the Telegraf agent is installed) to periodically exceed the 50% utilization level, and soon we will receive an alert mail titled “[Alerting] CPU Usage alert”, which has a chart snapshot attached to the time interval when this alert triggered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*Z1tMXtucsUc616qfX1wWCw.png" /></figure><p>A vertical red broken line shows the place the alert triggered. A horizontal one shows an alert threshold value (in our example — 50%).</p><p><strong>A crucial point:</strong> no variables (like <em>/^server$/ or $server</em>) should be selected in the metric query designer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*P-4n6Y6mp4fOlfVt-NUW7A.png" /></figure><p>Otherwise, the alerts will not work because variables in metrics are not supported in the query subsystem for alerts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Y7e8aMJ-EPTw0A5-FOHkTw.png" /></figure><p>The official bug tracker contains lots of complaints about this issue or flaw (for example, <a href="https://github.com/grafana/grafana/issues/6557">here</a>), but the developers have not yet fixed or implemented it (this limitation is officially commented <a href="http://docs.grafana.org/alerting/rules/">here</a>).</p><p>This issue makes it difficult to configure alerts in many scenarios. You will either have to give up on them in this metric collection chart or skip using variables. For example, if we want to handily filter data and charts on the dashboard according to the build numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnpaEyVhj3cVZBEtiuqN_w.png" /></figure><p>We will have to use a variable, for example, <em>“Build”:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*YXKNnnSBhFUabF7isHKYEQ.png" /></figure><p>Now, if we want to add an alert to this chart, Grafana will return a message “Template variables are not supported in alert queries” (see the example in the screenshot above, Fig 11).</p><p>Here are some facts about variables in Grafana. They are meant to customize the display of panels and other dashboard visualization units according to predetermined filters, for example, data source, station, disk, network adapter name, product build number, and more. They are not limited by their dashboard only. Find out more details about the variables in the official <a href="http://docs.grafana.org/reference/templating/">documentation</a>.</p><p>Variable controls are in the dashboard settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OQPPf7o7hg340EkN4kV3g.png" /></figure><p>Here we can add variables of different types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*aDV6jj6ptmh6m56nq6S22Q.png" /></figure><p>In the example shown, from the query results tags, we get the server name, drive letter, adapter name, and product build number. Next, we can use these variables in the metric query designer and when filtering the dashboard data (see several screenshots presented above with the variable “<em>Build</em>” as an example).</p><p>At the end of this part of the article, we would like to recapitulate Grafana’s panels, tables, and other data display units available to be added to the dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*lzK1plY1WS8eoXATgVm9OA.png" /></figure><p>Actually, there are many more of them than shown in the screenshot because this Grafana feature is expanded with plug-ins, the complete list of which is <a href="https://grafana.com/plugins?type=panel">here</a>.</p><p>Each panel can be flexibly configured for different data display logic. We will get back to this feature when we show how to calculate the number of supported “virtual clients” for our test product in the following parts of the article about automation and load autotests.</p><p>As your homework, try to “play around” with the built-in panels: add and customize them for your objectives and preferences. You can also see many samples of different types of dashboards and panels. You can also “play around” with their settings, on the Grafana <a href="https://play.grafana.org/">demo portal</a>.</p><h4>Summary</h4><p>In this third part of the article, we described how to configure Telegraf to read specific counters tracking our product, applied a load to the test server using a load client, showed how values picked up by these counters are displayed in Grafana, and saw some of Grafana’s configuration issues regarding visualization, variables, and notifications.</p><p>Next, in the fourth part, we will start automating the TIGeR components operation by connecting the test automation server (“teach TIGeR to act by itself”), as well as configure Telegraf and Grafana to display our test product performance dynamics both in test run scenarios and for each build (“observe TIGeR success”).</p><h4>Links</h4><p><a href="https://medium.com/italabs/tiger-performance-part1-en-a3c56972c355">TIGeR on guard for performance — Part 1</a></p><p><a href="https://medium.com/italabs/tiger-performance-part2-en-140008c250e2">TIGeR on guard for performance — Part 2</a></p><p><em>Author: Eugene Klimov, System Engineer, </em><a href="https://www.ita-labs.com/?utm_source=Medium&amp;utm_medium=Blogs&amp;utm_campaign=tigr_part3_en"><em>ITA Labs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb3e468b296e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/italabs/tiger-performance-part3-en-bb3e468b296e">TIGeR on guard for performance — Part 3</a> was originally published in <a href="https://medium.com/italabs">ITA Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TIGeR on guard for performance — Part 2]]></title>
            <link>https://medium.com/italabs/tiger-performance-part2-en-140008c250e2?source=rss-48122f8e28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/140008c250e2</guid>
            <category><![CDATA[italabs]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[stories]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Lisa Botty]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 15:01:03 GMT</pubDate>
            <atom:updated>2019-02-01T09:21:30.472Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>TIGeR on guard for performance — Part 2</strong></h3><h4>Introduction</h4><p>In the previous part of this series “<a href="https://medium.com/italabs/tiger-performance-part1-en-a3c56972c355">TIGeR on guard for performance — Part 1</a>”, we sorted out why we need to test performance, why we need to test it automatically, and shaped up the original objective.</p><p>In this (second) part, we will take a closer look at the selected solution components architecture (“the TIGeR anatomy”), and we will also describe installation processes and ways to set the components up in their basic configuration (“cage the TIGeR”).</p><h4>Part 2. Studying the TIGeR</h4><h4>More details on the “TIGeR anatomy” (component architecture)</h4><p>Let us briefly recollect the components which the TIGeR bundle consists of, namely Telegraf + InfluxDB + Grafana:</p><p>· <strong>Telegraf</strong> is an agent aimed at collecting all sorts of the system metrics.</p><p>· <strong>InfluxDB</strong> is a time series database specializing in time series storage.</p><p>· <strong>Grafana</strong> is a web server designed to visualize data.</p><h4>Telegraf</h4><p>It is an agent designed to collect system metrics from stand-alone stations. In our case, we will install it on the server side of the product tested. As you can see on the chart, the agent will transfer the collected metrics into the InfluxDB database in the format understandable for both of them (Telegraf and InfluxDB):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*fSVFv3uBK7WRE8GGV2jICw.png" /></figure><p>Telegraf consists of an executable file and a configuration file. Therefore, no special installation is required.</p><p>Plug-ins are among the main advantages of this agent: there are a lot of them (more than 100 for now). However, annoyances sometimes do happen — for example, it contains no plug-in for MSSQL (as a database, and therefore, no possibility to store metrics there).</p><p>As for the capabilities that the Telegraf already has without plug-ins, we can highlight the following:</p><p>· <strong>Outgoing</strong> data formats, namely, metrics transfer to various databases or just like communication lines: InfluxDB, JSON, Graphite, ElasticSearch, common text file, Prometheus, etc.</p><p>· <strong>Incoming</strong> data formats, namely, metrics sources: Win_perf_counters, MSSQL, RabbitMQ, Memcached, MongoDB, MySQL, simple HTTP, JSON, Filestat (different file statistics), Docker, Cassandra, SMART, DNS, etc.</p><p>Check a more detailed list at <a href="https://docs.influxdata.com/telegraf/">https://docs.influxdata.com/telegraf/</a> and <a href="https://github.com/influxdata/telegraf/tree/master/plugins">https://github.com/influxdata/telegraf/tree/master/plugins</a></p><p>Plug-ins, not built into Telegraf, can only be downloaded as source files, and that is both an advantage and a disadvantage. On the one hand, you can flexibly fine-tune the plug-in, and on the other hand, you will have to spend extra time to integrate it.</p><p>One more thing: unfortunately, we could not compile them into a separate library file and then insert it into the folder with the executable file. It is necessary to include source files of such plug-ins in the Telegraf source files and re-compile the entire agent completely. There are more details on this process on github (see the link above), but now, we will not dwell on this peculiarity, as Telegraf has enough built-in capabilities to meet our objectives.</p><h4>InfluxDB</h4><p>Let us have a look at a simplified structural chart of this database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Wkk9L36eSZGCrsTHvrFROw.png" /></figure><p>· Database available;</p><p>· Inside it, there are tables — Measurements, each has its own name and retention;</p><p>· The tables include a Time column — the main and compulsory columns where timestamps are stored;</p><p>· There are Fields columns (not indexed) — the very metrics data is stored here;</p><p>· Tags columns (indexed) usually store group records, for example, a metric from some server, developed by some user, for some process, etc.</p><p>To query data from the database, an SQL-like language is used.</p><p>Main <strong>advantages</strong>:</p><p>· Quick installation (just unpack the archive, executable files, and configuration files);</p><p>· High performance and low resource utilization;</p><p>· Record and read data over HTTP (access data through a browser, curl, etc.);</p><p>· Support for various data sources except for Telegraf and similar agents (see the list in the previous part in the chapter “What tools, designed for performance testing, exist?”), it is possible to work using the ready libraries, including .NET C#.</p><p>What we can highlight among <strong>disadvantages</strong> is the lack of a graphical user interface (GUI) dedicated to working with the database (interestingly, it was available in previous builds but was removed in the latest versions), meaning that all services should be carried out using Command-Line Interface (CLI).</p><p>That is, actually all. Simple, isn’t it?</p><h4>Grafana</h4><p>It consists of a client (usually a browser) and a server used as a proxy to the database (there is also a possibility to connect directly, using the client — we will talk about this mode in a little more detail below), has a simple role model, various data sources and a set of panels grouped by dashboards (henceforth — dashboard).</p><p>The entire rendering is performed on the client side. For example, here is a sample of one of those dashboards (however, all the possibilities to set up beautiful charts in Grafana are a topic for a separate article):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-xrzY6Ar4uUL7UASju8_EQ.png" /></figure><p>In addition to InfluxDB, we can use various databases as data sources (almost all most widespread ones, except MSSQL) and common text files. Initially, there are few supported data sources, but InfluxDB is available and that will do for us.</p><p>We can extend Grafana’s capabilities installing plug-ins (unlike with Telegraf, it is much easier to do so — all you have to do is to run the installation command of the required plug-in from the command line). Besides additional data sources, there are plug-ins adding various panels to get an even more flexible and beautiful visualization than already available.</p><p>Now, we will briefly tell you about the data request modes, mentioned above:</p><p>· <strong>Proxy</strong> — the client opens Grafana, and it independently executes all requests in InfluxDB;</p><p>· <strong>Direct </strong>— the request goes directly from the browser to InfluxDB (for example, when Grafana does not have access to InfluxDB, but the client has it):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*m51lvev7u-CZg9EfH3lApw.png" /></figure><p>Grafana’s <strong>advantages</strong>:</p><p>· Easy to install (just unpack the archive);</p><p>· Very convenient, flexible, and rich dashboard customization;</p><p>· Simple (relatively) and flexible data sources query builder;</p><p>· Alert system;</p><p>· Snapshots — these are very detailed reports on the conducted test with a link entry point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJLC8uzv5mdDKIfwUGoe-w.png" /></figure><p>Despite all the advantages, very many people choose it primarily for its visualization beauty:</p><p>As for the <strong>disadvantages</strong>, we can only highlight the complicated configuration system. There are lots of instructions, articles, tips, and discussions on this topic, but in our opinion, this shortcoming is by far compensated with advantages.</p><h4>“Caging” the TIGeR (installation and basic configuration)</h4><p>From the previous chapter, it has become clear that the installation process of all three components consists of:</p><p>· Downloading archives</p><p>o Telegraf and InfluxDB — <a href="https://portal.influxdata.com/downloads">https://portal.influxdata.com/downloads</a></p><p>o Grafana — <a href="https://grafana.com/grafana/download?platform=windows">https://grafana.com/grafana/download?platform=windows</a></p><p>· Unpacking into any directory;</p><p>· Setting up in configuration files (for Grafana dashboards as well).</p><p>The general chart of interaction with our test product will look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*iLQ7tMM1h3SzhvSboJlPpw.png" /></figure><p>· A loading client (or several) loads the tested product, with which the Telegraf agent is installed</p><p>· Telegraf collects predefined metrics and records them to InfluxDB</p><p>· Observers or operators address Grafana, using the browser</p><p>· Grafana makes a query to the InfluxDB database, receives, and visualizes data</p><p>In the example above, InfluxDB and Grafana are on the same machine, but actually, they can be on different ones.</p><h4>InfluxDB</h4><p>Everything is really simple in this case: at the minimum — you do not have to change anything even in the configuration file:</p><p><em>influxd.exe -config influxdb.conf</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*t_n262VdId1lLRoa_u5-_Q.png" /></figure><p><strong>Important remark:</strong> initially, all parts of TIGeR cannot work as Windows services — we have to use some third-party solutions, for example, to “wrap” executable files into services (for example, NSSM — <a href="http://nssm.cc/">Non-Sucking Service Manager</a>). We will not dwell on this issue in our article anymore, you will decide on your own whether to leave it as it is or to configure the launch as services. For example, in our <a href="https://www.ita-labs.com/?utm_source=Medium&amp;utm_medium=Blogs&amp;utm_campain=tigr_part2_en">company</a>, we have set up InfluxDB and Grafana to be launched as services, and Telegraf as a common application.</p><p>We will not expatiate upon the InfluxDB configuration parameters either — there are lots of them, but most of them will not be of use for us right now. Later on, we can change the port, authentication, logging, etc.</p><p>The executable file influx.exe is the command interface to InfluxDB, with which you can manage various databases and their data. We do not need it for the time being, but we will return to it if necessary.</p><h4>Telegraf</h4><p>Almost everything with Telegraf is just the same as it is with InfluxDB, but we will have to tweak the default settings in the configuration file <em>telegraf.conf</em> a little bit:</p><p>· <em>logfile</em> = “path to the folder and the file name for the log” — better to enter your own values;</p><p>· In the section <em>[outputs.influxdb]</em>:</p><p><em>urls</em> (correct to the real server address where InfluxDB is installed);</p><p><em>database</em> — database name (specify any, but if it is not set, a database with a default name is created automatically);</p><p>Next, the file contains the list of Windows Performance Counters — you can leave the values as they are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-xVjwP14LSuByiW65TLwA.png" /></figure><p>Run:</p><p><em>telegraf.exe -config telegraf.conf</em> — and let it collect the metrics for the time being (Windows Performance Counters), but we will go on.</p><h4>Grafana</h4><p>In this case, it is even simpler and more difficult at the same time — we can right away run:</p><p><em>grafana-server.exe</em></p><p>and follow the link <a href="http://localhost:3000/"><em>http://localhost:3000</em></a> (login: password — admin: admin, the host name should be replaced with the real one if you log in with Grafana not locally).</p><p>The further dashboards configuration and metrics display are all that is difficult here. In this part of the article, we will just run a ready dashboard to comprehend how it works. So, there is nothing difficult for now.</p><p>After we log in to Grafana, the first thing to do is to create a data source:</p><p>· Source name (any), type — InfluxDB, URL in our example — <a href="http://localhost/"><em>http://localhost:</em></a><em> 8086</em> (should be replaced with your own if InfluxDB is not installed locally but on some other port);</p><p>· Access type — commonly Proxy (we have talked about these types above);</p><p>· If authentication is set up in InfluxDB (initially it is not), you also have to specify the required user credentials;</p><p>· Database name (see configuration file for Telegraf), time interval — 10 seconds.</p><p>That will do for now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXcZuy3ACQjJVMAuFm7GPw.png" /></figure><p>Next, you have to download the ready dashboard template (you will have time to create your own one later on, but for now, it is better to use an example) — <a href="https://grafana.com/dashboards/1902">https://grafana.com/dashboards/1902</a></p><p>Dashboards come as files with the json extension. Hence, they contain the usual json data.</p><p>The package (on the dashboard page) also contains a configuration file for Telegraf: you can compare it with your own and correct points that differ or replace your file with the one from the package (do not forget to correct the parameters mentioned above in the chapter about Telegraf launching).</p><p>After that, we have to import the downloaded json file into Grafana, specify the dashboard name, and select the data source (we have already created it above):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kn9LaBQr_aBVBCrVunQ_HA.png" /></figure><p>Unfortunately, not all panels from this template will work at once — some of them will return the “No data points” message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfqGaIgfCPgxjU2ytGQ83A.png" /></figure><p>We will have to get in the settings of the problem panels and change the host to <em>/^server$/</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51aFD6Zx-9S8vvdECeR4OQ.png" /></figure><p>Then, everything will operate as it should:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXya89Ld2R4QZIIUZR-qkQ.png" /></figure><p>In the upper right corner, we can flexibly adjust the display time and the data refresh rate.</p><p>Now, we can observe how the charts are drawn and do something on the server where Telegraf is running, just for a change. To get a better feel of Grafana, we can “play” with various settings and parameters right on the test dashboard.</p><h4>Summary</h4><p>In the second part of our article, we had a closer look at the TIGeR components architecture and also explained how to install and set them up in their basic configuration.</p><p>Next, in the third part of the article, we will set up Telegraf to read specific Windows Perf Counters for our product, apply the load to the tested server (i.e. “feed the TIGeR”), learn how to display the values returned by the counters in Grafana, and also consider some Grafana’s fine tuning-issues relating to visualization and notifications (first “TIGeR training”).</p><h4>Links</h4><p><a href="https://medium.com/italabs/tiger-performance-part1-en-a3c56972c355">TIGeR on guard for performance — Part 1</a></p><p><em>Author: Eugene Klimov, System Engineer, </em><a href="https://www.ita-labs.com/?utm_source=Medium&amp;utm_medium=Blogs&amp;utm_campaign=tigr_part2_en"><em>ITA Labs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=140008c250e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/italabs/tiger-performance-part2-en-140008c250e2">TIGeR on guard for performance — Part 2</a> was originally published in <a href="https://medium.com/italabs">ITA Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TIGeR on guard for performance — Part 1]]></title>
            <link>https://medium.com/italabs/tiger-performance-part1-en-a3c56972c355?source=rss-48122f8e28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3c56972c355</guid>
            <category><![CDATA[italabs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[stories]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Lisa Botty]]></dc:creator>
            <pubDate>Wed, 17 Oct 2018 16:01:02 GMT</pubDate>
            <atom:updated>2019-02-01T09:22:12.120Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>TIGeR on guard for performance — Part 1</strong></h3><h4>Introduction</h4><p>In this round of publications consisting of several parts, we will tell you about how we looked for, researched, and implemented the solution helping us keep ourselves up to date with the current situation regarding our products performance.</p><p>Part after part, step by step, from theory to practice — we will show you what issues we have encountered and how we have solved them.</p><p>Having read all the parts of this publication, you will apprehend why we actually need it, why we have chosen this method, and, having studied this practical example, you will be able to easily use it for your products.</p><h4><strong>Part 1. How we have traced that fairy-tale beast</strong></h4><h4>What kinds of performance testing exist</h4><p>To start with, let us recall all the existing methods used to test performance:</p><p>1. <strong>Load testing </strong>is the main type of testing used to measure various server parameters when supplying a load from a loading tool mimicking the client work.</p><p>2. <strong>Stress testing</strong> loads the system using its maximum resources and removes the load afterwards to find out whether the tested system is capable of recovering.</p><p>3. <strong>Testing with a large bulk of data </strong>presumes the preliminary or simultaneous generation of as much data as system resources can handle and the subsequent metrics recording. To some extent, it is a subtype of tests mentioned above but they are usually subdivided.</p><p>4. <strong>Stability testing</strong> is the longest one aiming at identifying various resource leaks and performance degradation at moderate loads but for a longer period of time.</p><p>5. <strong>Scalability testing</strong> is necessary to find out whether the productivity will increase with a larger number of resources, and if it will, what the proportion will be.</p><p>6. <strong>Configuration testing</strong> is checking the product functionality on various equipment configurations, test rigs, etc.</p><p>A visual representation of all the above-mentioned types is shown in this diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*_U71MyuqzmkDKy4PNXyWnQ.png" /></figure><p>In this article, we will only delve into the type I (load) testing, but you can equally apply this publication material and the methods described for other types of testing.</p><p>Load testing also presumes two methods of conducting it:</p><p>1. <strong>Manual testing</strong> is usually long, sometimes even expensive, but it provides more or less absolute numbers of load metrics.</p><p>2. <strong>Automatic testing</strong> is aimed at identifying the dynamic pattern in selected metrics after some modifications in the product logic were made. What we mean is we only have to compare the current figures with the figures obtained when previous product versions were tested.</p><h4>Why it is necessary to test performance</h4><p>Our company <a href="https://www.ita-labs.com/?utm_source=Medium&amp;utm_medium=Blogs&amp;utm_campain=tigr_part1_en">ITA Labs</a> is committed to this wording:</p><p>“You have to test performance to comprehend to what extent a specific product meets expectations (both customers’ and ours) and identify possible issues associated with it.”</p><p>Performance testing often deals with potential issues not just in the product code but also in software configuration, hardware, and other problems.</p><h4>Why we need it</h4><p>First of all, we have to determine the components of which the initial data consists to set the objective:</p><p>1. We have a client-server product (hereinafter referred to as the “product”), and we have to test how the server end handles the client load.</p><p>2. We have clients for this product who keep asking a reasonable question, “How many clients (users) will it be able to service simultaneously within a single node of a high-availability cluster? We need a clear and preferably some standardized report on performance tests — HPLoadRunner, for example…”</p><p>3. Our company <a href="https://www.ita-labs.com/?utm_source=Medium&amp;utm_medium=Blogs&amp;utm_campain=tigr_part1_en">ITA Labs</a> has set a task to periodically test our components and check if any performance degradation takes place when we introduce this or that feature, or on the contrary, how much the performance increases after the specific optimization.</p><p>It usually takes testers a lot of time to conduct such tests, the reports look complicated and messy, and consequently, they are incomprehensible to customers. Moreover, it will not be right to skip such tests because we can get absolute figures (i.e., deliver the maximum load on powerful stands) and then show them to our clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*jRF7pVr_pAitAIUIKlLRDA.png" /></figure><p>Now, we have a long-pending issue on our hands: how can we avoid occupying testers for too long but see the actual components performance rates more often. Obviously, we cannot get absolute figures when the objectives are set like this. Therefore, we started looking for a compromise.</p><h4>Stating the original objective</h4><p>So, we found a compromise. We were reasoning like this: since we cannot get actual and absolute performance figures on a regular basis, we will take our product of the specific build as a reference (reference point) for which these absolute figures are known, and then, we will simply compare all subsequent builds with it.</p><p>Actually, as a result, we will observe the product performance dynamic pattern according to the selected metrics — compare figures regardless of their absolute value. Thus, it (the dynamics) will show us at once which metrics go beyond acceptable limits and in which build. The data will be applicable for both performance losses and gains (when, for example, the code was optimized).</p><p>Moreover, to achieve this, we will use regular automatic performance test runs for each build, and see charts like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*UXGlxrgvvMk0D89Jc2R9LQ.png" /></figure><p>The chart itself represents one of the metrics or its derivative.</p><p>Across– the product build number, and up– the performance index. In our example –what maximum number of clients one server end of the product supports.</p><h4>Specifying the original objective</h4><p>You have probably noticed that one thing is missing in the objective statement –analysis and notifications automation. We will see charts, but it is inconvenient to retrieve them “manually” for each build.</p><p>That is why, let showing charts be a minimum objective, but we have to specify the maximum one:</p><p>1. A short performance testing according to predefined scenarios should automatically run for each product build.</p><p>2. The indicators change in components performance should be shown clearly according to the predetermined metrics.</p><p>3. If any performance losses or sharp gains take place, they should be automatically analyzed, and detailed warning messages should be displayed.</p><p>All this is done to either quickly fix the issue in the code, in technical specs, or somewhere else or define the solution which is currently optimal.</p><p>Our chart will now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*920sZWKmW9FTSQLHCy69WQ.png" /></figure><p>We added warning thresholds — all values beyond the lower and upper thresholds will warn that we experience a drastic change in a certain performance metric.</p><p>Sounds tempting, but what is in practice?</p><h4>Why HPLoadRunner was not good for us</h4><p>First, we earnestly took up <a href="http://www8.hp.com/sg/en/ad/load-runner/load-runner.html">HPLoadRunner</a> because its reports are considered to be an essential standard in testing serious products produced by serious companies.</p><p>We installed HPLoadRunner, configured its basic functionality, made several test runs for our tested website, and got a couple of reports — everything worked OK, so, the beginning was not bad.</p><p>After that, we were trying to achieve the main objective– emulate the load client. Our components are coded using .NET, and HPLoadRunner has a so-called “.NET Vuser” integrated, which, as it seemed to us, could “pretend” to be a real client if it was prepared for it beforehand, specifically, its operation script was recorded.</p><p>As we recorded this script, it turned out that our client-server exchange protocol or more precisely — the moment of client authentication, could not be emulated using “.NET Vuser”. The matter became even worse when we found out that the HP Company itself had no detailed documentation on that component.</p><p>When we finally realized that HPLoadRunner could not help us, we took a decision to have a look at other products designed to conduct performance testing, and what solutions other companies use for this purpose.</p><p>We will provide more details about our agony of choosing, but actually, we chose the simplest and, at the same time, most flexible and reliable solution approved by other testers (to be more precise, it was the basis for the solution because our products features and infrastructure imposed certain difficulties which we had to solve). What other tools, designed for performance testing, exist?</p><p>Now, let us talk about the promised agony of choosing in respect of tools and solutions.</p><p><a href="http://www8.hp.com/sg/en/ad/load-runner/load-runner.html">HPLoadRunner</a> — it was the first app we tested from among major professional industry solutions. In addition, the product is, in fact, the standard, as many clients know it and trust it. What can we say: reliable, complicated, and expensive.</p><p>The product is interesting, and perhaps, we will publish a separate article on it in future.</p><p><a href="https://jmeter.apache.org/">JMeter</a> — if we could compare HPLoadRunner with Windows in the world of Operating Systems, JMeter would be Linux in this case: powerful, free, flexible, but often needs various modifications (both in the JMeter itself and in the tested products).</p><p>JMeter currently almost keeps up with HPLoadRunner in its functionality, but we experienced the same problem with it –we could not emulate our client due to the client-server protocol specifics. JMeter has a support aimed at their own plug-ins development, but for our specific purpose, such a plug-in seemed to be complicated to implement.</p><p>Nevertheless, the product is interesting as well and deserves a dedicated article too.</p><p><a href="https://gatling.io/#/">Gatling</a> is a serious competitor to JMeter but without a GUI. However, it is considered to be one of the most powerful instruments. In addition, its test description language is among the standardized ones. With other features equal to JMeter, it provides a more productive socket module.</p><p>If we have an article on JMeter, it will necessarily contain a comparison to Gatling. However, as part of this article and for our product load testing purposes, it is not suitable for us because of the same reasons as both solutions mentioned above.</p><p><a href="https://gettaurus.org/">Taurus</a>, <a href="https://tech.yandex.ru/tank/">Yandex.Tank</a> are other similar solutions meant exclusively for website testing (but our components are not exactly websites, or they are not websites at all to be more precise). However, in their niche, these solutions celebrate a deservedly good reputation. Yandex uses “Tank” for its websites inclusive–admit it, it is a good advertising trick even as it is. Unfortunately, we have not been able to “fit” these solutions into our products yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-d9WaNXIxZoTpJ4Q80V8lA.png" /></figure><p>Then, we started looking towards the solutions, of which we learned from developers and testers at various forums, conferences, and just in casual publications.</p><p><a href="https://www.influxdata.com/">InfluxData</a> or <strong>TICK </strong>Stack (Telegraf, InfluxDB, Chronograf, and Kapacitor) was not originally meant for performance testing, but many developers quickly understood its advantage and utilize it for this purpose as well. It was primarily conceived as a solution used to monitor metrics deriving from various sources.</p><p>Note that it was the very TICK Stack which seriously influenced our final choice. Moreover, right at this stage of our research, we understood we had to choose the solution with the most complete support for Windows counters because our products actively use them.</p><p>There are also different kinds of agent bundles (Carbon, NetData, Node_Exporter, CollectD, Zabbix, Telegraf), databases (MySQL, ElasticSearch, Prometheus, InfluxDB), and visualization interfaces (the choice is smaller in this category — Chronograf, Kibana, Graphite, and Grafana which is actually over Graphite’s add-on). In most respects, the choice here depends on personal preferences because these agents actually compete with each other.</p><p>We also tried to understand what solutions other software companies use for automated testing. However, now, no one is eager to share their experience with others for some reason: either they are to that extent secretor there is nothing to share.</p><p>As a result, having researched and tried several different options and combinations of the solutions described above, we shaped up a certain preference that influenced our final choice.</p><h4>Why we chose TIGeR and what kind of beast it is</h4><p>As many of you have already guessed reading the article title, as well as descriptions of existing solutions, we have chosen “Tiger”, to be more specific: Telegraf + InfluxDB + Grafana = TIG(e)R</p><p>Let us briefly view the separate components included in this solution:</p><p>1. <a href="https://grafana.com/">Grafana</a> is a standalone web server designed to visualize data and all sorts of cyclic metrics.</p><p>It does not support its own database, but it is able to use various data sources (there is a built-in support for several sources which can be expanded using plug-ins). It is usually called simply “dashboard” because of the specific concept of allocating objects.</p><p>All the advantages can be simply described as follows: nice, flexible, simple, http-API, many plug-ins, and a great recognition among system administrators and testers. This product has recently shown the tendency of being used it in other different areas.</p><p>The entire scope of capabilities inherent to the platform is definitely the topic for a separate article or, possibly, for several ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tERRyvkUOD5t4zrgJIVW2A.png" /></figure><p>2. <a href="https://docs.influxdata.com/influxdb">InfluxDB</a> is the so-called “timeseries” database, meaning it specializes in storing time series and in handling them.</p><p>It ideally fitted in our chosen bundle: it is installed simply, an easy and fast solution which seamlessly integrates with the rest of the TIGeR bundle components, widely available and documented, and has http-API as well.</p><p>Therefore, our choice of this particular database was obvious and not long in coming.</p><p>3. <a href="https://docs.influxdata.com/telegraf">Telegraf</a> is an agent designed to collect various metrics from the system (in which it is installed), Windows in particular. It is implemented as a regular executable file with a separate configuration file responsible for tweaking all the logic of this agent’s operation.</p><p>The agent is simple and easy to use with abuilt-in support for multiple input metrics, including Windows counters (the most important feature for us as we marked above) and output data formats.It is expanded with plug-ins, fully supports InfluxDB as a metrics transfer database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*TVQCurMUlU_v-cjuz84TQQ.png" /></figure><p>All the three mentioned components are coded using the Go (Golang) programming language. This language is developed by the Google team, it is predicted to replace C (++), and it is specifically optimized for multithreading. You can find more details about it and about its other interesting features on its official <a href="https://golang.org/">website</a>.</p><p>All this is compatible with Windows, which is significant for our infrastructure, as we:</p><p>· are official Microsoft partners</p><p>· mainly work on the Microsoft technology stack</p><p>Nevertheless, you will probably never find someone who utilized the entire TIGeR bundle in the Windows environment, except the Telegraf agent perhaps. After all, the product is initially orientated for Linux, and that affects the way it is utilized.</p><p>All the three components are open source products (MIT license for Telegraf and InfluxDB, Apache license for Grafana).</p><p>Let us have a look at the TIGeR’s operation chart (here is the chart from the official <a href="https://www.influxdata.com/">InfluxData</a> website but redesigned to reflect our objective):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*BCtdNviOuHVa0D082dS0ew.png" /></figure><p>InfluxDB functions as the main link receiving data from Telegraf and transferring it to Grafana in a format comprehensible to all solution participants.</p><h4>Summary</h4><p>In the first part of the article, we analyzed why we need performance testing and why we need to test it automatically, and we also set the original objective.</p><p>Then, we showed the solution search process, and having analyzed the whole variety of products, we selected a specific bundle Telegraf + InfluxDB + Grafana = TIGeR</p><p>In the second part of the article, we will consider the bundle components architecture in more detail (“the TIGeR anatomy”), and we will also describe installation processes and ways to set the components up in their basic configuration (“cage the TIGeR”).</p><blockquote>Author: Eugene Klimov, System Engineer, <a href="https://www.ita-labs.com/?utm_source=Medium&amp;utm_medium=Blogs&amp;utm_campaign=tigr_part1_en">ITA Labs</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3c56972c355" width="1" height="1" alt=""><hr><p><a href="https://medium.com/italabs/tiger-performance-part1-en-a3c56972c355">TIGeR on guard for performance — Part 1</a> was originally published in <a href="https://medium.com/italabs">ITA Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого…]]></title>
            <link>https://medium.com/ita-labs/https-medium-com-ita-labs-aop-part4-dd97a14820b3?source=rss-48122f8e28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd97a14820b3</guid>
            <category><![CDATA[stories]]></category>
            <category><![CDATA[postsharp]]></category>
            <category><![CDATA[fody]]></category>
            <category><![CDATA[methodecorator]]></category>
            <category><![CDATA[aop]]></category>
            <dc:creator><![CDATA[Lisa Botty]]></dc:creator>
            <pubDate>Tue, 11 Sep 2018 07:01:01 GMT</pubDate>
            <atom:updated>2019-01-31T20:08:21.138Z</atom:updated>
            <content:encoded><![CDATA[<h3>Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого маститого вендора AOP — PostSharp. Часть 4</h3><h4>Внутреннее устройство плагинов Fody</h4><p>В <a href="https://medium.com/ita-labs/aop-part3-f86f8cc65584">предыдущей части статьи</a> мы рассмотрели возможности Fody и его плагина MethodDecorator. И сделали вывод о том, что их возможностей не хватает для того, чтобы покрыть все возможности, предоставляемые PostSharp.</p><p>Поэтому для полноценной замены нам пришлось вносить изменения в плагин Fody: MethodDecorator. Этот проект является open source и имеет MIT-лицензию, позволяющую использование модифицированных исходников в коммерческих проектах.</p><p>Прежде чем описать сделанные нами модификации, мы кратко обсудим архитектуру плагинов Fody, чтобы иметь общее представление о том, как эти модификации реализовывать.</p><p>На рисунке ниже продемонстрирована общая структура зависимостей Fody. Плагины используют базовые классы, определенные в библиотеке Fody. В свою очередь эти классы дают возможность модификации обрабатываемых сборок, предоставляя доступ к объектной модели сборки с помощью библиотеки Mono.Cecil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*2llqPp8vFkp5XUyD9H4PTQ.png" /></figure><p>В общих чертах, при обработке сборки Fody:</p><p>1. Загружает объектную модель обрабатываемой сборки, используя для этого библиотеку Mono.Cecil.</p><p>2. Загружает свои плагины согласно конфигурационному файлу <em>FodyWeavers.xml</em>.</p><p>3. Передает каждому плагину объектную модель Mono.Cecil для обработки.</p><p>4. Сохраняет модифицированную версию обрабатываемой сборки.</p><p>Стоит отметить, что если модифицируемая сборка подписана, то после таких модификаций, её необходимо заново подписать. Fody берёт на себя эту задачу и автоматически подписывает обработанные сборки, если в соответствующем проекте стоит настройка <em>SignAssembly </em>и указан корректный путь до ключа, которым подписывается сборка.</p><p>Теперь подробнее рассмотрим, что представляют собой плагины Fody.</p><h4>Устройство плагинов Fody</h4><p>Каждый плагин Fody — это отдельная .NET сборка, обязательно содержащая класс с названием <em>ModuleWeaver </em>в любом пространстве имен.</p><p>В процессе сборки Fody ищет сборки плагинов в соответствии с содержимым файла <em>FodyWeavers.xml</em>, формат которого был описан в предыдущей части статьи. При этом, если плагинов несколько, то модифицируемая сборка будет обрабатываться каждым плагином последовательно.</p><p>Класс <em>ModuleWeaver</em> должен наследоваться от класса <em>BaseModuleWeaver</em>, определенной в сборке <em>FodyHelpers</em>, которую нужно добавить как референс в проект плагина. Сделать это можно используя соответствующий NuGet-пакет: <a href="https://www.nuget.org/packages/FodyHelpers">https://www.nuget.org/packages/FodyHelpers</a>.</p><p>В самом классе <em>ModuleWeaver </em>достаточно переопределить два метода: <em>Execute</em> и <em>GetAssembliesForScanning.</em></p><p>Метод <em>Execute</em> должен содержать реализацию логики плагина.</p><p>Метод <em>GetAssembliesForScanning </em>должен возвращать названия сборок, содержащих типы, которые используются в генерируемом плагином коде. То есть, если в коде нам необходимо сгенерировать поле или переменную с типом <em>System.Object</em>, то это метод должен возвращать сборку <em>mscorlib</em>, где этот тип содержится.</p><p>Простейший пример реализации ModuleWeaver выглядит так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*5qvl-wMiajy_6HNuzxa5VA.png" /></figure><p>Данный код генерирует пустой класс внутри сборки, которая будет обработана этим плагином. Как видно, для этого используется некое свойство <em>ModuleDefinition</em>, определенное в классе <em>BaseModuleWeaver</em>, и тип <em>TypeDefinition</em>. Все эти классы представлены библиотекой Mono.Cecil, используемой плагинами Fody для генерации кода. Подробнее о её возможностях мы напишем ниже.</p><p>Официальной документации по тому, как писать плагины для Fody на данный момент не существует, но в репозитории Fody есть проект, содержащий пример проекта плагина: <a href="https://github.com/Fody/BasicFodyAddin">https://github.com/Fody/BasicFodyAddin</a>.</p><h4>Mono.Cecil</h4><p>Mono.Cecil — это библиотека с открытым исходным кодом, реализующая возможность модификации кода существующих .NET сборок.</p><p>Эта библиотека предоставляет достаточно интуитивную объектную модель сборки. Диаграмма классов этой модели изображена на рисунке ниже.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*cdvxuKurT4xJK0YXWABFfQ.png" /></figure><p>Здесь,</p><p>· <em>AssemblyDefinition</em> — метаданные сборки,</p><p>· <em>ModuleDefinition</em> — метаданные модуля сборки. Каждая сборка может содержать один или более модуль.</p><p>· <em>TypeDefinition</em> — метаданные типов сборки: классов, перечислений и т.п.</p><p>· <em>FieldDefinition</em> — метаданные полей внутри типов сборки.</p><p>· <em>PropertyDefinition</em> — метаданные свойств.</p><p>· <em>MethodDefinition</em> — метаданные методов.</p><p>Также мы можем работать с отдельными методами на более низком уровне, добавляя в них IL-инструкции с помощью вспомогательного класса <em>CilWorker</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*pCTKXKf3XrheNIc2Wmdbjw.png" /></figure><p>Fody предоставляет доступ к классу <em>ModuleDefinition</em> внутри класса <em>ModuleWeaver</em>, который соответствует главному модулю обрабатываемой сборки. Используя объектную модель Mono.Cecil потенциально мы можем вносить любые изменения в обрабатываемую сборки, например:</p><p>· Добавлять новые классы и типы;</p><p>· Генерировать новые методы;</p><p>· Модифицировать существующие методы, вплоть до полной замены их кода;</p><p>· И много других возможностей.</p><h4>Заключение</h4><p>Итак, мы вкратце рассмотрели, что представляют собой плагины Fody.</p><p>В общих чертах, для того, чтобы внести изменения в плагин MethodDecorator, нам необходимо найти класс <em>ModuleWeaver </em>внутри проекта плагина и внести необходимые нам изменения.</p><p>В этом классе Fody предоставляет нам доступ к объектной модели обрабатываемой сборки, которую мы можем модифицировать по своему усмотрению, используя все возможности библиотеки Mono.Cecil.</p><p>В следующей части статьи мы подробно рассмотрим все модификации, сделанные нами в плагине MethodDecorator.</p><h4>Ссылки</h4><ol><li><a href="https://spark.ru/startup/ita-labs/blog/38979/aspektno-orientirovannoe-programmirovanie-aop-ili-pochemu-mi-otkazalis-ot-ispolzovaniya-samogo-mastitogo-vendora-aop-postsharp-chast-1">Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого маститого вендора AOP — PostSharp. Часть 1</a></li><li><a href="https://spark.ru/startup/ita-labs/blog/39720/aspektno-orientirovannoe-programmirovanie-aop-ili-pochemu-mi-otkazalis-ot-ispolzovaniya-samogo-mastitogo-vendora-aop-postsharp-chast-2">Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого маститого вендора AOP — PostSharp. Часть 2</a></li><li><a href="https://medium.com/ita-labs/aop-part3-f86f8cc65584">Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого маститого вендора AOP — PostSharp. Часть 3</a></li></ol><p><em>Автор статьи: Марат Вильданов, разработчик, </em><a href="http://www.ita-labs.ru/?utm_source=Spark&amp;utm_medium=Blogs&amp;utm_campaign=aop_part4"><em>ITA Labs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd97a14820b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ita-labs/https-medium-com-ita-labs-aop-part4-dd97a14820b3">Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого…</a> was originally published in <a href="https://medium.com/ita-labs">ITA Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого…]]></title>
            <link>https://medium.com/ita-labs/aop-part3-f86f8cc65584?source=rss-48122f8e28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f86f8cc65584</guid>
            <category><![CDATA[postsharp]]></category>
            <category><![CDATA[fody]]></category>
            <category><![CDATA[aop]]></category>
            <category><![CDATA[methoddecorator]]></category>
            <category><![CDATA[stories]]></category>
            <dc:creator><![CDATA[Lisa Botty]]></dc:creator>
            <pubDate>Tue, 24 Jul 2018 07:01:01 GMT</pubDate>
            <atom:updated>2019-01-31T20:07:34.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого маститого вендора AOP — PostSharp. Часть 3</h3><h4>Описание Fody и MethodDecorator</h4><h3>Введение</h3><p>В <a href="https://spark.ru/startup/ita-labs/blog/39720/aspektno-orientirovannoe-programmirovanie-aop-ili-pochemu-mi-otkazalis-ot-ispolzovaniya-samogo-mastitogo-vendora-aop-postsharp-chast-2?utm_source=facebook.com&amp;utm_medium=social&amp;utm_campaign=prodolzhaem-publikatsiyu-tsikla-statey--posv">предыдущей</a> (второй) части статьи мы подробно рассмотрели те возможности PostSharp, которые используются в проектах <a href="http://www.ita-labs.ru/?utm_source=Spark&amp;utm_medium=Blogs&amp;utm_campaign=aop_part3">нашей компании</a>.</p><p>В этой части статьи мы подробно рассмотрим другой AOP-фреймворк — <a href="https://github.com/Fody/Fody">Fody</a>, которым мы решили заменить PostSharp. И попробуем ответить на вопрос, что мы приобретаем и что теряем при этом переходе.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*YzVnEUJPJWt3p3V2E7xgEg.png" /></figure><p>Одним из решающим для нас отличием от PostSharp было то, что Fody является бесплатным open source продуктом, использующим MIT-лицензию. Эта лицензия позволяет свободно использовать и модифицировать Fody и в закрытых коммерческих проектах.</p><h4>Fody и его плагины</h4><p>Fody, как и PostSharp, выполняет обработку сборок после их компиляции. Схематично, это изображено на рисунке ниже. Этот рисунок аналогичен рисунку для PostSharp, с тем лишь отличием, что PostSharp здесь заменен на Fody.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*uQ1uw4JIPD89b04wHozCow.png" /></figure><p>В отличие от PostSharp, который является монолитным продуктом со множеством реализованной функциональности, Fody является движком для постобработки сборок, так как сам по себе не реализует никакой логики, а лишь предоставляет API и инфраструктуру для её реализации.</p><p>Для реализации логики постобработки Fody использует плагины. Плагины, как правило, представляют собой отдельные проекты со своими лицензиями, и, как и Fody, выложенные на GitHub.</p><p>Перечислим наиболее примечательные, на наш взгляд, плагины:</p><p>· <a href="https://github.com/Fody/MethodDecorator">MethodDecorator</a>, на котором мы подробно остановимся чуть позже;</p><p>· <a href="https://github.com/Fody/PropertyChanged">PropertyChanged</a>, генерирует код для реализации интерфейса INotifyPropertyChanged;</p><p>· <a href="https://github.com/Dresel/MethodCache">MethodCache</a>, генерирует код, который кэширует результаты вызовов методов.</p><p>Помимо этих плагинов существует десятки других. Полный и актуальный список плагинов доступен на GitHub-странице Fody: <a href="https://github.com/Fody/Fody#addins-list">https://github.com/Fody/Fody#addins-list</a></p><h4>Использование Fody</h4><p>Для того, чтобы использовать Fody в своём проекте достаточно:</p><p>1. Добавить в проект <a href="https://www.nuget.org/packages/Fody/">NuGet-пакет</a> Fody.</p><p>2. Добавить в проект отдельные NuGet-пакеты необходимых плагинов.</p><p>3. Добавить в корневой каталог проекта или солюшена файл FodyWeavers.xml такого содержания:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*nvjS9QcOiJMSCuGd0BYYnA.png" /></figure><p>Где <em>WeaverName</em> — это название плагина.</p><p>После этого достаточно применить в исходных кодах проекта кастомные атрибуты, которые предоставляют плагины, к своим классам, и при следующей компиляции эти классы будут обработаны Fody.</p><h4>Возможности плагина MethodDecorator</h4><p>Как уже было сказано выше, Fody сам по себе не реализует никакой логики постобработки, а только обеспечивает передачу управления в в свои плагины.</p><p>Поэтому при замене PostSharp недостаточно рассматривать только Fody в отдельности, а необходимо еще подобрать и плагины, реализующие необходимую функциональность.</p><p>MethodDecorator — плагин Fody, реализующий функциональность, аналогичную аспекту <em>OnMethodBoundaryAspect у PostSharp</em>, а именно — добавление своей логики в начало и конец метода.</p><p>Для примера, приведем код уже знакомого нам атрибута <em>TraceAttribute</em>, адаптированного под MethodDecorator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*j_W8X4bLYOSJuXhSOf_ZLQ.png" /></figure><p>Сразу можно отметить, что в новой реализации <em>TraceAttribute</em> сохранены названия методов <em>OnEntry</em> и <em>OnExit</em>, и оба эти метода сохранили свою семантику.</p><p>Но на этом сходства заканчиваются. Отметим следующие различия:</p><p>1. Для сохранения имени метода используется отдельное поле <em>_methodName</em>, значение которого задается в новом методе <em>Init</em>, специфичным для MethodDecorator.</p><p>2. В сигнатурах методов OnEntry, OnExit нет параметров.</p><p>А теперь рассмотрим, какой код генерирует MethodDecorator для этого атрибута:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*cZJDWPCFRhAiM2CFJmbgDA.png" /></figure><p>Что можно отметить из приведенного фрагмента кода?</p><p>В целом, структура генерируемого кода внутри метода напоминает то, что генерирует PostSharp. Но важное отличие от PostSharp состоит в том, что на каждый вызов метода теперь будет создаваться отдельный экземпляр аспекта. При этом применяется механизм reflection, при использовании которого всегда возникают вопросы о производительности. В данном случае, если бы этот метод использовался внутри гигантского цикла, то по сравнению с PostSharp, его производительность ухудшилась бы на порядки.</p><p>Преимуществом такого подхода можно было бы назвать отсутствие необходимости думать о многопоточности при реализации аспекта. В частности, при реализации аспекта можно свободно использовать поля класса для сохранения состояния между вызовами методов <em>Init</em>, <em>OnEntry</em>, <em>OnException</em>. Но при переносе кода адаптированного под PostSharp, где проблемы с многопоточностью уже решены, это не является преимуществом.</p><p>Подводя итог, в целом, описанная выше функциональность и является единственной возможностью MethodDecorator. И хотя она позволяет реализовать аспекты, сделанные на основе <em>OnMethodBoundaryAspect </em>из PostSharp, при этом необходимо учитывать разницу в генерируемом коде и то, как она может сказаться на производительности приложения.</p><h4>Другие возможности Fody+MethodDecorator?</h4><p>Если вспомнить предыдущую часть статьи, помимо <em>OnMethodBoundaryAspect </em>в наших проектах используются и атрибуты, сделанные на основе аспекта <em>MethodInterceptionAspect</em>. Плюс код некоторых аспектов опирался на уникальную возможность PostSharp: <em>инициализацию аспектов во время компиляции через метод</em>.</p><p>Если подобная функциональность в плагинах Fody? Ответ: нет.</p><p>Для наглядности, приведем табличку, где приведем используемые нами возможности PostSharp и их аналоги в Fody (если они есть):</p><p><strong>Возможности PostSharp и аналог в Fody</strong></p><ol><li>Аспект <em>OnMethodBoundaryAspect — </em>Аналог в Fody: реализовано плагином <em>MethodDecorator</em></li></ol><p>2. Возможность инициализации на этапе билда (метод <em>CompileTimeInitialize</em>) — Аналога в Fody нет</p><p>3. Аспект <em>MethodInterceptionAspect — </em>Аналога в Fody нет</p><p>Поэтому при переходе на Fody встает вопрос и о том, каким образом заменить данную функциональность из PostSharp?</p><h4>Что дальше?</h4><p>При прочтении данной статьи может сложиться впечатление, что перспективы перехода с PostSharp на Fody выглядят сомнительными. Fody не только не покрывает используемые нами возможности PostSharp, но и делает это хуже для аналогичной функциональности.</p><p>Но, и Fody, и MethodDecorator являются продуктами с открытым исходным кодом, поэтому при необходимости их можно довести до ума своими руками, чем мы и занялись.</p><p>Перед нами, прежде всего, встали такие проблемы:</p><p>1. «Научить» MethodDecorator генерировать более оптимальный, с точки зрения производительности, код, аналогично PostSharp.</p><p>2. Придумать, как сделать альтернативу <em>MethodInterceptionAspect </em>для Fody.</p><p>В следующей части мы подробно рассмотрим, как реализованы плагины для Fody, заглянем под «капот» плагина MethodDecorator и продемонстрируем решение указанных выше проблем.</p><h4>Ссылки</h4><ol><li><a href="https://spark.ru/startup/ita-labs/blog/38979/aspektno-orientirovannoe-programmirovanie-aop-ili-pochemu-mi-otkazalis-ot-ispolzovaniya-samogo-mastitogo-vendora-aop-postsharp-chast-1">Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого маститого вендора AOP — PostSharp. Часть 1</a></li><li><a href="https://spark.ru/startup/ita-labs/blog/39720/aspektno-orientirovannoe-programmirovanie-aop-ili-pochemu-mi-otkazalis-ot-ispolzovaniya-samogo-mastitogo-vendora-aop-postsharp-chast-2">Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого маститого вендора AOP — PostSharp. Часть 2</a></li></ol><p><em>Автор статьи: Марат Вильданов, разработчик, </em><a href="http://www.ita-labs.ru/?utm_source=Spark&amp;utm_medium=Blogs&amp;utm_campaign=aop_part3"><em>ITA Labs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f86f8cc65584" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ita-labs/aop-part3-f86f8cc65584">Аспектно-ориентированное программирование (AOP) или почему мы отказались от использования самого…</a> was originally published in <a href="https://medium.com/ita-labs">ITA Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TIGr на страже производительности - часть 3]]></title>
            <link>https://medium.com/ita-labs/tigr-performance-part3-9fbcd9eb9cdd?source=rss-48122f8e28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fbcd9eb9cdd</guid>
            <category><![CDATA[influxdb]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[stories]]></category>
            <category><![CDATA[italabs]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Lisa Botty]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 07:01:01 GMT</pubDate>
            <atom:updated>2019-01-31T20:06:25.260Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>TIGr на страже производительности — часть 3</strong></h3><h3>Введение</h3><p>В <a href="https://medium.com/ita-labs/tigr-performance-part2-dbb04fba3fec">предыдущей</a> (второй) части статьи мы более подробно рассмотрели архитектуру компонентов TIGr-а, а также рассказали, как их устанавливать и настраивать в базовой конфигурации.</p><p>В этой части (третьей) мы опишем настройку Telegraf на чтение специфических Windows-счетчиков (Perf Counters) нашего продукта, подадим нагрузку на тестируемый сервер (будем «кормить Тигра»), покажем, как отображать показания этих счетчиков в Grafana, а также рассмотрим некоторые вопросы настройки Grafana в части визуализации, переменных и уведомлений (начнем «дрессировку Тигра»).</p><h4>Часть 3. Приручаем TIGr-а</h4><h4>Кормим TIGr-а (подача нагрузки)</h4><p>Прежде всего, уточним, что InfluxDB, как и серверная часть Grafana, уже должны к этому времени быть запущенными и работать (например, они у нас выделены на отдельный сервер, где всегда запущены).</p><p>Для нашего тестового продукта мы используем нагрузочный клиент, который был создан нами специально для этих целей. У вас наверняка будут свои варианты подачи нагрузки (специализированные инструменты), но в любом случае — снимать метрики будем со счетчиков Windows:</p><p>· Счетчики, которые наш продукт создает при установке (ими у нас покрыты все важные места кода)</p><p>· Системные счетчики (CPU, Memory, Disk и т.д.) — опционально, в зависимости от задач.</p><p>Теперь надо определиться со счетчиками, с которых необходимо снимать метрики. Базовые системные уже есть в нашей конфигурации (мы их оставим), просто добавим свои. Для этого, в самый конец файла конфигурации Telegraf-а нужно вставить следующие строки:</p><p><em>[[inputs.win_perf_counters.object]]</em></p><p><em># Имя вашего продукта</em></p><p><em>ObjectName = “</em><strong><em>Test Engine — ClientManager</em></strong><em>”</em></p><p><em>Instances = [“</em><strong><em>default</em></strong><em>”]</em></p><p><em>Counters = [</em></p><p><strong><em>“Имя счетчика 1</em></strong><em>”,</em></p><p><strong><em>“Имя счетчика 2</em></strong><em>”,</em></p><p><strong><em>“Имя счетчика …</em></strong><em>”</em></p><p><em>]</em></p><p><em>Measurement = “</em><strong><em>Test_CM</em></strong><em>”</em></p><p><em>FailOnMissing = </em><strong><em>true</em></strong></p><p>Жирным шрифтом выделены места, которые необходимо поменять на свои варианты:</p><p>· <strong><em>Test Engine — ClientManager </em></strong>и<strong><em> Имя счетчика … — </em></strong>имя категории и непосредственно счетчиков, их можно посмотреть при добавлении в оснастке Системного монитора Windows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*wkwyuUHuFMDJpqZh0wJ07g.png" /></figure><p>· <strong><em>default </em></strong>— имя экземпляра выбранного объекта (счетчика), пример видно на скриншоте выше</p><p>· <strong><em>Test_CM </em></strong>— имя сбора или прогона, фактически — это таблица, куда будут записываться данные (мы это разбирали на схеме InfluxDB во второй части статьи)</p><p>· <em>FailOnMissing = </em><strong><em>true </em></strong>— отладочный параметр (потом его можно убрать или поставить <strong><em>false</em></strong>), прерывает запуск Telegraf-а, если возникли проблемы с поиском каких-то счетчиков при своем запуске.</p><p>В противном случае, агент запустится, но не будет собирать такие «проблемные» счетчики, соответственно, ничего не будет отображается в Grafana, что может сбивать с толку — это нагрузки нет, не работает счетчик или что-то случилось с Telegraf-ом.</p><p>Сейчас, для упрощения понимания, мы рассматриваем пример с одним нагрузочным сценарием на один прогон автотестов. В «боевом» тестировании, сценариев в одном прогоне может быть и больше (например, «Напряженное рабочее утро», «Спокойный выходной день» и т.д.). Поэтому, в таких случаях для каждого сценария надо как-то разделять поток данных, чтобы <strong>в рамках одного прогона можно было различать тестируемые сценарии при визуализации в Grafana (это очень важный момент, по нашему мнению)</strong>.</p><p>Это можно сделать, например, с помощью:</p><p>· добавления определенных тэгов в секцию [global_tags] конфигурации агента Telegraf, чтобы потом группировать по ним на графиках:</p><p><em>[global_tags]</em></p><p><em>scenario = “morning”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*vPHNRBkkJbeUJTOAJnU8_A.png" /></figure><p>· либо сменой имени Measurement-а (таблицы) там же, в конфигурации агента, а затем фильтровать по этим параметрам при построении графиков:</p><p><em>Measurement = “Test_CM_Morning”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*CpvR6BO1oW6bLrNoLRKMNQ.png" /></figure><p>Подробнее, мы затронем эту тему в следующих частях статьи, когда начнем автоматизировать сбор данных с учетом номеров сборок продукта (билдов).</p><p>Теперь пора подавать нагрузку (у себя мы запускаем наш нагрузочный клиент, про который было сказано в самом начале этой части статьи) и уже после этого можно стартовать агент Telegraf. Если делать наоборот, то некоторое время будут идти нулевые данные, что может «портить» итоговый график. С другой стороны, может быть и сценарий, когда важно «захватить» момент старта нагрузки, поэтому оба варианта запуска могут быть полезны.</p><p>Схемы последовательности старта компонентов TIGr-а, в общем случае, выглядят так:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*FQD9im5kbjkQILYyXPOMzA.png" /></figure><p>Пока идет нагрузка и собираются данные, пора немного донастроить наш тестовый дашборд в Grafana:</p><p>· добавляем новую панель типа «Graph» и заходим в ее настройки</p><p>· выбираем Data Source (у нас это <em>Perf_DB</em>, мы создавали его выше)</p><p>· ниже, в конструкторе запросов, указываем <em>FROM default Test_CM SELECT field (имя счетчика)</em></p><p>· аналогично, в этом же конструкторе можно добавлять и другие счетчики (кнопка Add Query)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fe2SQDp-oCJjRa3RH4DyQA.png" /></figure><p>После этого возвращаемся к дашборду:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*syeuwK-oFTf1igXj3uLacw.png" /></figure><p>По минимуму — этого уже достаточно, чтобы увидеть общую картину (в примере на скриншотах выше — два тестовых прогона нагрузки с двумя графиками двух счетчиков).</p><p>Но, как это обычно бывает — приходится еще что-то настраивать под свои конкретные задачи (в первой части статьи мы как раз поставили их на своем примере), и теперь займемся доработками.</p><h4>Дрессируем TIGr-а (визуализация, переменные и алерты)</h4><p>Давайте начнем с алертов (alert) — это предупреждения, отправляемые по заранее настроенному транспорту (в Grafana — это каналы), которые генерируются по определенному триггеру. Каналов достаточно:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*_b2M1VHBcWgySwEo0yNGFA.png" /></figure><p>Почта, мессенджеры, webhook и др., все рассматривать сейчас не будем — там все просто, а в нашем тестовом примере уведомления настроены на почту, при этом отметим, что параметры SMTP устанавливаются в конфигурационном файле Grafana — <em>defaults.ini</em></p><p>Рассмотрим пример — присылать нам письмо, если загрузка процессора на сервере с тестовым продуктом превысила 50% в определенный промежуток времени.</p><p>Заходим в свойство панели «CPU Usage» на нашем тестовом дашборде, вкладка Alert и создаем правило:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZpPsysUE6ChVfqfJAd1cw.png" /></figure><p>Стрелками показано, что изменено из дефолтных значений:</p><p>· установлено пороговое значение <em>50 </em>(%, как у вертикальной шкалы графика)</p><p>· в выражении <em>query(A,5m,now)</em> — <em>5m</em> заменено на <em>1m,</em></p><p>здесь <em>А</em> — порядковый номер запроса из конструктора (отображается в конструкторе, на вкладке «Metrics», рядом с запросами)</p><p><em>5m (1m)</em> и <em>now</em> — просматривать период от текущего времени до минус 5-ти (1-й) минут(ы) назад.</p><p>В итоге, согласно настройкам, мы должны получать алерты на почту, если в каждый такой промежуток времени (между текущим и минус одна минута) среднее значение (<em>avg</em>) всех результатов запроса «А» (в этой панели для CPU он там один) будет превышать 50%.</p><p>Проще говоря: подали нагрузку, прошла одна минута, если средняя загрузка CPU в эту минуту была выше 50%, то придет письмо. И так каждую минуту — алерт либо будет, либо нет. Это, конечно же, только пример, в реальности с такими настройками нас может «засыпать» письмами (если CPU загружен, как это часто бывает в тестах), поэтому настройки надо подбирать опытным путем, исходя из своих требований к уведомлениям.</p><p>С остальными параметрами алертов разобраться не сложно, поэтому их описывать не будем.</p><p>На практике получается так: подаем нагрузку на процессор рабочей станции (где установлен агент Telegraf), чтобы было периодически более 50% и скоро на почту получим письмо с темой «[Alerting] Cpu Usage alert», в которое приложен снимок графика, в интервале которого сработал этот алерт:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*Z1tMXtucsUc616qfX1wWCw.png" /></figure><p>Вертикальная красная прерывистая линия — здесь сработал алерт, горизонтальная — пороговое значение алерта (в нашем примере — 50%).</p><p><strong>Важный момент:</strong> в конструкторе запроса метрик не должно быть переменных (типа <em>/^server$/ или $server</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*P-4n6Y6mp4fOlfVt-NUW7A.png" /></figure><p>Иначе алерты работать не будут, т.к. в подсистеме запросов для алертов использование переменных в метриках не поддерживается:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*Y7e8aMJ-EPTw0A5-FOHkTw.png" /></figure><p>На эту проблему или недоработку есть очень много жалоб в официальном багтрекере (например, <a href="https://github.com/grafana/grafana/issues/6557">здесь</a>), но до сих пор разработчики никак её не исправят или не реализуют (официально про это ограничение <a href="http://docs.grafana.org/alerting/rules/">здесь</a>).</p><p>Во многих сценариях это делает неудобной настройку алертов, т.е. придется либо отказаться от них в данном графике сбора метрик, либо не использовать переменные. Например, если мы захотим удобно фильтровать данные и графики на дашборде по номерам сборок (билдов):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YnpaEyVhj3cVZBEtiuqN_w.png" /></figure><p>То надо использовать переменную, например «<em>Build</em>»:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*YXKNnnSBhFUabF7isHKYEQ.png" /></figure><p>Теперь, если мы захотим добавить алерт на этот график, то нам будет выдано сообщение, что «Template variables are not supported in alert queries» (пример есть на скриншоте чуть выше).</p><p>Немного про переменные в Grafana. Они предназначены для настройки отображения панелей и других единиц визуализации дашборда по заранее определенным фильтрам, например: источник данных, имя станции, диска или сетевого адаптера, номер сборки продукта и многое другое. Их область действия ограничена только своим дашбордом. Подробнее про переменные можно почитать в официальной <a href="http://docs.grafana.org/reference/templating/">документации</a>.</p><p>Управление переменными находится в настройках дашборда:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OQPPf7o7hg340EkN4kV3g.png" /></figure><p>Здесь мы можем создавать переменные разных типов:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*aDV6jj6ptmh6m56nq6S22Q.png" /></figure><p>В показанном примере мы получаем из тегов результатов запросов: имя сервера, букву диска, имя адаптера и номер сборки продукта. Затем, эти переменные можно использовать в конструкторе запросов метрик, а также при фильтрации данных дашборда (см. несколько скриншотов выше на примере переменной «<em>Build</em>»).</p><p>В конце этой части статьи, хотелось бы еще уточнить, какие в Grafana есть панели, таблицы и другие блоки отображения данных, которые можно добавлять на дашборд:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*lzK1plY1WS8eoXATgVm9OA.png" /></figure><p>На самом деле их гораздо больше, чем показано на скриншоте, т.к. этот функционал Grafana расширяется плагинами, полный список есть <a href="https://grafana.com/plugins?type=panel">здесь</a>.</p><p>Каждую панель можно гибко настраивать под разную логику отображения данных. Мы еще к этому вернемся, когда рассмотрим пример расчета количества поддерживаемых «виртуальных клиентов» нашего тестового продукта в следующих частях статьи, при автоматизации нагрузочных автотестов.</p><p>В качестве домашнего задания, попробуйте «поиграться» со встроенными панелями: добавлять и настраивать их под свои задачи и предпочтения. Посмотреть множество образцов различных типов дашбордов и панелей, а также «поиграться» с их настройками можно и на <a href="https://play.grafana.org/">демо-портале</a> Grafana.</p><h4>Итоги</h4><p>В третьей части статьи мы описали настройку Telegraf на чтение определенных счетчиков нашего продукта, с помощью нагрузочного клиента подали нагрузку на тестируемый сервер, продемонстрировали отображение показаний этих счетчиков в Grafana, а также рассмотрели некоторые вопросы настройки Grafana в части визуализации, переменных и уведомлений.</p><p>Далее, в четвертой части, мы начнем автоматизировать работу компонентов TIGr-а с подключением сервера автоматизации тестов («учить TIGr-а выступать самостоятельно»), а также произведем конфигурирование Telegraf и Grafana с целью наглядной демонстрации динамики производительности нашего тестового продукта, как в различных сценариях прогона тестов, так и при каждой сборке («Наблюдать за успехами TIGr-а»).</p><h4>Ссылки</h4><p><a href="https://medium.com/ita-labs/https-medium-com-ita-labs-tigr-performance-part1-fa5e70a96bfb">TIGr на страже производительности — часть 1</a></p><p><a href="https://medium.com/ita-labs/tigr-performance-part2-dbb04fba3fec">TIGr на страже производительности — часть 2</a></p><p><em>Автор статьи: Евгений Климов, Системный инженер, </em><a href="https://www.ita-labs.ru/?utm_source=Medium&amp;utm_medium=Blogs&amp;utm_campaign=tigr_part3"><em>ITA Labs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fbcd9eb9cdd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ita-labs/tigr-performance-part3-9fbcd9eb9cdd">TIGr на страже производительности - часть 3</a> was originally published in <a href="https://medium.com/ita-labs">ITA Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>