Solr i Open Tracing

Wraz z wydaniem Solr w wersji 8.2 dostaliśmy w nasze ręce wsparcie dla Open Tracing. Niezależne od dostawców API dostarczające możliwości dodania rozproszonego tracingu do naszej aplikacji. Ważne jest także to, iż nie jesteśmy związani z żadnym szczególnym dostawcą, czy rozwiązaniem – w tej chwili jest kilka rozwiązań open-source oraz tych komercyjnych, więc jest w czym wybierać. Spójrzmy zatem jak skonfigurować Solr, aby skorzystać z Open Tracing.

Na początek

Na potrzebny tego wpisu przygotowałem sobie klaster SolrCloud zbudowany z dwóch instancji Solr działających na tej samej maszynie. Nic skomplikowanego, ale na potrzeby tego wpisu jest wystarczające.

Open Tracing

Oczywiście, aby móc skorzystać z dobrodziejstw tracingu potrzebujemy miejsca, gdzie Solr będzie wysyłać dane, które zostaną wygenerowane przy pomocy API Open Tracing. W momencie pisania tego tekstu jedynym wspieranym domyśnie przez Solr rozwiązaniem jest Jaeger. Jest to rozwiązanie ze stajni CNCF, w pełni otwarte i darmowe. Dodanie innego dostawcy wspierającego API Open Tracing jest możliwe, ale nie jest to temat tego wpisu.

Do swoich testów wykorzystałem kontener Dockera jaegertracing/all-in-one w najnowszej wersji. Uruchomienie go jest proste i wystarczy do tego następujące polecenie:

$ docker run -d --name jaeger -p 16686:16686 -p 6831:6831/udp -p 5775:5775/udp jaegertracing/all-in-one:latest

Uruchomiliśmy kontener pod nazwą jaeger oraz przygotowaliśmy porty 16686, 6831 oraz 5775. Port 16686 będzie wykorzystywany do wyświetlenia UI Jaeger, natomiast port 5775 będzie wykorzystany jako port agenta, czyli tam gdzie będziemy wysyłać nasze dane wyprodukowane przez API Open Tracing.

Aby sprawdzić, czy kontener działa wystarczy następujące polecenie:

$ docker ps

Konfiguracja Solr z Open Tracing

Następną rzeczą jaką musimy zrobić to przygotowanie Solr. Na początek musimy przekopiować wszystkie biblioteki z katalogu contrib/jaegertracer-configurator/lib/ oraz bibliotekę jaegertracer-configurator-8.6.0.jar z katalogu dist i umieścić je w miejscu, gdzie Solr będzie je widzieć. W moim wypadku był to katalog lib w katalogu server/solr.

Musimy także zmodyfikować plik solr.xml który dostępny jest w katalogu server/solr. W tym pliku musimy dodać wpis konfigurujący odpowiednie elementy Solr. W większości wypadków plik ten nie będzie pusty, wystarczy więc dodać do niego następujący wpis:

<tracerConfig name="tracerConfig" class="org.apache.solr.jaeger.JaegerTracerConfigurator">
  <str name="agentHost">localhost</str>
  <int name="agentPort">5775</int>
  <bool name="logSpans">true</bool>
  <int name="flushInterval">1000</int>
  <int name="maxQueueSize">10000</int>
</tracerConfig>

Powyższa konfiguracja konfiguruje Jaeger. Stwierdzamy, iż nasz agent działa lokalnie – localhost i jest dostępny na porcie 5775. Dodatkowe opcje definiują czas wysyłania danych oraz wielkość kolejki.

Klaster testowy i dane

Po przygotowaniu naszych dwóch instancji w powyżej opisany sposób możemy je wreszcie uruchomić. Robimy to za pomocą następujących poleceń:

$ bin/solr start -c -f
$ bin/solr start -f -p 6883 -z localhost:9983

Uruchomiliśmy dwie instancje Solr. Pierwsza, oprócz samego Solr uruchamia Zookeepera, natomiast druga instancja łączy się do tego Zookeepera. Razem tworzą klaster testowy.

Przed stworzeniem kolekcji, której będziemy używać do testów zrobiłem jedną, dodatkową rzecz. Ustawiłem próbkowanie na 100%, co oznacza, iż wszystkie dane wyprodukowane przez API Open Tracing będą dostarczane do Jaegera. Aby to zrobić wystarczy ustawić właściwość klastra o nazwie samplePercentage na wartość 100. Ja zrobiłem to następującym poleceniem:

$ curl -XGET 'localhost:8983/solr/admin/collections?action=CLUSTERPROP&name=samplePercentage&val=100'

Oczywiście jest to ustawienie do testów. W przypadku produkcyjnego systemu, możemy nie chcieć trzymać 100% wszystkich danych ze względu ze względu na wielkość danych.

Następnie stworzyłem kolekcję o nazwie test z wykorzystaniem konfiguracji _default. Do wpisu nic więcej nie potrzeba. Sama kolekcja została stworzona przy pomocy następującego polecenia:

$ curl -XPOST -H 'Content-type:application/json' 'http://localhost:8983/api/c/'  -d '{ 
  "create": { 
    "name": "test",
    "numShards": "2"
  } 
}'

Następnie zaindeksowałem następujące dane:

$ curl -XPOST -H 'Content-type:application/json' 'localhost:8983/solr/test/update?commit=true' -d '[
 {
  "id": 1,
  "name": "Test document 1",
  "tags": [ "doc", "test" ]
 },
 {
  "id": 2,
  "name": "Test document 2",
  "tags": [ "doc", "test" ]
 },
 {
  "id": 3,
  "name": "Test document 3",
  "tags": [ "doc", "test" ]
 }
]'

Po czym zadałem proste zapytanie:

$ curl -XGET -H 'Content-type:application/json' 'localhost:8983/solr/test/select' -d '{
  "query" : "name:document",
  "facet": {
    "tags" : {
      "terms" : {
        "field" : "tags"
      }
    }
  }	
}'

Spójrzmy na dane

Po indeksowaniu oraz zadaniu zapytania powinniśmy mieć już jakieś dane dostępne w Jaeger. Aby to sprawdzić wystarczy otworzyć w przeglądarce adres localhost:16686 i wybrać solr z listy serwisów. Na przykład to pokazał Jaeger dla zapytania Solr:

Jeżeli potrzebujemy więcej danych sekcja tags może być pomocna:

I wszystko to dostępne po dodaniu kilku bibliotek oraz kawałka konfiguracji do Solr.

Krok dalej – tracing poza Solr

Oczywiście tracing uruchomiony tylko w ramach Solr to nie jest idealne rozwiżanie i chcielibyśmy mieć cały kod odpowiedniego przygotowany.

Na przykład, jeżeli mamy bardzo prostą aplikację odpytującą Solr możemy skorzystać z Open Tracing i samemu przygotować odpowiednie elementy typu span, które zostaną wysłane do Jaeger, tego samego, do którego wysyłane są dane z API Open Tracing w Solr. Przykładowy kod realizujący takie założenia może wyglądać następująco (cały projekt dostępny jest na Githubie):

public class App {
    private JaegerTracer tracer;
    private HttpSolrClient solrClient;

    public static void main(String[] args) throws Exception {
        App app = new App();
        app.initTracer();
        app.initSolrClient();
        app.start();
    }

    public void start() throws Exception {
        Span span = tracer.buildSpan("example query").start();

        final Map<String, String> query = new HashMap<>();
        query.put("q", "*:*");
        MapSolrParams queryParams = new MapSolrParams(query);

        final QueryResponse queryResponse = solrClient.query("test", queryParams);
        final SolrDocumentList documents = queryResponse.getResults();

        sleep(10);
        processDocumentsSlow(documents, span, 100);

        span.finish();
    }

    private void processDocumentsSlow(SolrDocumentList documents, Span rootSpan, long sleepTime) {
        Span span = tracer
            .buildSpan("process documents")
            .asChildOf(rootSpan)
            .start();

        processDocumentsSlowNext(documents, span, 300);
        sleep(sleepTime);

        span.finish();
    }

    private void processDocumentsSlowNext(SolrDocumentList documents, Span rootSpan, long sleepTime) {
        Span span = tracer
            .buildSpan("process documents next")
            .asChildOf(rootSpan)
            .start();

        sleep(sleepTime);

        span.finish();
    }

    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (Exception ex) {}
    }

    public void initTracer() {
        if (this.tracer == null) {
            Configuration.SamplerConfiguration samplerConfiguration = new Configuration
                .SamplerConfiguration()
                .withType(ConstSampler.TYPE)
                .withParam(1);

            Configuration.ReporterConfiguration reporterConfiguration = Configuration
                .ReporterConfiguration
                .fromEnv();

            Configuration.SenderConfiguration senderConfig = reporterConfiguration
                .getSenderConfiguration()
                .withAgentHost("localhost")
                .withAgentPort(5775);

            reporterConfiguration
                .withLogSpans(true)
                .withSender(senderConfig);

            Configuration configuration = new Configuration("Jaeger with Solr")
                .withSampler(samplerConfiguration)
                .withReporter(reporterConfiguration);

            this.tracer = configuration.getTracer();
        }
    }

    public void initSolrClient() {
        if (this.solrClient == null) {
            this.solrClient = new HttpSolrClient
                .Builder("http://localhost:8983/solr")
                .build();
        }
    }
}

Oprócz metody initTracer, która konfiguje Jaegera interesująca część kodu znajduje się w metodzie start. Tworzymy span, a następnie budujemy zapyatnie do Solr, wykonujemy je i pobieramy wyniki wyszukiwania. Następnie symulujemy opóźnienia wykonywania i wywołujemy metodę processDocumentsSlow, a w niej processDocumentsSlowNext. Każda z tym metod tworzy span oraz korzysta z metody asChildOf, aby poinformować, iż span jest częścią dłuższego wywołania logiki. To wszystko, w Jaeger, wygląda następująco:

W tym momencie mamy wgląd nie tylko w Solr, ale także w naszą aplikację.

Następne kroki

Cała siła rozproszonego tracingu widoczna jest wtedy, kiedy cały kod jest odpowiednio przygotowany, a my mamy możliwość śledzenia wywołań metod i funkcji oraz obserwacji z tym związanych. Open Tracing wspiera nie tylko język Java, ale także JavaScript, Go, Python, PHP, Objective-C, C++, C# i Ruby. A zatem jeżeli Twoja aplikacja korzysta z wymienionych języków instrumentalizacja kodu nie powinna być problemem.

Ważne jest także to, iż Open Tracing jest tylko zbiorem API, które nie jest związane z żadnym dostawcą, czy rozwiązaniem. Korzystając z API Open Tracing możemy wybrać dowolnego dostawcę lub rozwiązanie, które będzie dla nas odpowiednie, czy to komercyjne, czy w pełni otwarte. Warto o tym pomyśleć jeżeli chcemy dodać rozproszony tracing do naszej aplikacji i oprócz logów i metryk mieć także dostęp do tracingu.

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Wymagane pola są oznaczone *

We use cookies to personalise content and ads, to provide social media features and to analyse our traffic. We also share information about your use of our site with our social media, advertising and analytics partners.
Cookies settings
Accept
Privacy & Cookie policy
Privacy & Cookies policy
Cookie name Active

Privacy Policy

What information do we collect?

We collect information from you when you register on our site or place an order. When ordering or registering on our site, as appropriate, you may be asked to enter your: name, e-mail address or mailing address.

What do we use your information for?

Any of the information we collect from you may be used in one of the following ways: To personalize your experience (your information helps us to better respond to your individual needs) To improve our website (we continually strive to improve our website offerings based on the information and feedback we receive from you) To improve customer service (your information helps us to more effectively respond to your customer service requests and support needs) To process transactions Your information, whether public or private, will not be sold, exchanged, transferred, or given to any other company for any reason whatsoever, without your consent, other than for the express purpose of delivering the purchased product or service requested. To administer a contest, promotion, survey or other site feature To send periodic emails The email address you provide for order processing, will only be used to send you information and updates pertaining to your order.

How do we protect your information?

We implement a variety of security measures to maintain the safety of your personal information when you place an order or enter, submit, or access your personal information. We offer the use of a secure server. All supplied sensitive/credit information is transmitted via Secure Socket Layer (SSL) technology and then encrypted into our Payment gateway providers database only to be accessible by those authorized with special access rights to such systems, and are required to?keep the information confidential. After a transaction, your private information (credit cards, social security numbers, financials, etc.) will not be kept on file for more than 60 days.

Do we use cookies?

Yes (Cookies are small files that a site or its service provider transfers to your computers hard drive through your Web browser (if you allow) that enables the sites or service providers systems to recognize your browser and capture and remember certain information We use cookies to help us remember and process the items in your shopping cart, understand and save your preferences for future visits, keep track of advertisements and compile aggregate data about site traffic and site interaction so that we can offer better site experiences and tools in the future. We may contract with third-party service providers to assist us in better understanding our site visitors. These service providers are not permitted to use the information collected on our behalf except to help us conduct and improve our business. If you prefer, you can choose to have your computer warn you each time a cookie is being sent, or you can choose to turn off all cookies via your browser settings. Like most websites, if you turn your cookies off, some of our services may not function properly. However, you can still place orders by contacting customer service. Google Analytics We use Google Analytics on our sites for anonymous reporting of site usage and for advertising on the site. If you would like to opt-out of Google Analytics monitoring your behaviour on our sites please use this link (https://tools.google.com/dlpage/gaoptout/)

Do we disclose any information to outside parties?

We do not sell, trade, or otherwise transfer to outside parties your personally identifiable information. This does not include trusted third parties who assist us in operating our website, conducting our business, or servicing you, so long as those parties agree to keep this information confidential. We may also release your information when we believe release is appropriate to comply with the law, enforce our site policies, or protect ours or others rights, property, or safety. However, non-personally identifiable visitor information may be provided to other parties for marketing, advertising, or other uses.

Registration

The minimum information we need to register you is your name, email address and a password. We will ask you more questions for different services, including sales promotions. Unless we say otherwise, you have to answer all the registration questions. We may also ask some other, voluntary questions during registration for certain services (for example, professional networks) so we can gain a clearer understanding of who you are. This also allows us to personalise services for you. To assist us in our marketing, in addition to the data that you provide to us if you register, we may also obtain data from trusted third parties to help us understand what you might be interested in. This ‘profiling’ information is produced from a variety of sources, including publicly available data (such as the electoral roll) or from sources such as surveys and polls where you have given your permission for your data to be shared. You can choose not to have such data shared with the Guardian from these sources by logging into your account and changing the settings in the privacy section. After you have registered, and with your permission, we may send you emails we think may interest you. Newsletters may be personalised based on what you have been reading on theguardian.com. At any time you can decide not to receive these emails and will be able to ‘unsubscribe’. Logging in using social networking credentials If you log-in to our sites using a Facebook log-in, you are granting permission to Facebook to share your user details with us. This will include your name, email address, date of birth and location which will then be used to form a Guardian identity. You can also use your picture from Facebook as part of your profile. This will also allow us and Facebook to share your, networks, user ID and any other information you choose to share according to your Facebook account settings. If you remove the Guardian app from your Facebook settings, we will no longer have access to this information. If you log-in to our sites using a Google log-in, you grant permission to Google to share your user details with us. This will include your name, email address, date of birth, sex and location which we will then use to form a Guardian identity. You may use your picture from Google as part of your profile. This also allows us to share your networks, user ID and any other information you choose to share according to your Google account settings. If you remove the Guardian from your Google settings, we will no longer have access to this information. If you log-in to our sites using a twitter log-in, we receive your avatar (the small picture that appears next to your tweets) and twitter username.

Children’s Online Privacy Protection Act Compliance

We are in compliance with the requirements of COPPA (Childrens Online Privacy Protection Act), we do not collect any information from anyone under 13 years of age. Our website, products and services are all directed to people who are at least 13 years old or older.

Updating your personal information

We offer a ‘My details’ page (also known as Dashboard), where you can update your personal information at any time, and change your marketing preferences. You can get to this page from most pages on the site – simply click on the ‘My details’ link at the top of the screen when you are signed in.

Online Privacy Policy Only

This online privacy policy applies only to information collected through our website and not to information collected offline.

Your Consent

By using our site, you consent to our privacy policy.

Changes to our Privacy Policy

If we decide to change our privacy policy, we will post those changes on this page.
Save settings
Cookies settings